# -*- 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. 【转】Redis入门

    Redis是一个开源,先进的key-value存储,并用于构建高性能,可扩展的Web应用程序的完美解决方案. Redis从它的许多竞争继承来的三个主要特点: Redis数据库完全在内存中,使用磁盘仅用 ...

  3. C#中常用的系统内置委托

    在公共语言运行时(CLR)环境中系统为我们内置了一些常用的委托,包括Action类的委托.Func类的委托.Predicate<T>委托.Comparison<T>委托等等.以 ...

  4. Guava学习笔记(一)概览

    Guava是谷歌开源的一套Java开发类库,以简洁的编程风格著称,提供了很多实用的工具类, 在之前的工作中应用过Collections API和Guava提供的Cache,不过对Guava没有一个系统 ...

  5. F#之旅2 - 我有特别的学F#技巧

    原文地址:https://swlaschin.gitbooks.io/fsharpforfunandprofit/content/learning-fsharp/ Learning F#Functio ...

  6. CozyRSS开发记录10-RSS源管理

    CozyRSS开发记录10-RSS源管理 1.RSS源树结构 做解析体力活很多,把RSS解析的优化先放放,先玩一玩RSS源的管理. 虽然在初步的设计中,RSS源是以一个列表的方式来展示,但是,我觉得如 ...

  7. curl使用简单介绍

    http://www.linuxidc.com/Linux/2008-01/10891.htm Curl是Linux下一个很强大的http命令行工具,其功能十分强大. 二话不说,先从这里开始吧! $ ...

  8. 学习微信小程序之css7

    盒模型 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8 ...

  9. js随笔

    在js中,一个[]认为是数组:{}认为是Json对象:

  10. Double的精度问题

    /** * 自定义Math工具类 * */ public class MyMathTools { /** * 提供精确的小数位四舍五入处理. * * @param v * 需要四舍五入的数字 * @p ...