简体   繁体   English

为什么 python/numpy += 与 arrays 的行为类似?

[英]Why does python/ numpy += behave like this with arrays?

import numpy as np
x = np.arange(20)
x = np.reshape(x, (4,5))
dW = np.zeros(x.shape)
dWhy = dW
dW += np.sum(x)
dWhy += x

Why do the two methods results in the same result (dW = dWhy), when为什么这两种方法的结果相同(dW = dWhy),当

dW = dW + np.sum(x)
dWhy = dWhy + x

does not?才不是?

Because dWhy = dW makes them the same array.因为dWhy = dW使它们成为相同的数组。 += is not a redefinition (reassignment), it changes the values inplace. +=不是重新定义(重新分配),它会就地更改值。

dW += np.sum(x) # affects both since they are the same object
dWhy += x  # affects both since they are the same object

Unless you redefine (reassign) one of them later.除非您稍后重新定义(重新分配)其中之一。

dW = dW + np.sum(x) # redefines dW
dWhy = dWhy + x # redefines dWhy

Another way to make dW and dWhy 2 different arrays that can then be changed inplace independently with += would be to define dWhy = dW.copy() at the start.制作dWdWhy 2 个不同的 arrays 然后可以使用+=独立就地更改的另一种方法是在开始时定义dWhy = dW.copy()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM