# -*- 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. lattice 与 modelsim 仿真 笔记

    对于 lattice  Diamond 与 modelsim 的联合仿真,我总结了一句话,那就是—— 难者不会,会者不难.  也许刚开始 觉得 摸不着 头脑,但是 一旦学会 感觉还是很简单和直观的. ...

  2. opencv计算运行时间

    double Time = (double)cvGetTickCount();//  算法过程Time = (double)cvGetTickCount() - Time ; printf( &quo ...

  3. C 标准库系列之ctype.h

    ctype.h 主要提供了一些函数用以测试字符或字符处理的功能函数:包括字符判断检测.字符转换: 目前ASCII字符可分为以下一些类型,如:大写.小写.字母.数字.十六进制.空白字符.可打印字符.控制 ...

  4. Oracle获取干净的建表DDL语句,不含其它存储、表空间、段属性

    早上一个同事资讯怎么获取到建表语句而且是不带存储那种SQL.Oracle自己提供了一个函数DBMS_METADATA.GET_DDL,但是获取到的建表语句含有存储.表空间.以及一些其他段的属性.如图: ...

  5. Java 之 软件的生命周期

    1.寻找商机: a.项目:有明确的需求提供方 b.产品:没有需求提供方,由市场决定 2.可行性分析: a.国家法律法规 b.资金 c.人员技术组成 3.投标 4.需求的搜集与分析: a.参与人员:需求 ...

  6. 教你如何做Lotus Domino的应用开发

    http://www.lotuschina.net/club/thread-7309-1-1.html

  7. TAQSkinScrollBar 类美化滚动条再讨论

    再说:TAQSkinScrollBar 类美化滚动条,http://www.138soft.com/?p=156  里面有人提到不可以滚动 滚动的改善方法: unit AQSkinScrollBar; ...

  8. 通过GDI+绘制 验证码

    只为了记录下自己的学习历程,方便日后查看 现在开始言归正传,以下为其完整代码附上 using System; using System.Collections.Generic; using Syste ...

  9. Linux系统学习优缺点

    Linux是一套操作系统,按照鸟哥的说法Linux提供了一个完整的操作系统当中最底层的硬件控制与资源管理的完整架构,这个架构是沿袭Unix良好的传统而来的,功能强大而且稳定性卓越.其实Torvalds ...

  10. 转:界面之下:还原真实的 MVC、MVP、MVVM 模式

    前言 做客户端开发.前端开发对MVC.MVP.MVVM这些名词不了解也应该大致听过,都是为了解决图形界面应用程序复杂性管理问题而产生的应用架构模式.网上很多文章关于这方面的讨论比较杂乱,各种MV*模式 ...