代码之家  ›  专栏  ›  技术社区  ›  Zahid Hasan

OR函数的感知器不收敛

  •  1
  • Zahid Hasan  · 技术社区  · 7 年前

    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

    1 回复  |  直到 7 年前
        1
  •  3
  •   Umberto    7 年前

    我想说你错过了偏见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()