I am trying to code a simple algorithm that will learn the weights and the threshold to be able to draw the line w1*x + w2*y = threshhold such that it follows the data of any training set (in this case the AND gate training set).
However, it seems my program is not learning, and the error is always at -3, no matter how many iterations I let if have.
Below is my code:
import numpy
import random
w1 = random.uniform(-0.2, 0.2)
w2 = random.uniform(-0.2, 0.2)
threshhold = random.uniform(-0.2, 0.2)
training_x = numpy.asarray([[0,0], [0,1], [1,0], [1,1]])
out = [0,0,0,1]
def positive(number):
if(number >= 0):
return 1
else:
return 0
error = numpy.array([0,0,0,0])
for j in range(len(training_x)):
check = positive(numpy.dot(numpy.asarray([w1,w2]), training_x[j]) + threshhold)
error[j] = out[j] -check
errornumber = numpy.sum(error)
iterations = 1000
count = 1
eta = 0.1
values = [w1, w2, threshhold]
while count < iterations and errornumber != 0:
for j in range(len(training_x)):
check = positive(numpy.dot(numpy.asarray([w1,w2]), training_x[j]) + threshhold)
error[j] = out[j] -check
w1 = values[0] + eta * error[j]*training_x[j][0]
w2 = values[1] + eta * error[j]*training_x[j][0]
threshhold = values[2] + eta*training_x[j][0]
values = [w1, w2, threshhold]
errornumber = numpy.sum(error)
print("ERRORS: " + str(errornumber))
count += 1
print("w1 " + str(values[0]) + "w2 " + str(values[1]) + "theta " + str(values[2]))
print("count " + str(count))
I would appreciate any help.
By the way, I took inspiration from this website: https://medium.com/analytics-vidhya/implementing-perceptron-learning-algorithm-to-solve-and-in-python-903516300b2f
Thanks in advance!