Python 更改无共享变量不会影响内部变量的值

Python 更改无共享变量不会影响内部变量的值,python,theano,Python,Theano,我对共享变量有点小问题。代码如下: 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='float3

我对共享变量有点小问题。代码如下:

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**
但是,下面的工作:

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**
我无法理解共享变量的逻辑,希望得到帮助

共享变量封装一段内存,但不能保证在整个计算过程中只使用用于初始化共享变量的内存

borrow=True
应被视为在所有情况下都应遵循的提示,而不是明确的指令

在第一个示例中,共享变量包装了初始numpy数组,因为
borrow=True
。因此,更改numpy数组会更改共享变量的内容。但这不应该被依赖,对于Theano编程来说是一个糟糕的实践

在第二个示例中,
s_true+=1.0
是一个符号表达式。它实际上不会改变内存中的任何状态,只会使
s_为真
指向表示表达式而不是共享变量的对象
print s_true.eval()
显示执行符号计算的结果,但不会更改共享变量。更改共享变量内容的唯一“批准”方法是通过
shared\u var.set\u value(…)
或通过
theano.function(…)
updates=…
机制。如第一个示例中所示,更改备份存储有时会起作用,但并非总是如此,通常应避免

第三个例子只是做第一个例子的一种更迂回的方式,所以也是一种不好的做法


可能会有帮助。

我是一个新的theano用户,所以我认为“+=”将更改共享变量。现在我知道更改共享变量的适当方法是通过设置值或更新。但我发现,即使我使用set_value或updates来更改s_true,它也不会更改内部存储(np_数组)的值。所以,当s_true包装np_数组时,这个操作背后实际上是做什么的呢。这不是真的吗?就像引用np\u数组一样?当原始numpy数组被Theano共享变量包装后,您应该忘记它。绝对不能保证它们指向相同的内存位。(1) 创建初始值numpy数组,(2)为无共享变量指定初始值,(3)忘记初始值numpy数组和无共享变量之间有任何链接,(4)更新共享变量,(5)通过get_value()获取更新值。