您的位置:首页 > 其它

theano tutorial(一)

2016-04-18 12:05 429 查看
#coding=utf-8
"""shared
使用共享变量
shared函数创建共享变量
可以被多个函数共享
share函数可以用于符号表达式(例如=datrices返回的对象)
alue可以通过.get_value和.set_value获得和修改

updates
function.updates 其参数(shared-variable, new expression)是一个字典
key:shared-variable,values:new expression
每次run function的时候都用new expression来替换shared-variable
"""

import theano
import theano.tensor as T
from theano import shared
from theano import function
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())
# 0
# 1
# 301

#可以充值state:.set_values()
state.set_value(-1)
accumulator(3)
print(state.get_value())
#2

#可以定义多个方法使用同一个shared变量,这些函数都可以更新value
decrementor=function([inc],state,updates=[(state,state-inc)])
decrementor(2)
print(state.get_value())
#0

"""
使用updates有时是为了更快的使用一些内置的算法(eg.low-rank matrix updates)
和更好的控制内存的分配(gpu)
"""
#givens:当使用了shared变量定义来一个表达式,但不使用他的值,
# dtype:一个用来描述数组中元素类型的对象,可以通过创造或指定dtype使用标准Python类型。另外NumPy提供它自己的数据类型
fn_of_state=state*2+inc
foo=T.scalar(dtype=state.dtype)<pre code_snippet_id="1651439" snippet_file_name="blog_20160418_1_3329301" name="code" class="python">#givens允许你用一个不同的表达式将公式里面相同shape和dtype的那部分给替换掉
skip_shared=function([inc,foo],fn_of_state,givens=[(state,foo)])skip_shared(1, 3)print(state.get_value())
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  theano