附录一个:Keras学习随笔 http://blog.csdn.net/niuwei22007/article/details/49045909

参考 《Python Machine Learning》这本书的第13章

Theano是Bengio大神课题组弄得。

一、Theano初步

Theano编程三个步骤: 初始化、编译和执行,就是定义符号(变量对象)、编译代码和执行代码

举个例子:计算 z=x1*w1+wo 代码如下:

 # -*- coding: utf-8 -*-
__author__ = 'Administrator' import theano
import theano.tensor as T
import random
import numpy as np
from itertools import izip
import matplotlib.pyplot as plt #初始化
x1 = T.scalar()
w1 = T.scalar()
w0 = T.scalar()
z = w1*x1+w0 #编译 net_input = theano.function(
inputs=[w1, x1, w0],
outputs=z
) #执行 print 'net input %.2f'% (net_input(2.0, 1.0 ,0.5))

在写Theano代码时,要注意变量的类型 dtype ,要分清楚我们要使用 64或者32为的int or floats

二、 配置Theano

一般来说 采用CPU时,我们设置float64 ,采用GPU时,需要设置float32

print (theano.config.floatX)
print (theano.config.device)

在window中设置CPU or GPU模式,是在运行cmd后出现的路径下,新建一个.theanorc.txt的文件。文件内容如下图所示

三、使用array结构

一个简单的求和例子

 #初始化
x = T.fmatrix(name ='x')
x_sum = T.sum(x, axis=1) # 0 是按列 1 是按行 #编译
calc_sum = theano.function(
inputs=[x],
outputs=x_sum
) #执行
ary = np.array([[1,2,4],[1,2,3]],dtype=theano.config.floatX)
print calc_sum(ary)

shared variable 和 权值更新

 #初始化
x = T.fmatrix('x')
w = theano.shared(np.asarray([[0.0,0.0,0.0]],dtype=theano.config.floatX)) z = T.dot(x,w.T) # 这个就是两个矩阵相乘 w是1*3 x是1*3 update = [[w, w+1.0]] # 编译
net_input = theano.function(
inputs=[x],
updates=update,
outputs=z
) # 执行 data = np.array([[1,2,3]],dtype=theano.config.floatX)
for i in range(5):
print w.get_value()
print '%d %.2f' % (i,net_input(data))

可以提取指定数据,代码如下

 #初始化
data = np.array([[1,2,3]],dtype=theano.config.floatX)
x = T.fmatrix('x')
w = theano.shared(np.asarray([[0.0,0.0,0.0]],dtype=theano.config.floatX)) z = T.dot(x,w.T) # 这个就是两个矩阵相乘 w是1*3 x是1*3 update = [[w, w+1.0]] # 编译
net_input = theano.function(
inputs=[],
updates=update,
givens={x : data},
outputs=z
) # 执行 for i in range(5):
print w.get_value()
print '%d %.2f' % (i,net_input())

四、 一个线性回归的例子

 X_train = np.asarray(
[ [0,0] , [1, 0],
[2,0] , [3, 0],
[4,0] , [5, 0],
[6,0] , [7, 0],
[8,0] , [9, 0]],
dtype= theano.config.floatX
) y_train = np.asarray(
[ 1.0,1.3,3.1,2.0,
5.0,6.3,6.6,7.4,
8.0,9.0],
dtype= theano.config.floatX
) y_train_new = np.asarray(
[ [1.0],[1.3],[3.1],[2.0],
[5.0],[6.3],[6.6],[7.4],
[8.0],[9.0]],
dtype= theano.config.floatX
)
print X_train.shape[1] # shape 0 获取行 shape 1 获取列 def train_linreg(X_train, y_train ,eta, epochs):
costs = []
#初始化array0
eta0 = T.fscalar('eta0')
y = T.fvector(name='y')
X = T.fmatrix(name='X')
w = theano.shared(np.zeros(
shape=(X_train.shape[1] +1 ),dtype= theano.config.floatX), name = 'w') #计算损失函数
net_input = T.dot(X, w[1:]) + w[0] # w[1:] 从第二个到最后一个数据
errors = y - net_input
cost = T.sum(T.pow(errors,2)) #梯度更新
gradient = T.grad(cost,wrt=w)
update = [(w, w- eta0* gradient)] #定义模型
train = theano .function(inputs=[eta0],
outputs=cost,
updates=update,
givens={X:X_train,
y: y_train}) for i in range(epochs):
costs.append(train(eta))
print w.get_value()
return costs, w def predict_linreg(X,w):
Xt = T.matrix(name='X')
net_input = T.dot(Xt, w[1:])+w[0]
predict = theano.function(inputs=[Xt],
givens={w:w},
outputs= net_input)
return predict(X) costs,w= train_linreg(X_train,y_train,eta=0.001,epochs=10)
plt.plot(range(1,len(costs)+1),costs)
plt.tight_layout()
plt.xlabel("epoch")
plt.ylabel('cost')
plt.show()
#
#plt.scatter(X_train, y_train ,marker='s',s=50)
plt.plot(range(X_train.shape[0]),predict_linreg(X_train,w),color='gray',marker='o',markersize=4,linewidth=3)
plt.xlabel("x")
plt.ylabel('y')
plt.show()

结果图:

 

Theano入门神经网络(三)的更多相关文章

  1. Theano入门神经网络(一)

    Theano是一个Python库,专门用于定义.优化.求值数学表达式,效率高,适用于多维数组.特别适合做机器学习.一般来说,使用时需要安装python和numpy. 首先回顾一下机器学习的东西,定义一 ...

  2. Theano入门神经网络(四)

    这一部分主要介绍用Theano 实现softmax函数. 在多分类任务中经常用到softmax函数,首先上几个投影片解释一下 假设目标输出是y_hat ,激活函数后的Relu y 一个是1.2 一个是 ...

  3. Theano入门神经网络(二) 实现一个XOR门

    与非门的图片如下 示意图 详细解释: 1 定义变量的代码,包括了输入.权值.输出等.其中激活函数采用的是sigmod函数 # -*- coding: utf-8 -*- __author__ = 'A ...

  4. Theano入门——CIFAR-10和CIFAR-100数据集

    Theano入门——CIFAR-10和CIFAR-100数据集 1.CIFAR-10数据集介绍 CIFAR-10数据集包含60000个32*32的彩色图像,共有10类.有50000个训练图像和1000 ...

  5. 无废话ExtJs 入门教程三[窗体:Window组件]

    无废话ExtJs 入门教程三[窗体:Window组件] extjs技术交流,欢迎加群(201926085) 1.代码如下: 1 <!DOCTYPE html PUBLIC "-//W3 ...

  6. RequireJS入门(三)转

    这篇来写一个具有依赖的事件模块event.event提供三个方法bind.unbind.trigger来管理DOM元素事件. event依赖于cache模块,cache模块类似于jQuery的$.da ...

  7. RequireJS入门(三)

    这篇来写一个具有依赖的事件模块event.event提供三个方法bind.unbind.trigger来管理DOM元素事件. event依赖于cache模块,cache模块类似于jQuery的$.da ...

  8. 【SSRS】入门篇(三) -- 为报表定义数据集

    原文:[SSRS]入门篇(三) -- 为报表定义数据集 通过前两篇文件 [SSRS]入门篇(一) -- 创建SSRS项目 和 [SSRS]入门篇(二) -- 建立数据源 后, 我们建立了一个SSRS项 ...

  9. Bootstrap入门(三十)JS插件7:警告框

    Bootstrap入门(三十)JS插件7:警告框 通过这个插件可以为警告信息添加点击以及消失的功能. 当使用一个.close按钮,它必须是第一个子元素.alert-dismissible,并没有文字内 ...

随机推荐

  1. 【腾讯Bugly干货分享】腾讯验证码的十二年

    本文来自于腾讯bugly开发者社区,未经作者同意,请勿转载,原文地址:http://dev.qq.com/topic/581301b146dfb1456904df8d Dev Club 是一个交流移动 ...

  2. Actor的原理

    先从著名的c10k问题谈起.有一个叫Dan Kegel的人在网上(http://www.kegel.com/c10k.html)提出:现在的硬件应该能够让一台机器支持10000个并发的client.然 ...

  3. Kinect for Windows SDK 1.8的改进及新特性

    今年3月, 微软推出了Kinect for Windows SDK 1.7 更新,包括了手势识别 Kinect Interactions 和实时 3D 建模 Kinect Fusion 两项新技术. ...

  4. windows 8.1 试用感受:蛋疼感大幅降低

    众所周知windows 8 的最大使用感受就是蛋疼. 无论是微软MVP,还是我这样的万年不悔微软小白鼠,普通用户,小白用户,或多或少的都对这款操作系统感到蛋疼. 槽点太多,以至于大家都懒得批判了.好在 ...

  5. MYSQL 大文件无法导入的问题。

    1. 设置maxpacket. 要在[mysqld]标签下.这个疏忽了,就会发现没效果. 基本网上的都没说清,要看stackoverflow. Change in the my.ini file. I ...

  6. 趣味C程序-HelloWord

    说明:刚才写了一个基础的helloWord程序(很早以前从其他地方收集的.),本以为群里面的人是可以答对了,但是我错了,没有人.他们的错误往往被程序的外表给蒙蔽了. 很多人的回答是0.如果你仔细看的话 ...

  7. IOS Socket 02-Socket基础知识

    1. 简介 Socket就是为网络服务提供的一种机制 通信的两端都是Socket 网络通信其实就是Socket间的通信 数据在两个Socket间通过IO传输 2. Socket通信流程图 3. 模拟Q ...

  8. 已经为类型参数“Chart”指定了 constraint 子句。必须在单个 where 子句中指定类型参数的所有约束

    public abstract class FillWorkBook<TModel, Chart> where TModel : struct where Chart : new() wh ...

  9. mvc项目controller重命名了,用原网页url访问不了了,怎么办?

    如题.MVC项目,手机网站. 公司的官方微信上,用户关注之后,点击相应菜单就可以使用相关的功能. 最近项目重构,有些不规范的命名方式给予了重构.上线后,微信上发现一些网页访问不了了. 联系微信的维护人 ...

  10. PDO连接mysql和pgsql数据库

    PDO连接mysql数据库 <?php $dsn="mysql:host=localhsot;dbname=lamp87"; $user="root"; ...