1

我正在实现一个简单的感知器用于在Python中对OR函数进行分类。但是错误不会交谈。任何建议将不胜感激。OR函数感知器不会收敛

def activation_function(x): 
    if x<0: 
     return 0 
    else: 
     return 1 

training_set = [((0, 0), 0), ((0, 1), 1), ((1, 0), 1), ((1, 1), 1)] 

w = random.rand(2) 
errors = [] 
eta = .2 
n = 100 

for i in range(n): 
    for x, y in training_set: 
     u = sum(x*w)   
     error = y - activation_function(u)  
     errors.append(error) 

     for index, value in enumerate(x): 
      w[index] += eta * error * value 

ylim([-1,1]) 
plot(errors) 

错误情节:

enter image description here

回答

3

我会说你缺少偏差b ...

如果添加它,它精美的收敛。

enter image description here

import numpy as np 
import matplotlib.pyplot as py 

np.random.seed(42) 
w = np.random.rand(2) 
b = 0 
errors = [] 
eta = .2 
n = 10 

for i in range(n): 
    for x, y in training_set: 
     u = np.sum(x*w)+b  
     error = y - activation_function(u)  
     errors.append(error) 

     for index, value in enumerate(x): 
      #print(index, " ", value) 
      w[index] += eta * error * value 
      b += eta*error 

注意,我导入的库不同于你一些更合理的名字,让我知道它的功能来自...让我知道如果这能帮助你...

顺便说一下,这是分类的结果。我希望这些颜色是有意义的......红色和蓝色有点华丽,但你明白了。请注意,你可以找到这个问题的无限解决方案。所以如果你改变随机种子,你会得到一个不同的线,将线性分离你的点。

enter image description here

另外你的算法并不因为当你有你的线穿过(0,0)收敛,虽然你的预测是错误的,权重不会因为value=0这个特定点进行更新。所以问题是你的更新不会做任何事情。这就是你的错误波动的原因。

编辑根据要求我写了一个小教程(一个Jupyter笔记本)的例子如何绘制一个分类器的决策边界。你可以找到它在github上

的github仓库:https://github.com/michelucci/python-Utils

希望它是有用的。

编辑2:如果你想快速,非常脏版(我用红色和蓝色的情节之一)这里是代码

lim = 3.0 
X1 = [x1 for x1 in np.arange(-lim,lim,0.1)] 
X2 = [x2 for x2 in np.arange(-lim,lim,0.1)] 
XX = [(x1,x2) for x1 in np.arange(-lim,lim,0.1) for x2 in np.arange(-lim,lim,0.1)] 
Xcolor = ["blue" if np.sum(w[0]*x1+w[1]*x2)+b > 0 else "red" for x1 in X1 for x2 in X2] 
x,y = zip(*XX) 
py.scatter(x,y, c = Xcolor) 
py.scatter(0,0, c = "black") 
py.scatter(1,0, c = "white") 
py.scatter(0,1, c = "white") 
py.scatter(1,1, c = "white") 
py.show() 
+0

你能请张贴在这里的代码决策边界?非常感谢你的出色解释! –

+0

嗨,我写了一篇关于如何绘制决策边界的教程。享受:)让我知道,如果它可以帮助你。 – Umberto