我有以下代码:
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()
关于gpu - CPU和GPU与Theano的不同结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32804790/