0

While I was implementing the 2-dimensional AND perceptron I ran into the error

free variable '...' referenced before assignment in enclosing scope

I looked it up online, and for most of the cases I understand why this error arises. But in my case I have no idea why this error arieses. I am quite new to python and I would be very grateful if you could point out my mistakes!:) Here's my code:

import numpy as np

b = 0 #bias
weights = np.array([0,0]) #weight
alpha = 0.5 #learning rate
input_data = np.array([([0,0], 0),([0,1],0),([1,0],0),([1,1], 1)])  #data points that we want to separate
d = np.array([input_data[i][1] for i in range(len(input_data))]) #d will not change
x = np.array([input_data[i][0] for i in range(len(input_data))]) #x is the positions of the data points. They do not change either.


def perceptron():
    #repeat until the input error is zero
    while True:
        output = np.array([np.dot(weights, x[i]) + b for i in range(len(x))]) #y will be updated for each round
        y = np.array([1 if output[i]>0 else 0 for i in range(len(output))])
        for i in range(len(x)):
            weights = weights + alpha * (d[i] - y[i]) * x[i]
            b = b + alpha * (d[i]- y[i])
        if np.array_equal(d,y):
            break
    return weights, b  

The error is:

free variable 'weights' referenced before assignment in enclosing scope

But I have already declared "weights" at the every first beginning, before I defined perceptron().

Dennis
  • 175
  • 1
  • 3
  • 8
  • 1
    `weights` is not defined in the scope of that function. Pass it in as an arg/kwarg or make it global. – MyNameIsCaleb May 17 '19 at 18:42
  • Possible duplicate of [Use of "global" keyword in Python](https://stackoverflow.com/questions/4693120/use-of-global-keyword-in-python) – rdas May 17 '19 at 18:42
  • More precisely: you cannot initialize a local variable using a global variable of the same name. – chepner May 17 '19 at 19:02

0 Answers0