-2

I have a strange behavior with a variable in the following code.

Why is the output of w3 at the end the same as w2? Its never been changed in the code, but in the end it has the same value as w2?

import numpy as np

inpt = np.array([[1]])

w1 = np.random.random((1,1))
w2 = np.random.random((1,1))

w3 = w2

print("First w3: ", w3)

n1 = np.dot(inpt, w1)
n2 = np.dot(n1, w2)

delta = 1 - n2

n1_d = np.dot(delta, w2.T)

w2 += np.dot(n1.T, delta)
w1 += np.dot(inpt.T, n1_d)

print("Second w3: ", w3)

print("Value of w2: ", w2)

First w3: [[ 0.98377014]]

Second w3: [[ 1.01105407]]

Value of w2: [[ 1.01105407]]

What am I doing wrong here?

  • 1
    Not a python expert so I might be wrong. Is it because w3 is just a reference to w2? So when you change w3, w2 reference's w3's new value. It changes after this line `w2 += np.dot(n1.T, delta)` – Barney Chambers Aug 02 '17 at 06:19
  • 1
    Use `w3 = np.copy(w2)` – Dima Chubarov Aug 02 '17 at 06:21
  • It looks like you're not clear on how Python variables and assignment work. Here's a [handy guide](https://nedbatchelder.com/text/names.html). – user2357112 Aug 02 '17 at 06:29
  • 1
    You may find this article helpful: [Facts and myths about Python names and values](http://nedbatchelder.com/text/names.html), which was written by SO veteran Ned Batchelder. – PM 2Ring Aug 02 '17 at 06:32
  • 1
    There's also some good, relevant info [here](https://stackoverflow.com/questions/2612802/how-to-clone-or-copy-a-list). That question is about plain Python lists, but much of the info is applicable to any mutable object in Python. – PM 2Ring Aug 02 '17 at 06:35

1 Answers1

0

w3 is just a reference to w2 so it will reflect the change in w2 when you update w2

Barney Chambers
  • 2,720
  • 6
  • 42
  • 78