【问题标题】:Why does python/ numpy += behave like this with arrays?为什么 python/numpy += 对数组有这样的行为?
【发布时间】: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

没有?

【问题讨论】:

    标签: python arrays numpy


    【解决方案1】:

    因为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
    

    另一种制作dWdWhy 的不同数组的方法是在开始时定义dWhy = dW.copy(),然后可以使用+= 独立地就地更改。

    【讨论】:

    • 为了清楚起见,我会说 "same object" ;)
    猜你喜欢
    • 1970-01-01
    • 2012-01-13
    • 1970-01-01
    • 1970-01-01
    • 2018-06-19
    • 1970-01-01
    • 2014-12-21
    • 2014-01-24
    • 1970-01-01
    相关资源
    最近更新 更多