如何从共享变量支持的theano tensor变量中获取值?

时间:2015-07-11 20:13:34

标签: python numpy scipy theano

我有一个通过转换共享变量创建的theano tensor变量。如何提取原始值或已转换值? (我需要这样,所以我不必携带原始的共享/ numpy值。)

>>> x = theano.shared(numpy.asarray([1, 2, 3], dtype='float'))
>>> y = theano.tensor.cast(x, 'int32')
>>> y.get_value(borrow=True)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'TensorVariable' object has no attribute 'get_value'
# whereas I can do this against the original shared variable
>>> x.get_value(borrow=True)
array([ 1.,  2.,  3.])

1 个答案:

答案 0 :(得分:14)

get_value仅适用于共享变量。 TensorVariables是通用表达式,因此可能需要额外的输入以便能够确定它们的值(想象一下,您设置y = x + z,其中z是另一个张量变量。您需要指定{在能够计算z之前{1}}。您可以创建一个函数来提供此输入,也可以使用y方法在字典中提供它。

在您的情况下,eval仅取决于y,因此您可以

x

你应该看到结果

import theano
import theano.tensor as T

x = theano.shared(numpy.asarray([1, 2, 3], dtype='float32'))
y = T.cast(x, 'int32')
y.eval()

(在array([1, 2, 3], dtype=int32) 的情况下,您必须执行y = x + z,例如)