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

ted*_*ddy 13 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.])
Run Code Online (Sandbox Code Playgroud)

eic*_*erg 15

get_value仅适用于共享变量.TensorVariables是一般表达式,因此可能需要额外的输入,以便能够确定它们的值(想象一下你设置y = x + z,在哪里z是另一个张量变量.你需要z在能够计算之前指定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()
Run Code Online (Sandbox Code Playgroud)

你应该看到结果

array([1, 2, 3], dtype=int32)
Run Code Online (Sandbox Code Playgroud)

(在这种情况下y = x + z,你必须做y.eval({z : 3.}),例如)