我有以下代码:
import theano
import theano.tensor as T
import numpy as np
x = theano.shared(np.asarray([1, 2, 3], dtype=theano.config.floatX), borrow=True)
y = T.cast(x, 'int32')
print 'type of y: ', type(y)
print 'type of y.owner.inputs[0]: ', type(y.owner.inputs[0])
print 'value of y: ', y.owner.inputs[0].get_value(borrow=True)
与CPU一起运行
$ THEANO_FLAGS=mode=FAST_RUN,device=cpu,floatX=float32 python test_share.py
type of y: <class 'theano.tensor.var.TensorVariable'>
type of y.owner.inputs[0]: <class 'theano.tensor.sharedvar.TensorSharedVariable'>
value of y: [ 1. 2. 3.]
与GPU一起运行
$ THEANO_FLAGS=mode=FAST_RUN,device=gpu,floatX=float32 python test_share.py
Using gpu device 0: GeForce 310M
type of y: <class 'theano.tensor.var.TensorVariable'>
type of y.owner.inputs[0]: <class 'theano.tensor.var.TensorVariable'>
value of y:
Traceback (most recent call last):
File "test_share.py", line 10, in <module>
print 'value of y: ', y.owner.inputs[0].get_value(borrow=True)
AttributeError: 'TensorVariable' object has no attribute 'get_value'
如何获得与CPU相同的结果?
通常,用于访问计算图中的子节点的方法.owner.inputs[0]
不适用于跨平台代码。
您调用共享变量,x
以便访问x
值的正确方法是使用x.get_value()
。
此代码应在CPU和GPU上相同地运行:
import theano
import theano.tensor as T
import numpy as np
x = theano.shared(np.asarray([1, 2, 3], dtype=theano.config.floatX), borrow=True)
y = T.cast(x, 'int32')
print 'type of y: ', type(y)
print 'type of x: ', type(x)
print 'value of x: ', x.get_value(borrow=True)
如果要查看将符号转换操作应用于x
的结果(调用的符号结果)y
,则可以执行以下操作:
print 'value of y: ', y.eval()
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句