使用Theano处理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 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()

最新更新