A Type in Theano represents a set of constraints on potential data objects. These constraints allow Theano to tailor C code to handle them and to statically optimize the computation graph.
Theano对数据的类型要求很严格,因为Theano需要把函数等内容编译成C语言(所以控制台console在执行到theano.function(…)语句时会有明显的延迟)。如果程序运行过程中输入数据比函数中对应变量的精度要高,程序就会报错,要求你向下cast或对输入数据进行转换、
例:
import theano
import theano.tensor as T
from theano import function
import numpy
a = T.fvector('a') # declare variable
b = T.fvector('b')
out = a**2 + b**2 + 2*a*b
f = function([a,b],out) # compile function
print f(numpy.asarray([2.3, 5,7], dtype = numpy.float32),numpy.asarray([4.4, 5,6],dtype = numpy.float32)) # 1st time call function
print f([2.3, 5,7],[4.4, 5,6]) # 2nd time call function
运行结果
[ 44.88999939 100. 169. ]
TypeError: ('Bad input argument to theano function with name "E:/.../.py:26" at index 0(0-based)',
'TensorType(float32, vector) cannot store accurately value [2.3, 5, 7],
If you do not mind this precision loss, you can:
1) explicitly convert your data to a numpy array of dtype float32,
or 2) set "allow_input_downcast=True" when calling "function".', [2.3, 5, 7])
[2.3, 5,7]默认是float64格式,fvector中的元素是float32格式。第一次调用函数时用numpy显式把数组转为float32格式,所以运行正常。第二次调用函数时报错TypeError,提示无法用float32准确表示数值2.3。
theano.tensor模块中的数据格式都可以在官网找到:
http://deeplearning.net/software/theano/library/tensor/basic.html#libdoc-tensor-creation