import theano.tensor as T
from theano import (function, pp)
import numpyt as np
x = T.dscalar('x') # 宣告純量符號變數x, 預設type為doubleprint (type(x)) # theano.tensor.var.TensorVariable
print(x.type) # TensorType(float64, scalar)print (x.type is T.dscalar) # True
y = T.dscalar('y') # 宣告純量符號變數y, 預設type為double# symbolic expression
z = x + y
print(pp(z)) # 'x+y'# compile function([inputs], outputs), 第一次編譯時會花不少時間
f = function([x, y], z)
# call function
print(f(1,2)) # array(3.0)
print(f(3,4)) # array(7.0)print (np.allclose(f(16.3, 12.1), 28.4)) # True
如果將 x,y變數指定為matrix時,即為矩陣的加法如下:
import theano.tensor as T
from theano import function
import numpy as np
x = T.dmatrix('x')
y = T.dmatrix('y')
# symbolic expression
z = x + y
# compile function
f = function([x, y], z)
# call function
print(f(np.array([[1, 2], [3, 4]]), np.array([[10, 20], [30, 40]])))
# array([[ 11., 22.],# [ 33., 44.]])
import theano
import theano.tensor as T
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])
res = f([[1, 1], [1, 1]], [[0, 1], [2, 3]])
print(res[0]) # array([[ 1., 0.],[-1., -2.]])
print(res[1]) # array([[ 1., 0.],[ 1., 2.]]),
print(res[2]) # array([[ 1., 0.],[ 1., 4.]])]
函數輸入可使用預設值
In class可設定function中參數的預設值
也可以像dict替變數取名
from theano import In
from theano import function
import theano.tensor as T
x, y = T.dscalars('x', 'y')
z = x + y
f = function([x, In(y, value=1)], z)
print (f(33)) # array(34.0)
print( f(33, 2)) # array(35.0)
from theano import In
from theano import function
import theano.tensor as T
x, y, w = T.dscalars('x', 'y', 'w')
z2 = (x+y)*w
f2 = function([x, In(y, value=1), In(w, value=2, name='w_by_name') ], z2)
print(f2(33)) # array(68.0)
print(f2(33,2)) # array(70.0)
print(f2(33, w_by_name=1)) # array(34.0)
print(f2(33, w_by_name=1, y=0)) # array(33.0)
Example: logistic function
加、減、乘、除計算在theano中均為elementwise的計算。
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]]))
#array([[ 0.5 , 0.73105858],# [ 0.26894142, 0.11920292]])
Updates to shared variables can sometimes be done more quickly using in-place algorithms.
Theano has more control over where and how shared variables are allocated, which is one of the important elements of getting good performance on the GPU.