如何从共享变量支持的theano张量变量中获取值? [英] How to get value from a theano tensor variable backed by a shared variable?
问题描述
我有一个通过转换共享变量创建的theano张量变量.如何提取原始值或强制转换值? (我需要这样做,因此不必携带原始的shared/numpy值.)
I have a theano tensor variable created from casting a shared variable. How can I extract the original or casted values? (I need that so I don't have to carry the original shared/numpy values around.)
>>> 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.])
推荐答案
get_value
仅适用于共享变量. TensorVariables
是通用表达式,因此可能需要额外的输入才能确定其值(假设您设置了y = x + z
,其中z
是另一个张量变量.您需要先指定z
才能计算y
).您可以创建一个函数来提供此输入,也可以使用eval
方法在字典中提供它.
get_value
only works for shared variables. TensorVariables
are general expressions and thus potentially need extra input in order to be able to determine their value (Imagine you set y = x + z
, where z
is another tensor variable. You would need to specify z
before being able to calculate y
). You can either create a function to provide this input or provide it in a dictionary using the eval
method.
根据您的情况,y
仅取决于x
,因此您可以这样做
In your case, y
only depends on x
, so you can do
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
情况下,您必须执行y.eval({z : 3.})
)
(And in the case y = x + z
, you would have to do y.eval({z : 3.})
, for example)
这篇关于如何从共享变量支持的theano张量变量中获取值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!