Home > database >  How do I fix my collab notebook always updating a numpy array regardless of my if conditions?
How do I fix my collab notebook always updating a numpy array regardless of my if conditions?

Time:10-22

I am using collab for a perceptron problem, and am trying to record the best set of values found so far. I used the following relevant code:

if errors_[i] <= besterrors:  
              besterrors = errors_[i]  
              Wbest = W  
              bestiteration = i 1 

Where W is the current array I am using. When running through iterations, I print the best scores shown in the code below:

print("Best Weights: ", Wbest)  
print("On iteration: ", bestiteration)  

I find that bestiteration updates correctly in the final result, however Wbest always updates to the most recent W regardless of the condition. There are no other sections that use the variable Wbest aside from an initial definition (that is unrelated to W) and removing "Wbest = W" causes Wbest to not update at all.

Is there a strange behaviour of numpy arrays that could cause all arrays generated by numpy.zeros to update simultaneously, or whether collab is causing strange behaviour?

CodePudding user response:

Use .copy() method:

if errors_[i] <= besterrors:  
    besterrors = errors_[i]  
    Wbest = W.copy()
    bestiteration = i 1 
  • Related