[英]Simple AND Gate Perceptron Learning in Python
我正在尝试编写一个简单的算法,该算法将学习权重和阈值,以便能够绘制w1*x + w2*y = threshhold
线,使其遵循任何训练集的数据(在本例中为 AND 门训练放)。 然而,我的程序似乎没有学习,错误总是在-3,不管我让多少次迭代。 下面是我的代码:
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))
我将不胜感激任何帮助。
顺便说一句,我从这个网站获得灵感: https://medium.com/analytics-vidhya/implementing-perceptron-learning-algorithm-to-solve-and-in-python-903516300b2f
提前致谢!
我重写了算法,现在可以完美运行了。
import random
trainingset = [[0,0,0], [0,1,0], [1,0,0], [1,1,1]]
eta = 0.3
maxiterations = 100
w1 = random.uniform(-0.2, 0.2)
w2 = random.uniform(-0.2, 0.2)
w0 = random.uniform(-0.2, 0.2)
error = random.uniform(-0.2, 0.2)
count = 0
while count < maxiterations and error != 0:
error = 0
for array in trainingset:
target = array[2]
output = 0
summation = w1*array[0] + w2*array[1] - w0
if(summation > 0):
output = 1
else:
output = 0
if(output != target):
error += 1
w1 += eta*(target - output)*array[0]
w2 += eta*(target - output)*array[1]
w0 += eta*(target - output)*(-1)
print("output " + str(output) + " target " + str(target))
print("ERROR " + str(error))
count += 1
print("COUNT " + str(count))
print("ENDING ERROR" + str(error))
print("w1 " + str(w1) + "w2 " + str(w2) + "w0 " + str(w0))
尝试调整学习率“eta”。 当我设置 eta = 0.005 时,它会收敛 - 但我可能必须重新运行它 3-5 次以获得不同的随机初始化。
示例 output:
错误:1
错误:1
错误:1
错误:1
错误:0
w1 -0.142054790891668 w2 0.11580039178422052 theta -0.09818819751599175
数 6
编辑
再运行几次后,我得到了这个解决方案:ERRORS: 1
错误:1
错误:1
...
错误:1
错误:1
错误:0
w1 0.04909721513572815 w2 0.04279261178484681 theta -0.08081630077876589
数 20
它确实具有按照您希望的方式划分图形的属性,用于 AND 门。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.