共享变量有点问题。代码如下:
np_array = numpy.ones(2, dtype='float32')
s_true = theano.shared(np_array,borrow=True)
np_array+=1.
print s_true.get_value()#[ 2. 2.] change np_array will change s_true
我能理解以上内容。但是反向不能工作,如下所示:
np_array = numpy.ones(2, dtype='float32')
s_true = theano.shared(np_array,borrow=True)
s_true+=1.0
print s_true.eval() #[ 2. 2.]
np_array #array([ 1., 1.], dtype=float32) **change s_true will not change np_array**
但是,以下工作:
s_true = theano.shared(np_array,borrow=True)
v_true=s_true.get_value(borrow=True,return_internal_type=True)
v_true+=1.0
print s_true.get_value() #[ 2. 2.] **change v_true will change s_true**
np_array #array([ 2., 2.], dtype=float32) **change v_true will change np_array**
我不能理解共享变量的逻辑,希望得到帮助
在theano-users mailing list回答。你知道吗
共享变量封装了一段内存,但不能保证在整个计算过程中只使用用于初始化共享变量的内存。你知道吗
borrow=True
应该被认为是一个提示,而不是在任何情况下都要遵循的明确指示。你知道吗在第一个示例中,共享变量包装初始numpy数组,因为
borrow=True
。因此,更改numpy数组会更改共享变量的内容。但是这不应该被依赖,而且对于无编程来说是一个糟糕的实践。你知道吗在第二个例子中,
s_true+=1.0
是一个符号表达式。实际上,表示共享状态的变量在另一个点而不是在另一个点上改变。print s_true.eval()
显示执行符号计算的结果,但不会更改共享变量。更改共享变量内容的唯一“批准”方法是通过shared_var.set_value(...)
或通过theano.function(...)
的updates=...
机制。如第一个示例中所示,更改备份存储有时会起作用,但并不总是这样,通常应该避免。你知道吗第三个例子只是做第一个例子的一种更迂回的方式,所以也是不好的做法。你知道吗
This page in the documentation可能会有帮助。你知道吗
相关问题 更多 >
编程相关推荐