附录一个: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. go程序注册为windows服务

    cmd下运行:nssm install 服务名 go打包好的exe文件 nssm下载地址:http://nssm.cc/,将下载好nssm.exe放到/windows/system32文件夹下

  2. Spring中Ordered接口简介

    目录 前言 Ordered接口介绍 Ordered接口在Spring中的使用 总结 前言 Spring中提供了一个Ordered接口.Ordered接口,顾名思义,就是用来排序的. Spring是一个 ...

  3. Alpha阶段冲刺总结

    Alpha阶段冲刺阶段总结 预期计划: 本阶段的预期计划是实现打地鼠游戏的基本功能,包括:游戏功能.难度调节功能.计时功能.计数记分功能.DIY设置功能.分数记录功能. 实际进展: 在经过三周的Alp ...

  4. 【吉光片羽】MVC 导出Word的两种方式

    1.直接将Html转成Word.MVC自带FileResult很好用.Html中我们也可以嵌入自己的样式. html: <div id="target"> <st ...

  5. JavaScript函数编程-Ramdajs

    在JavaScript语言世界,函数是第一等公民.JavaScript函数是继承自Function的对象,函数能作另一个函数的参数或者返回值使用,这便形成了我们常说的高阶函数(或称函数对象).这就构成 ...

  6. 从Windows中卸载Apache

    在重装Apache或者妳不再需要它的时候,这时就需要将它卸载. 下面是步骤: 打开开始菜单(win8中ÿ+X)或者我的电脑(废话) 找到并打开Apache的安装目录(Program Files\Apa ...

  7. Java集合框架的总结

    本篇文章先从整体介绍了Java集合框架包含的接口和类,然后总结了集合框架中的一些基本知识和关键点,并结合实例进行简单分析.当我们把一个对象放入集合中后,系统会把所有集合元素都当成Object类的实例进 ...

  8. 破解Excel密码保护文件

    首先打开vba编辑器,输入代码: Public Sub AllInternalPasswords() ' Breaks worksheet and workbook structure passwor ...

  9. 阿里云ecs Linux下安装MySQL后设置root密码 【转】

    方法一:最简单的方法,也是安装完mysql后,系统提示的方法.使用mysqladmin来完成.shell> mysqladmin -u root password "newpwd&qu ...

  10. 每天一个linux命令(44):top命令

    top命令是Linux下常用的性能分析工具,能够实时显示系统中各个进程的资源占用状况,类似于Windows的任务管理器.下面详细介绍它的使用方法.top是一个动态显示过程,即可以通过用户按键来不断刷新 ...