How to get value from a theano tensor variable backed by a shared variable?

坚强是说给别人听的谎言 提交于 2020-01-01 02:33:05

问题


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.])

回答1:


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.

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()

and you should see the result

array([1, 2, 3], dtype=int32)

(And in the case y = x + z, you would have to do y.eval({z : 3.}), for example)



来源:https://stackoverflow.com/questions/31361377/how-to-get-value-from-a-theano-tensor-variable-backed-by-a-shared-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!