0
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 = dW + np.sum(x)
dWhy = dWhy + x

does not?

1 Answer 1

2

Because dWhy = dW makes them the same array. += 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.

Sign up to request clarification or add additional context in comments.

1 Comment

I would say "same object" for clarity ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.