【发布时间】:2022-01-26 19:47:03
【问题描述】:
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
没有?
【问题讨论】:
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 的不同数组的方法是在开始时定义dWhy = dW.copy(),然后可以使用+= 独立地就地更改。
【讨论】: