[英]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
为什么这两种方法的结果相同(dW = dWhy),当
dW = dW + np.sum(x)
dWhy = dWhy + x
才不是?
因为dWhy = dW
使它们成为相同的数组。 +=
不是重新定义(重新分配),它会就地更改值。
dW += np.sum(x) # affects both since they are the same object
dWhy += x # affects both since they are the same object
除非您稍后重新定义(重新分配)其中之一。
dW = dW + np.sum(x) # redefines dW
dWhy = dWhy + x # redefines dWhy
制作dW
和dWhy
2 个不同的 arrays 然后可以使用+=
独立就地更改的另一种方法是在开始时定义dWhy = dW.copy()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.