Python 单层感知器
我正在努力实现一个单层感知器:。根据权重,我的程序要么在学习循环中丢失,要么找到错误的权重。作为测试用例,我使用逻辑AND。你能告诉我为什么我的感知器不能收敛吗?这是为了我自己的学习。谢谢Python 单层感知器,python,perceptron,Python,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],
# 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
#学习率
比率=0.1
#测试数据
#逻辑与
#向量=(偏差、坐标1、坐标2、目标结果)
testdata=[[1,0,0,0],[1,0,1,0],[1,1,0,0],[1,1,1,1]]
#初始重量
随机输入
w=[random.random(),random.random(),random.random()]
打印“初始重量=”,w
def测试(w,矢量):
如果差值(w,矢量)为0:
返回1
其他:
返回0
错误=真
当error==True时:
差异=0
对于testdata中的x:
如果未进行试验(w,x):
w=改善(w,x)
差异+=1
如果差异==0:
打印“改进的重量=”,w
错误=错误
看起来您需要一个额外的循环来围绕for循环迭代改进,直到您的解决方案趋于一致(您链接的Wikipedia页面中的步骤3)
现在,您只给每个训练案例一次更新权重的机会,因此它没有收敛的机会
(z>0.5)
也许使用打印语句或调试器?更好的问题。谢谢。它非常容易实现。我开始想也许是因为我一次又一次地改变体重,但我应该同时改变它们。我将使用参数。