簡體   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

為什么這兩種方法的結果相同(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

制作dWdWhy 2 個不同的 arrays 然后可以使用+=獨立就地更改的另一種方法是在開始時定義dWhy = dW.copy()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM