一、两个标量(scalar)求和
>>> import numpy
>>> 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)
返回值z即为x+y
>>> f(2, 3)
array(5.0)
>>> numpy.allclose(f(16.3, 12.1), 28.4)
True
theano 中,所有的符号都必须指定类型
eval的好处是,无需import function,如下
>>> import numpy
>>> import theano.tensor as T
>>> x = T.dscalar('x')
>>> y = T.dscalar('y')
>>> z = x + y
>>> numpy.allclose(z.eval({x : 16.3, y : 12.1}), 28.4)
True
二、两个矩阵(matrices)求和
import numpy
import theano.tensor as T
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]])
输出结果为
[[ 11. 22.]
[ 33. 44.]]
由于变量是NumPy array,因此可以直接采用NumPy array作为输入
import numpy
f(numpy.array([[1, 2], [3, 4]]), numpy.array([[10, 20], [30, 40]]))
结果同上下面给出变量类型
- byte:
bscalar, bvector, bmatrix, brow, bcol, btensor3, btensor4
- 16-bit integers:
wscalar, wvector, wmatrix, wrow, wcol, wtensor3, wtensor4
- 32-bit integers:
iscalar, ivector, imatrix, irow, icol, itensor3, itensor4
- 64-bit integers:
lscalar, lvector, lmatrix, lrow, lcol, ltensor3, ltensor4
- float:
fscalar, fvector, fmatrix, frow, fcol, ftensor3, ftensor4
- double:
dscalar, dvector, dmatrix, drow, dcol, dtensor3, dtensor4
- complex:
cscalar, cvector, cmatrix, crow, ccol, ctensor3, ctensor4
http://deeplearning.net/software/theano/tutorial/adding.html