1.function传入多个计算公式
代码:
a, b = T.dmatrices('a', 'b')
diff = a - b
abs_diff = abs(diff)
diff_squared = diff**2
f = theano.function([a, b]. [diff, abs_diff, diff_squared])
笔记:
同时声明多个矩阵调用dmatrices:
a, b = T.dmatrices('a', 'b')
多个计算公式以中括号[]包裹,以逗号隔开。
2.function默认参数实现
代码:
from theano import In
from theano import function
x, y = T.dscalars('x','y')
z = x + y
f = function([x,In(y, value = 1)], z)
笔记:
从theano中引入In
在function参数传入中用In(var, value = default value)的格式代替计算参数var。
ln(var, value = defualt value, name = 'renamed')可以实现重命名。
3.function updates参数
代码:
from theano import shared
state = shared(0)
inc = T.iscalar('inc')
accumulator = function([inc], state, updates=[(state, state+inc)])
笔记:
shared为共享变量,传入的参数为初始化赋值,如shared(0)即将state初始化为0。共享变量,其他函数也可改变该变量的值。updates只可以用于更新共享变量。格式为updates = [(state, state_formula)]。
4.function givens参数
代码:
fn_of_state = state * 2 + inc
foo = T.scalar(dtype=state.dtype)
skip_shared = function([inc, foo], fn_of_state, givens=[(state, foo)])
笔记:
givens是当你的公式中需要共享变量,而不需要共享变量的值的时候需求的参数。目的是用某个与共享变量同类型的变量替代共享变量,代入公式进行计算。格式为 givens=p[(shared_var, sub_var)]
T.scalar(dtyoe = state.type)用于确保变量类型一致
5.function 函数复制
代码:
state = shared(0)
inc = T.iscalar('inc')
accumulator = theano.function([inc], state, updates=[(state, state+inc)])
new_state = shared(0)
new_accumulator = accmulator.copy(swap = {state:new_state})
笔记:
一个已定义的函数调用copy,闯入一个字典(dictionary)类型的swap参数,字典目的是替换共享变量,格式为{old_var:new_var}
网友评论