# -*- coding: utf-8 -*-
import theano
import theano.tensor as T
import numpy as np
from sklearn import datasets
import matplotlib.pyplot as plt
import time
#定义数据类型 np.random.seed(0)
train_X, train_y = datasets.make_moons(300, noise=0.20)
train_X = train_X.astype(np.float32)
train_y = train_y.astype(np.int32)
num_example=len(train_X) #设置参数
nn_input_dim=2 #输入神经元个数
nn_output_dim=2 #输出神经元个数
nn_hdim=100
#梯度下降参数
epsilon=0.01 #learning rate
reg_lambda=0.01 #正则化长度 #设置共享变量 w1=theano.shared(np.random.randn(nn_input_dim,nn_hdim),name="W1")
b1=theano.shared(np.zeros(nn_hdim),name="b1")
w2=theano.shared(np.random.randn(nn_hdim,nn_output_dim),name="W2")
b2=theano.shared(np.zeros(nn_output_dim),name="b2") #前馈算法
X=T.matrix('X') #double类型的矩阵
y=T.lvector('y') #int64类型的向量
z1=X.dot(w1)+b1
a1=T.tanh(z1)
z2=a1.dot(w2)+b2
y_hat=T.nnet.softmax(z2)
#正则化项
loss_reg=1./num_example * reg_lambda/2 * (T.sum(T.square(w1))+T.sum(T.square(w2)))
loss=T.nnet.categorical_crossentropy(y_hat,y).mean()+loss_reg
#预测结果
prediction=T.argmax(y_hat,axis=1) forword_prop=theano.function([X],y_hat)
calculate_loss=theano.function([X,y],loss)
predict=theano.function([X],prediction) #求导
dw2=T.grad(loss,w2)
db2=T.grad(loss,b2)
dw1=T.grad(loss,w1)
db1=T.grad(loss,b1) #更新值
gradient_step=theano.function(
[X,y],
updates=(
(w2,w2-epsilon*dw2),
(b2,b2-epsilon*db2),
(w1,w1-epsilon*dw1),
(b1,b1-epsilon*db1) )
) def build_model(num_passes=20000,print_loss=False): w1.set_value(np.random.randn(nn_input_dim, nn_hdim) / np.sqrt(nn_input_dim))
b1.set_value(np.zeros(nn_hdim))
w2.set_value(np.random.randn(nn_hdim, nn_output_dim) / np.sqrt(nn_hdim))
b2.set_value(np.zeros(nn_output_dim)) for i in xrange(0,num_passes):
gradient_step(train_X,train_y)
if print_loss and i%1000==0:
print "Loss after iteration %i: %f" %(i,calculate_loss(train_X,train_y))
def accuracy_rate():
predict_result=predict(train_X)
count=0;
for i in range(len(predict_result)):
realResult=train_y[i]
if(realResult==predict_result[i]):
count+=1
print "the correct rate is :%f" %(float(count)/len(predict_result)) def plot_decision_boundary(pred_func):
# Set min and max values and give it some padding
x_min, x_max = train_X[:, 0].min() - .5, train_X[:, 0].max() + .5
y_min, y_max = train_X[:, 1].min() - .5, train_X[:, 1].max() + .5
h = 0.01
# Generate a grid of points with distance h between them
xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h))
# Predict the function value for the whole gid
Z = pred_func(np.c_[xx.ravel(), yy.ravel()])
Z = Z.reshape(xx.shape)
# Plot the contour and training examples
plt.contourf(xx, yy, Z, cmap=plt.cm.Spectral)
plt.scatter(train_X[:, 0], train_X[:, 1], c=train_y, cmap=plt.cm.Spectral)
plt.show() build_model(print_loss=True)
accuracy_rate()
# # plot_decision_boundary(lambda x: predict(x))
# # plt.title("Decision Boundary for hidden layer size 3")
# -*- coding: utf-8 -*-
import theano
import theano.tensor as T
import numpy as np
from sklearn import datasets
import matplotlib.pyplot as plt
import time
#定义数据类型 np.random.seed(0)
train_X, train_y = datasets.make_moons(5000, noise=0.20)
train_y_onehot = np.eye(2)[train_y] #设置参数
num_example=len(train_X)
nn_input_dim=2 #输入神经元个数
nn_output_dim=2 #输出神经元个数
nn_hdim=1000
#梯度下降参数
epsilon=np.float32(0.01) #learning rate
reg_lambda=np.float32(0.01) #正则化长度 #设置共享变量
# GPU NOTE: Conversion to float32 to store them on the GPU!
X = theano.shared(train_X.astype('float32')) # initialized on the GPU
y = theano.shared(train_y_onehot.astype('float32'))
# GPU NOTE: Conversion to float32 to store them on the GPU!
w1 = theano.shared(np.random.randn(nn_input_dim, nn_hdim).astype('float32'), name='W1')
b1 = theano.shared(np.zeros(nn_hdim).astype('float32'), name='b1')
w2 = theano.shared(np.random.randn(nn_hdim, nn_output_dim).astype('float32'), name='W2')
b2 = theano.shared(np.zeros(nn_output_dim).astype('float32'), name='b2') #前馈算法
z1=X.dot(w1)+b1
a1=T.tanh(z1)
z2=a1.dot(w2)+b2
y_hat=T.nnet.softmax(z2)
#正则化项
loss_reg=1./num_example * reg_lambda/2 * (T.sum(T.square(w1))+T.sum(T.square(w2)))
loss=T.nnet.categorical_crossentropy(y_hat,y).mean()+loss_reg
#预测结果
prediction=T.argmax(y_hat,axis=1) forword_prop=theano.function([],y_hat)
calculate_loss=theano.function([],loss)
predict=theano.function([],prediction) #求导
dw2=T.grad(loss,w2)
db2=T.grad(loss,b2)
dw1=T.grad(loss,w1)
db1=T.grad(loss,b1) #更新值
gradient_step=theano.function(
[],
updates=(
(w2,w2-epsilon*dw2),
(b2,b2-epsilon*db2),
(w1,w1-epsilon*dw1),
(b1,b1-epsilon*db1) )
) def build_model(num_passes=20000,print_loss=False): w1.set_value((np.random.randn(nn_input_dim, nn_hdim) / np.sqrt(nn_input_dim)).astype('float32'))
b1.set_value(np.zeros(nn_hdim).astype('float32'))
w2.set_value((np.random.randn(nn_hdim, nn_output_dim) / np.sqrt(nn_hdim)).astype('float32'))
b2.set_value(np.zeros(nn_output_dim).astype('float32')) for i in xrange(0,num_passes):
start=time.time()
gradient_step()
end=time.time()
# print "time require:"
# print(end-start)
if print_loss and i%1000==0:
print "Loss after iteration %i: %f" %(i,calculate_loss()) def accuracy_rate():
predict_result=predict()
count=0;
for i in range(len(predict_result)):
realResult=train_y[i]
if(realResult==predict_result[i]):
count+=1
print "count"
print count
print "the correct rate is :%f" %(float(count)/len(predict_result)) def plot_decision_boundary(pred_func):
# Set min and max values and give it some padding
x_min, x_max = train_X[:, 0].min() - .5, train_X[:, 0].max() + .5
y_min, y_max = train_X[:, 1].min() - .5, train_X[:, 1].max() + .5
h = 0.01
# Generate a grid of points with distance h between them
xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h))
# Predict the function value for the whole gid
Z = pred_func(np.c_[xx.ravel(), yy.ravel()])
Z = Z.reshape(xx.shape)
# Plot the contour and training examples
plt.contourf(xx, yy, Z, cmap=plt.cm.Spectral)
plt.scatter(train_X[:, 0], train_X[:, 1], c=train_y, cmap=plt.cm.Spectral)
plt.show() build_model(print_loss=True)
accuracy_rate() # plot_decision_boundary(lambda x: predict(x))
# plt.title("Decision Boundary for hidden layer size 3")

daima的更多相关文章

  1. cheng gong de daima

    /** * Copyright (c) 2012-2016 ebizwindow, Inc. All rights reserved. * * Permission is hereby granted ...

  2. 配置apache的虚拟机+软件下载

    第一步: 打开c:/wamp/apache/conf中的httpd.conf文件, 在httpd.conf中ctrl+f输入vhosts 找到那一行将前面的#号去掉 操作如图所示 第二步: 打开虚拟主 ...

  3. myfocus官方网站已经挂掉,相关下载已经从googlecode转到网盘

    首先说,我跟作者没有任何关系,只是偶然发现这个东西,努力了1个多小时才有下载,现在友情提供出来. 其次,我找到的是v2.0.4 MS这个是最新的版本,更新日期是2012年10月. 再次,本文原本是准备 ...

  4. vs中部分快捷键

    ctrl + r ctrl + r     ctrl 按两次r修改变量名(修改被引用到的变量名),不同于ctrl + f(修改全部相同名字的) ctrl +r ctrl + m    先选中一部分da ...

  5. java.lang.NullPointerException 空指针异常

    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.heheh.daima/com.heheh.daima.H ...

  6. c#重点[数据类型,构造方法,变量,变量,运算符,装箱,拆箱]

    1.命名规范    类  :名词 每个单词的首字母大写 Dog Student  PersonClass 字段:首个字母小写,如果有多个单词,后面的单词首字母大写 string name=" ...

  7. 一个基于Myeclipse开发的Java打地鼠小游戏(Appletcation)

    package javaes.zixue.wangshang.daima; 2 3 import java.awt.Cursor; import java.awt.Image; import java ...

  8. 2016"百度之星" - 初赛(Astar Round2A) 1004 D Game 区间DP

    D Game Problem Description   众所周知,度度熊喜欢的字符只有两个:B 和D. 今天,它发明了一个游戏:D游戏. 度度熊的英文并不是很高明,所以这里的D,没什么高深的含义,只 ...

  9. Layui - 示例

    示例地址 http://www.layui.com/demo/ 下载地址 http://www.layui.com/ 示例代码 <!doctype html> <html> & ...

随机推荐

  1. 怎么写makefile?(转)

    跟我一起写 Makefile 陈皓 第一章.概述 什么是makefile?或许很多Winodws的程序员都不知道这个东西,因为那些Windows的IDE都为你做了这个工作,但我觉得要作一个好的和 pr ...

  2. javascript之循环保存数值

    javascript之循环保存数值 语言都是相通的,这句话在我学javascript时有的深刻的意识.js中的for循环与java中的for循环有很大相似之处. 先看下面这段代码 for(var i= ...

  3. javascript 核心语言笔记 4 - 表达式和运算符

    表达式(expression)是 JavaScript 中的一个短语(phrases),JavaScript 解释器会将其计算(evaluate)出一个结果.程序中的常量.变量名.数组访问等都是表达式 ...

  4. wpf——三维学习1

    以下xmal是我从msdn上复制下来的.是用于在wpf中创建3d模型的实例链接https://msdn.microsoft.com/zh-cn/library/ms747437.aspx看它的使用方式 ...

  5. Jmeter发送Java请求

    1.创建一个Java工程 2.把Jmeter的lib\ext目录下的ApacheJMeter_java.jar.ApacheJMeter_core.jar文件添加进该项目的Build Path 3.创 ...

  6. JS中获得当前时间的年月

    //获取完整的日期 var date=new Date; var year=date.getFullYear(); var month=date.getMonth()+1; month =(month ...

  7. json 排序

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...

  8. QT编译时 cc1plus进程占用大量内存卡死问题解决

    QT5.7 做一个demo编译时,内存几乎完全消耗,卡死.经尝试发现是添加资源文件过大导致(不知是单个文件过大触发还是文件总共过大触发)的.我的资源文件工136M,单个最大是125M左右. 解决方法是 ...

  9. Android基础学习第一篇—Project目录结构

    写在前面的话: 1. 最近在自学Android,也是边看书边写一些Demo,由于知识点越来越多,脑子越来越记不清楚,所以打算写成读书笔记,供以后查看,也算是把自己学到所理解的东西写出来,献丑,如有不对 ...

  10. Design and Implementation of the Sun Network File System

    Introduction The network file system(NFS) is a client/service application that provides shared file ...