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

2024-05-16 19:59:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个theano张量变量,它是通过转换一个共享变量创建的。如何提取原始值或铸造值?(我需要这样做,所以不必携带原始的shared/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.])

Tags: numpytruemostgetvaluetheanofloatshared
1条回答
网友
1楼 · 发布于 2024-05-16 19:59:10

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

你应该看看结果

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

(例如,在y = x + z的情况下,您必须执行y.eval({z : 3.})

相关问题 更多 >