我正在努力实现一个单层感知器:http://en.wikipedia.org/wiki/Perceptron。我的程序,取决于权重,要么在学习循环中丢失,要么找到错误的权重。作为测试用例,我使用逻辑AND。你能告诉我为什么我的感知器不收敛吗?这是我自己学的。谢谢。在
# learning rate
rate = 0.1
# Test data
# logical AND
# vector = (bias, coordinate1, coordinate2, targetedresult)
testdata = [[1, 0, 0, 0], [1, 0, 1, 0], [1, 1, 0, 0], [1, 1, 1, 1]]
# initial weigths
import random
w = [random.random(), random.random(), random.random()]
print 'initial weigths = ', w
def test(w, vector):
if diff(w, vector) <= 0.1:
return True
else:
return False
def diff(w, vector):
from copy import deepcopy
we = deepcopy(w)
return dirac(sum(we[i]*vector[i] for i in range(3))) - vector[3]
def improve(w, vector):
for i in range(3):
w[i] += rate*diff(w, vector)*vector[i]
return w
def dirac(z):
if z > 0:
return 1
else:
return 0
error = True
while error == True:
discrepancy = 0
for x in testdata:
if not test(w, x):
w = improve(w, x)
discrepancy += 1
if discrepancy == 0:
print 'improved weigths = ', w
error = False
(z > 0.5)
。在看起来你需要一个围绕for循环的额外循环来迭代改进,直到你的解决方案收敛(你链接的Wikipedia页面的第3步)。在
现在,您只给每个训练案例一次更新权重的机会,所以它没有收敛的机会。在
相关问题 更多 >
编程相关推荐