机器学习入门--and(or)感知机

参考网站:https://www.zybuluo.com/hanbingtao/note/433855

分析:and是一个二元函数,带有两个参数x_{1}x_{2},可以通过一个感知机模拟此二元函数运算

实现思路:

激活函数选择阶跃函数

权重weight和偏置bias更新方法如下:w_{i}\leftarrow w_{i}+\Delta w_{i}b\leftarrow b+\Delta b;(其中\Delta w_{i}=lr(t-y)x_{i}\Delta b = lr(t-y)t是训练样本的实际值(label)lr是学习率,y是感知器的输出值)

实现步骤:

1)定义感知机中所需要的权重weight(and感知机包含两个输入x,每个输入都需要一个权重)和偏置bias,我这里只将这两个量定义在一个类中,也可以不定义在类中;

#类 -- 集合中每个对象所共有的属性和方法
class Perceptron:
    def __init__(self):
        self.weight = [0.0,0.0]
        self.bias = 0.0

2)定义输入向量input,标签label,学习率learnRate,学习迭代次数lun;

3)计算and感知机输出值,即对应输入x与对应权重w乘积,再加上偏置b;

4)利用激活函数(这里选择阶跃函数)激活上一步得到的值;

5)更新权重(我单独定义的权重更新函数updateWeight);

6)重复1)-5),仅仅需要3轮迭代即可实现;

实现代码:

import os
import perceptron

def activatorRelu(val):
    if val>0:
        return 1
    else:
        return 0
def updateWeight(label,weight,bias,rate,output,input):
    delta = label - output
    w1 = delta*input[0]*rate+weight[0]
    w2 = delta*input[1]*rate+weight[1]
    bias = bias+rate*delta
    return [w1,w2],bias

def calcOutput(x1,x2,w1,w2,b):
    return x1*w1+x2*w2+b

if __name__=="__main__":
    #初始化,赋初值
    p1 = perceptron.Perceptron()
    print(p1.weight)
    print(p1.bias)

    input = [[0,0],[0,1],[1,0],[1,1]]
    label = [0,0,0,1]
    learnRate = 0.1
    lun=0;
    #训练迭代,更新权重、偏置
    while lun<=2:
        for x in input:
            print("lun:",lun,x)
            output = calcOutput(x[0],x[1],p1.weight[0],p1.weight[1],p1.bias)
            print("before activate output:",output)
            output = activatorRelu(output)
            print("after activate output:",output)
            # raise "\nend****"
            print("label:",label[input.index(x)],"index:",input.index(x))
            p1w,p1b = updateWeight(label[input.index(x)],p1.weight,p1.bias,learnRate,output,x)
            p1.weight,p1.bias = p1w,p1b
            print(p1.weight,p1.bias)
            print("\n******************************************\n")
        lun = lun + 1
    
    #预测过程
    preInput = [0,1]
    output = calcOutput(preInput[0],preInput[1],p1.weight[0],p1.weight[1],p1.bias)
    print("predict output:",output)
    output = activatorRelu(output)
    print("predict output:",output)

3次迭代运算之后,w_{1}=0.2;w_{2}=0.1;b=-0.1,即可实现我们需要的and(or)感知机功能。

4次迭代运算之后,w_{1}=0.2;w_{2}=0.1;b=-0.2,并且后续过程一直保持稳定

猜你喜欢

转载自blog.csdn.net/lantuxin/article/details/81078838