theano 模块 MLP示例,有需要的朋友可以参考下。

theano教程
Example: MLP:

约定数组为列向量,

层级:
将多层传感器定义为一连串的层级,每个层级定义为一个类。类属性包括:权重、偏差矢量、以及计算这一层输出的函数。
如果不使用Theano,我们可能希望输出函数会接收一个向量并返回图层的激活来响应输入。然而在Theano中输出函数反而是为了创造能够接收向量并返回图层激活的函数而创建的。因此我们要创建一个在类外部计算图层的激活。
Layer类:neural network 的一层用于计算非线性误差s = Wx+b 。其中x就是输入的向量。

class Layer(object):
def __init__(self,W_init,b_init,activation):
'''
W_init 是需要初始化的权重矩阵的值 (n_output,n_input)
b_init 是需要初始化的偏差向量的值 (n_output,)
activation 是图层激活函数
'''
#基于W的初始化来获得输入和输出的维度
n_output,n_input = W_init.shape
#确定b是output的大小
assert b_init.shape == (n_output,)
#所有参数都应该是共享变量,在类里用于计算图层的输出。但在优化网络参数时在类外更新。
#W_init 必须设置为 theano.config.floatX 字符类型。
self.W = theano.shared(value = W._init.astype(theano.config.floatX),
#name 参数是专门用来打印 purporses
name = 'w',
#将borrow 设置为 True 来允许 theano 为对象使用用户的内存,可以避免对结构的深拷贝来使编码的速度快一点。
borrow = True,
#theano 与numpy类似,允许广播,但是要明确的标示出需要被广播的坐标轴。通过设置 boardcastable = (False,True),来表示b能够沿着它的第二维广播,以便将他添加到其他变量。
broadcastable = (False,True))
self.activation = activation
#计算关于列表中参数的网络成本的梯度。
self.params = [self.W,self.b] def ouput(self,x):
'''
参数:
- x : theano.tensor.var.TensorVariable
图层输入的 theano 符号变量 返回:
- output : theano.tensor.var.TensorVariable
混合的,有误差的,激活的 x
'''
#计算线性组合
lin_output = T.dot(self.W,x) + self.b
#如果缺少激活函数,那么返回的仅仅只是线性组合
#调用激活函数
return(lin_output if self.activation is None else self.activation(lin_output))

MLP类:大多数多层传感器的功能包含在 Layer 类中,MLP 类本质上是 Layer对象列表和相关的参数的容器。输出函数递归的计算每一图层的输出。squared_error:被给定输入的网络的输出和期望之间的欧氏距离的平方。这个函数的作用是估算建立在训练数据集上的最小成本。
综上,squared_error函数 和output 并不作为最终结果,相反,他们被用来计算得出最终结果。

class MLP(object):
def __init__(self,W_init,b_init,activations):
'''
Multi-layer perceprton class 用来计算图层序列的组成部分。
:参数
- W_init : list of np.ndarray, len=N
参数的值初始化为每一层的权重值
图层的大小应从 W_init 的 shape 属性中推断出
- b_init : list of np.ndarray, len=N
参数的值初始化为每一层的偏差向量
- activations : list of theano.tensor.elemwise.Elemwise, len=N
Activation function for layer output for each layer
'''
#确保输入列表的元素都是相同的大小
assert len(W_init) == len(b_init) == len(activations) #初始化图层列表
self.layers = []
#创建图层创建图层
for W , b , activation in zip (W_init,b_init,activations):
self.layers.append(Layer(W,b,activation)) #从所有的图层中合并参数
self.params = []
for layer in self.layers:
self.params += layer.params def output(self,x):
'''
:parameters:
- x : theano.tensor.var.TensorVariable
图层输入的 theano 符号变量 :returns:
- output : theano.tensor.var.TensorVariable
通过 MLP 的 x '''
#递归计算输出
for layer in self.layers:
x = layer.output(x)
return x def squared_error(self,x,y):
'''
计算网络的输出相对与期望的欧几里得误差的平方 :parameters:
- x : theano.tensor.var.TensorVariable
网络输入的 theano 的符号变量
- y : theano.tensor.var.TensorVariable
网络输出期望的 theano 的符号变量 :returns:
- error : theano.tensor.var.TensorVariable
x 和 y 之间的欧式误差的平方
''' return T.sum((self.output(x) - y) ** 2)

梯度下降法:为了训练网络, 需要对训练数据集使用梯度下降法来降低成本(网络输出相对于期望的欧式误差的平方)。做神经网络的梯度下降法时, 常用方法是 momentum (动量), 也就是对参数更新进行有漏积分 : 在更新参数时, 计算当前梯度更新和之前的梯度更新的线性组合. 这往往使得网络在一个相对好的结果上更快的收敛,同时能够帮助避免成本函数中的局部极小值. 使用传统的梯度下降法你能够保证在每次迭代过程中降低成本. 当我们使用 momentum 时没有这个保证, 但在一般情况下,momentum 通常为这种改良提供了足够小的成本。

在 theano 中,我们把之前的更新储存为一个共享变量,因此它的值能在迭代过程中被保留. 于是, 在梯度更新中, 我么不仅仅只更新参数, 也同时更新之前的参数更新得到共享变量。

def gradient_updates_momentum(cost,params,learning_rate,momentum):
'''
利用 momentum 计算梯度下降的更新 :parameters:
- cost : theano.tensor.var.TensorVariable
Theano cost function to minimize
- params : list of theano.tensor.var.TensorVariable
Parameters to compute gradient against
- learning_rate : float
Gradient descent learning rate
- momentum : float
Momentum parameter, should be at least 0 (standard gradient descent) and less than 1 :returns:
updates : list
List of updates, one for each parameter
'''
#确保 momentum 是一个 合理的值
assert momentum >0 and momentum <1
#每个参数的更新步骤列表
updates = []
#对成本应用梯度下降
for param in params:
#为每个参数创建一个共享变量 param_update
#这个变量会在迭代过程中持续跟踪参数的更新步骤
#param_update 初始化为0
param_update = theano.shared(param.get_value()*0.,broadcastable = param.broadcastable)
#每个参数沿梯度方向移动一步完成更新。
#但是我们也根据给定的 momentum 的值“混入”之前的步骤
#所以,在更新 param_update 时,需要的变量是:前一步的 momentum 的值和新的梯度步骤
updates.append(param,param - learning_rate*param_update)
#我们不需要推导计算更新的反向传播算法,用 T.grad 即可。
updates.append((param_update , momentum*param_update+(1.-momentum)*T.grad(cost,param)))
return updates

theano 模块 MLP示例的更多相关文章

  1. 为Lua5.3编写C模块简单示例

    为Lua5.3编写C模块简单示例 一.编译安装Lua5.3 MSVC 命令行安装脚本: @echo off md bin md lib md include cd src cl /c /nologo ...

  2. Ansible VMware模块使用示例

    vmware_vm_facts模块使用示例 执行条件: 安装Pyvmimo:  pip install pyvmomi 方法一,直接编写单个yaml文件: - hosts: localhost # 注 ...

  3. python中hashlib模块用法示例

    python中hashlib模块用法示例 我们以前介绍过一篇Python加密的文章:Python 加密的实例详解.今天我们看看python中hashlib模块用法示例,具体如下. hashlib ha ...

  4. UIPullRefreshFlash模块demo示例

    UIPullRefreshFlash 模块概述:UIPullRefreshFlash模块对引擎新推出的下拉刷新接口进行了一层封装,app可以通过此模块来实现带炫酷动画效果的下拉刷新功能.使用此模块,在 ...

  5. Python tesserocr模块使用示例

    操作系统:Win10 1709  X64 python版本:3.6.5 依赖模块:PIL.tesserocr. 需要说明的是,在windows系统上PowerShell通过PIP3 install t ...

  6. pythondifflib模块讲解示例

    版权声明:本文为博主原创文章,未经博主允许不得转载. https://blog.csdn.net/Lockey23/article/details/77913855 difflib模块提供的类和方法用 ...

  7. python强大的绘图模块matplotlib示例讲解

    Matplotlib 是 Python 的绘图库.作为程序员,经常需要进行绘图,在我自己的工作中,如果需要绘图,一般都是将数据导入到excel中,然后通过excel生成图表,这样操作起来还是比较繁琐的 ...

  8. python中的 uuid 模块使用示例

    此模块提供不可变的 UUID 对象 (类 uuid) 和函数uuid1().uuid3().uuid4().uuid5(), 用于生成在 RFC 4122 中指定版本1.3.4和5UUIDs .如果你 ...

  9. Redis模块开发示例

    实现一个Redis module,支持两个扩展命令: 1) 可同时对hash的多个field进行incr操作: 2) incrby同时设置一个key的过期时间 在没有module之前,需要借助eval ...

随机推荐

  1. CPU使用情况检测

    改编自:https://blog.csdn.net/Yan_Chou/article/details/80456995 检测命令整理: dd iotop df top psiostatvmstatne ...

  2. ORACLE 12.1.0.1 至12.1.0.2升级文档(单机版 DBUA方式)

    12C DBUA新特性 1. 新的pre-upgrade 检查工具. 2. 并行升级. 3. DBUA升级时,默认并行度为CPU个数或2. 并行度可调整. 4. 在升级过程中,DBUA工具可再次调用( ...

  3. JavaScript中内置对象的一些属性及方法

    Javascript对象总结 JS中内置了17个对象,常用的是Array对象.Date对象.正则表达式对象.string对象.Global对象 Array对象中常用方法: Concat():表示把几个 ...

  4. Keepalived + Nginx + Tomcat 高可用负载均衡架构

    环境: 1.centos7.3 2.虚拟ip:192.168.217.200 3.192.168.217.11.192.168.217.12上分别部署Nginx Keepalived Tomcat并进 ...

  5. C# AD 验证登陆

    using System.DirectoryServices; using System.DirectoryServices.AccountManagement; using (DirectoryEn ...

  6. 1104 Sum of Number Segments(20 分)

    Given a sequence of positive numbers, a segment is defined to be a consecutive subsequence. For exam ...

  7. (转)linux配置网卡的命令

    linux配置网卡的命令 原文:http://blog.51cto.com/lanxianting/1754923 1.配置命令 如果一台服务器需要通外网,能被远程连接,就得给这个台服务器配置ip,子 ...

  8. centos6安装bochs

    安装包 bochs 2.6.8 平台 centos6 前提依赖 yum groupinstall -y "Server Platform Development" "De ...

  9. Golang: runnerw.exe: CreateProcess failed with error 216 (no message available)

    话说这个我应该遇到几次了 每次新项目都有这问题,我的记忆是金鱼的记忆吗? 好在这次隐约记起是包名的问题... 方法 修改包名为main

  10. maven(多个模块)项目 部署 开发环境 问题处理历程【异常Name jdbc is not bound in this Context 异常java.lang.NoSuchMethodE】

    maven(多个模块)项目 部署 开发环境 问题处理历程[异常Name jdbc is not bound in this Context 异常java.lang.NoSuchMethodE] 201 ...