daima
# -*- 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的更多相关文章
- cheng gong de daima
/** * Copyright (c) 2012-2016 ebizwindow, Inc. All rights reserved. * * Permission is hereby granted ...
- 配置apache的虚拟机+软件下载
第一步: 打开c:/wamp/apache/conf中的httpd.conf文件, 在httpd.conf中ctrl+f输入vhosts 找到那一行将前面的#号去掉 操作如图所示 第二步: 打开虚拟主 ...
- myfocus官方网站已经挂掉,相关下载已经从googlecode转到网盘
首先说,我跟作者没有任何关系,只是偶然发现这个东西,努力了1个多小时才有下载,现在友情提供出来. 其次,我找到的是v2.0.4 MS这个是最新的版本,更新日期是2012年10月. 再次,本文原本是准备 ...
- vs中部分快捷键
ctrl + r ctrl + r ctrl 按两次r修改变量名(修改被引用到的变量名),不同于ctrl + f(修改全部相同名字的) ctrl +r ctrl + m 先选中一部分da ...
- java.lang.NullPointerException 空指针异常
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.heheh.daima/com.heheh.daima.H ...
- c#重点[数据类型,构造方法,变量,变量,运算符,装箱,拆箱]
1.命名规范 类 :名词 每个单词的首字母大写 Dog Student PersonClass 字段:首个字母小写,如果有多个单词,后面的单词首字母大写 string name=" ...
- 一个基于Myeclipse开发的Java打地鼠小游戏(Appletcation)
package javaes.zixue.wangshang.daima; 2 3 import java.awt.Cursor; import java.awt.Image; import java ...
- 2016"百度之星" - 初赛(Astar Round2A) 1004 D Game 区间DP
D Game Problem Description 众所周知,度度熊喜欢的字符只有两个:B 和D. 今天,它发明了一个游戏:D游戏. 度度熊的英文并不是很高明,所以这里的D,没什么高深的含义,只 ...
- Layui - 示例
示例地址 http://www.layui.com/demo/ 下载地址 http://www.layui.com/ 示例代码 <!doctype html> <html> & ...
随机推荐
- Thread比Task多出的无法代替的部分
Task比Thread耗资源更少,且默认在线程池中. 但是Thread能够设置为STA来执行而Task不能,这对于某些特殊功能很重要,比如WebBrowser控件对象就不能在非单线程单元的线程中new ...
- Jquery知识点梳理
Jquery $代表选择器 JS 选取元素 操作内容 操作属性 操作样式 <div id="aa" style="width:100px; height:100px ...
- rdlc报表相关
错误提示:1.尚未指定报表定义的来源 注意ReportPath与ReportEmbeddedResource的区别,前者获取或设置本地报表的本地文件系统路径,设置此属性将导致后者属性值被忽略:后者将获 ...
- hbase1.2.4 伪分布式安装
注意:在安装hbase或者hadoop的时候,要注意hadoop和hbase的对应关系.如果版本不对应可能造成系统的不稳定和一些其他的问题.在hbase的lib目录下可以看到hadoop对应jar文件 ...
- 2016年6月20日 JAVA知识框架
基于 J2EE 列举的知识架构,大体列举开发基础知识.帮助我随时查缺补漏,奉行好记性不如烂笔头.写了这该随笔,以便后续查询. 1 JAVA简介 2 JAVA编程环境 3 JAVA基本编程结构 4 ...
- android include进来的组件 调用其子元素
include标签包裹着一个可复用的布局: <include layout="@layout/footer_detail" android:id="@+id/foo ...
- Spring MVC 学习 -- 创建过程
Spring MVC 学习 -- 创建过程 Spring MVC我们使用的时候会在web.xml中配置 <servlet> <servlet-name>SpringMVC< ...
- Android 笔记 AutoCompleteTextView day8
用于自动补全内容 适应器可用于显示多行内容 package com.supermario.autocompletedemo; import android.app.Activity; import a ...
- 防止sql注入和sqlmap介绍
sql注入问题从WEB诞生到现在也一直没停过,各种大小公司都出现过sql注入问题,导致被拖库,然后存在社工库撞库等一系列影响. 防止sql注入个人理解最主要的就一点,那就是变量全部参数化,能根本的解决 ...
- CozyRSS开发记录10-RSS源管理
CozyRSS开发记录10-RSS源管理 1.RSS源树结构 做解析体力活很多,把RSS解析的优化先放放,先玩一玩RSS源的管理. 虽然在初步的设计中,RSS源是以一个列表的方式来展示,但是,我觉得如 ...