其作用在於調試。
這與不設定function的另一個調用形式相對應,
z.eval({x: 16.3, y:12.1})
亦可以使用諸如 T.dmatrices('a', 'b')這樣的方法一次初始化多個自變量矩陣。
類似於partial的默認參數綁定方法,In.
但其行爲與partial的實現不同,後者是永久性對函數對象參數進行修改,而前者
提供函數的默認參數。
甚至這種方法可以對函數提供默認參數的別名,這爲改變參數的序提供了方便。
這類似於C++中的靜態變量。(在機理上)
設定了shared變量後,可以利用update參數實現shared變量的改變。(更新)
這裏值得注意的一點是變量的更新是在函數返回之後,否則初值的設定就沒有意義
了。
shared變量的意義不僅僅在於如同全局常量的意義,theano定義了這個變量可以
作爲輸出等,這使得其具備微分等數學性質。這也有運行速度上考慮的意義。
但這裏要注意應當將用於替換的變量與state變量聲明爲相同類型。(state.dtype)
設定copy參數delete_update爲True可以將拷貝的函數的update行爲刪掉。
#from theano import *
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)
print f(2, 3)
print type(f(2, 3))
x = T.dmatrix('x')
y = T.dmatrix('y')
z = x + y
f = function([x, y], z)
print f([[1, 2], [3, 4]], [[10, 20], [30, 40]])
import theano
a = theano.tensor.vector()
out = a + a ** 10
f = theano.function([a], out)
print f([0, 1, 2])
b = theano.tensor.vector()
out = a ** 2 + b ** 2 + 2 * a * b
f = theano.function([a, b], out)
print f([0], [2])
import theano
import theano.tensor as T
x = T.dmatrix('x')
s = 1 / (1 + T.exp(-x))
logistic = theano.function([x], s)
print logistic([[0, 1], [-1, -2]])
s2 = (1 + T.tanh(x / 2)) / 2
logistic2 = theano.function([x], s2)
print logistic2([[0, 1], [-1, -2]])
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])
print f([[1, 1], [1, 1]], [[0, 1], [2, 3]])
from theano import In
x, y = T.dscalars('x', 'y')
z = x + y
f = function([x, In(y, value = 1)], z)
print f(33)
print f(33, 2)
x, y, w = T.dscalars('x', 'y', 'w')
z = (x + y) * w
f = function([x, In(y, value = 1), In(w, value = 2, name = 'w_by_name')], z)
print f(33)
print f(33, 2)
print f(33, 0, 1)
print f(33, w_by_name = 1)
print f(33, w_by_name = 1, y = 0)
from theano import shared
state = shared(0)
inc = T.iscalar('inc')
accumulator = function([inc], state, updates = [(state, state + inc)], on_unused_input='ignore')
print state.get_value()
print accumulator(1)
print state.get_value()
print accumulator(300)
print state.get_value()
state.set_value(-1)
accumulator(3)
print (state.get_value())
decrementor = function([inc], state, updates = [(state, state - inc)])
print decrementor(2)
print state.get_value()
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()
state.set_value(10)
new_state = theano.shared(0)
new_accumulator = accumulator.copy(swap = {state: new_state})
print new_accumulator(100)
print new_state.get_value()
print state.get_value()
null_accumulator = accumulator.copy(delete_updates=True)
print null_accumulator(9000)
print state.get_value()