Theano学习笔记(一)——代数
标量相加
import theano.tensor as T
from theano import function
x = T.dscalar('x')
y = T.dscalar('y')
z = x + y
f = function([x, y], z)
输入定义两个符号变量来取代数值,输出是一个0维的numpy.ndarray数组。
矩阵相加
把输入类型换一下即可了,矩阵假设维数不同,会遵循NumPy的广播规则。
import theano.tensor as T
from theano import function
x = T.dmatrix('x')
y = T.dmatrix('y')
z = x + y
f = function([x, y], z)
定义一个公式如:a ** 2 + b ** 2 + 2 * a* b
这里每一个变量都须要单独申明。
import theano
a = theano.tensor.vector()
b = theano.tensor.vector()
out = a ** 2 + b ** 2 + 2 * a * b
f = theano.function([a,b],out)
print f([0, 1],[1,2])
>>>
[ 1. 9.]
支持多输出
import theano.tensor as T
from theano import function
a, b = T.dmatrices('a', 'b')
diff = a - b
abs_diff = abs(diff)
diff_squared = diff**2
f = function([a, b], [diff, abs_diff,diff_squared])
print f([[1, 1], [1, 1]], [[0, 1], [2,3]])
>>>
[array([[ 1., 0.],
[-1., -2.]]), array([[ 1., 0.],
[ 1., 2.]]), array([[ 1., 0.],
[ 1., 4.]])]
设置默认參数
和标准Python一样,缺省參数必须在非缺省之后,也能够定义缺省变量名。
import theano.tensor as T
from theano import function
from theano import Param
x, y = T.dscalars('x', 'y')
z = x + y
f = function([x, Param(y, default=1,name='by_name')],z)
print f(33)
print f(33, 2)
print f(33,by_name=3)
>>>
34.0
35.0
36.0
共享变量
为了在GPU上更好的性能,引入共享变量,以累加器为例。
import theano.tensor as T
from theano import function
from theano import shared
state = shared(0)
inc = T.iscalar('inc')
accumulator = function([inc], state,updates=[(state, state+inc)])
print state.get_value()
accumulator(1)
print state.get_value()
accumulator(300)
print state.get_value()
state.set_value(-1)
print accumulator(3)
print state.get_value()
>>>
0
1
301
-1
2
state的值在调用函数之后才刷新。并且能够定义多个函数共用同一个共享变量,比如这个减法器。
decrementor = function([inc], state,updates=[(state, state-inc)])
print decrementor(2)
print state.get_value()
>>>
2
0
假设在某个函数中,共用了这个共享变量,可是又不想变动它的值,那么能够使用given參数替代这个变量。而旧的state不发生变化。
fn_of_state = state * 2 + inc
foo = T.scalar(dtype=state.dtype)
skip_shared = function([inc, foo],fn_of_state,
givens=[(state,foo)])
print skip_shared(1, 3)
print state.get_value()
>>>
7
0
产生随机数
和C中的srand()一样,都是伪随机数。
from theano import function
from theano.tensor.shared_randomstreamsimport RandomStreams
srng = RandomStreams(seed=234)#种子
rv_u = srng.uniform((2,2))#均匀分布
rv_n = srng.normal((2,2))#正态分布
f = function([], rv_u)#每次调用,每次都会更新
g = function([], rv_n,no_default_updates=True)#假设以后一直用这组随机数,就不再更新
nearly_zeros = function([], rv_u + rv_u- 2 * rv_u)
print nearly_zeros()#函数每次运行仅仅获得一个随机数,即使表达式里面有3个随机数
种子流:上述2个随机变量,能够全局设定同一个种子,也能够是分别设定。
#分别设置,使用.rng.set_value()函数
rng_val =rv_u.rng.get_value(borrow=True) # Get the rng for rv_u
rng_val.seed(89234) # seeds thegenerator
rv_u.rng.set_value(rng_val,borrow=True)
#全局设置,使用.seed()函数
srng.seed(902340)
函数间共享流
state_after_v0 =rv_u.rng.get_value().get_state()#保存调用前的state
nearly_zeros() # this affects rv_u's generator
v1 = f()#第一个调用,之后state会变化
rng = rv_u.rng.get_value(borrow=True)
rng.set_state(state_after_v0)#为其state还原
rv_u.rng.set_value(rng, borrow=True)
v2 = f() # v2 != v1输出更新后state相应的随机数
v3 = f() # v3 == v1再次更新又还原成原来的state了
在2张Theano图间复制状态
import theano
import numpy
import theano.tensor as T
from theano.sandbox.rng_mrg importMRG_RandomStreams
from theano.tensor.shared_randomstreamsimport RandomStreams class Graph():
def __init__(self, seed=123):
self.rng = RandomStreams(seed)
self.y = self.rng.uniform(size=(1,)) g1 = Graph(seed=123)
f1 = theano.function([], g1.y) g2 = Graph(seed=987)
f2 = theano.function([], g2.y) print 'By default, the two functionsare out of sync.'
print 'f1() returns ', f1()
print 'f2() returns ', f2()
#输出不同的随机值
def copy_random_state(g1, g2):
if isinstance(g1.rng, MRG_RandomStreams):
#类型推断:其第一个參数为对象,第二个为类型名或类型名的一个列表。其返回值为布尔型。
g2.rng.rstate = g1.rng.rstate
for (su1, su2) in zip(g1.rng.state_updates, g2.rng.state_updates):#打包
su2[0].set_value(su1[0].get_value())#赋值 print 'We now copy the state of thetheano random number generators.'
copy_random_state(g1, g2)
print 'f1() returns ', f1()
print 'f2() returns ', f2()
#输出同样的随机值
>>>
By default, the two functions are outof sync.
f1() returns [ 0.72803009]
f2() returns [ 0.55056769]
We now copy the state of the theanorandom number generators.
f1() returns [ 0.59044123]
f2() returns [ 0.59044123]
欢迎參与讨论并关注本博客和微博以及知乎个人主页兴许内容继续更新哦~
转载请您尊重作者的劳动,完整保留上述文字以及文章链接,谢谢您的支持!
Theano学习笔记(一)——代数的更多相关文章
- Theano 学习笔记(一)
Theano 学习笔记(一) theano 为什么要定义共享变量? 定义共享变量的原因在于GPU的使用,如果不定义共享的话,那么当GPU调用这些变量时,遇到一次就要调用一次,这样就会花费大量时间在数据 ...
- IMPLEMENTING A GRU/LSTM RNN WITH PYTHON AND THEANO - 学习笔记
catalogue . 引言 . LSTM NETWORKS . LSTM 的变体 . GRUs (Gated Recurrent Units) . IMPLEMENTATION GRUs 0. 引言 ...
- Theano学习笔记(二)——逻辑回归函数解析
有了前面的准备,能够用Theano实现一个逻辑回归程序.逻辑回归是典型的有监督学习. 为了形象.这里我们如果分类任务是区分人与狗的照片. 首先是生成随机数对象 importnumpy importth ...
- Theano学习笔记(三)——图结构
图结构(Graph Structures)这是理解Theano该基金会的内部运作. Theano编程的核心是用符号占位符把数学关系表示出来. 图结构的组成部分 如图实现了这段代码: importthe ...
- Theano学习笔记(四)——导数
导数使用T.grad计算. 这里使用pp()打印梯度的符号表达式. 第3行输出是打印了经过优化器简化的符号梯度表达式,与第1个输出相比确实简单多了. fill((x** TensorConstant{ ...
- Theano学习笔记:Theano的艰辛安装体验
http://www.cnblogs.com/hanahimi/p/4127026.html
- TensorFlow学习笔记4-线性代数基础
TensorFlow学习笔记4-线性代数基础 本笔记内容为"AI深度学习".内容主要参考<Deep Learning>中文版. \(X\)表示训练集的设计矩阵,其大小为 ...
- Caffe学习笔记2--Ubuntu 14.04 64bit 安装Caffe(GPU版本)
0.检查配置 1. VMWare上运行的Ubuntu,并不能支持真实的GPU(除了特定版本的VMWare和特定的GPU,要求条件严格,所以我在VMWare上搭建好了Caffe环境后,又重新在Windo ...
- 学习笔记︱Nvidia DIGITS网页版深度学习框架——深度学习版SPSS
DIGITS: Deep Learning GPU Training System1,是由英伟达(NVIDIA)公司开发的第一个交互式深度学习GPU训练系统.目的在于整合现有的Deep Learnin ...
随机推荐
- HDU 3126 Nova [2009 Asia Wuhan Regional Contest Online]
标题效果 有着n巫妖.m精灵.k木.他们都有自己的位置坐标表示.冷却时间,树有覆盖范围. 假设某个巫妖攻击精灵的路线(他俩之间的连线)经过树的覆盖范围,表示精灵被树挡住巫妖攻击不到.求巫妖杀死所有精灵 ...
- 使用 gridfs-stream 存储文件遇到的一个坑。
前一段时间参读了某个coder写的用 gridfs-stream 来存储文件,感觉不错就自己用 gridfs-stream 模块写了一个文件存储服务,但是发现存储的文件总是删不掉, 我调用的是GFS的 ...
- unix pwd使用命令
[语法]: pwd [说明]: 此命令会显示当前的工作文件夹 []: pwd 这显示当前工作文件夹 版权声明:本文博主原创文章.博客,未经同意不得转载.
- LAN远程重启server安全方法
原创文章.转载请注明出处.(百度经验:http://jingyan.baidu.com/article/454316abaadc41f7a7c03a13.html) 在局域网中,管理和操作server ...
- Event Sourcing
Event Sourcing - ENode(二) 接上篇文章继续 http://www.cnblogs.com/dopeter/p/4899721.html 分布式系统 前篇谈到了我们为何要使用分布 ...
- SQL Server 优化存储过程的七种方法
原文:SQL Server 优化存储过程的七种方法 优化存储过程有很多种方法,下面介绍最常用的7种. 1.使用SET NOCOUNT ON选项 我们使用SELECT语句时,除了返回对应的结果集外,还会 ...
- [INS-20802] Oracle Database Configuration Assistant 失败
1.错误原因 [INS-20802] Oracle Database Configuration Assistant 失败 2.错误原因 3.解决方案 版权声明:本文博主原创文章.博客,未经同意 ...
- JavaScript技巧&写法
原文:JavaScript技巧&写法 JavaScript技巧篇: 1>状态机 var state = function () { this.count = 0; this.fun = ...
- swift UI特殊培训38 与滚动码ScrollView
有时我们适合页面的全部内容,我们需要使用ScrollView,额外的内容打通滚动. 什么样的宽度和高度首先,定义,健身器材轻松. let pageWidth = 320 let pageHeight ...
- 一个由proguard与fastJson引起的血案(转)
更新微信sdk导致ComposeData中的内部类ComposeDataSender方法被混淆 根本原因,fastjson使用姿势不对. 问题描述: 一个发件人列表里,应当呈现的数据(这里命名为Com ...