简单感知机的实现

感知机算法初步实现

import numpy as np
# 阶跃函数
def f(y):
    return 1 if y>0 else 0

def And():
    x = np.array([[0,0],[0,1],[1,0],[1,1]])#数据集
    w = np.array([0.038,0.044])
    c = 0.042 #阈值
    a = 0.015 #学习速率a
    b = 0.006 #学习速率b
    d=[0,0,0,1] #期望输出
    e=0 #误差  
   for i in range(4):
       s = np.sum(w*x[i])-c
       y = f(s)
       e = d[i] - y  
       w = w+a*e*x[i]
       c = np.sum(c+b*e)  
       print(w, c)

if __name__ == '__main__':
    And()

感知机实现进一步改进

import numpy as np
# 阶跃函数
def f(y):
    return 1 if y>0 else 0

def And():
    x = np.array([[0,0],[0,1],[1,0],[1,1]])#数据集
    w = np.array([0.038,0.044])
    c = 0.042 #阈值
    a = 0.015 #学习速率a
    b = 0.006 #学习速率b
    d=[0,0,0,1] #期望输出
    e=0 #误差
    while True:
        num_errors=0
        for i in range(4):
            s = np.sum(w*x[i])-c
            y = f(s)
            e = d[i] - y  
            w = w+a*e*x[i]
            c = np.sum(c+b*e)  
            # 判断是否误分类
            
            if e != 0:
                num_errors += 1
            #print(e)
        if num_errors == 0:
            print(w, c)
            break
            
if __name__ == '__main__':
    And()

感知机实现加上画图

import numpy as np
import matplotlib.pyplot as plt


def f(y):
    return 1 if y > 0 else 0


def And():
    x = np.array([[0, 0], [0, 1], [1, 0], [1, 1]])  # 数据集
    w = np.array([0.038, 0.044])
    c = 0.042  # 阈值
    a = 0.015  # 学习速率a
    b = 0.006  # 学习速率b
    d = [0, 0, 0, 1]  # 期望输出
    e = 0  # 误差
    while True:
        num_errors = 0
        for i in range(4):
            s = np.sum(w * x[i]) - c
            y = f(s)
            e = d[i] - y
            w = w + a * e * x[i]
            c = np.sum(c + b * e)
            #  判断是否误分类

            if e != 0:
                num_errors += 1
            #print(e)
        if num_errors == 0:
            print(w, c)
            break

    # x = np.random.ranf(20) # 0到1的均匀分布
    x = np.random.uniform(-0.1,1.2,100) # 指定在0.0~1.2均匀分布
    y = -(w[0] * x-c) / w[1]

    plt.plot(x, y, 'g')
    # # # 画出训练集中的点
    plt.scatter(0, 0, c='r')
    plt.scatter(0, 1, c='r')
    plt.scatter(1, 0, c='r')
    plt.scatter(1, 1, c='b')
    plt.show()


if __name__ == '__main__':
    And()
发布了1 篇原创文章 · 获赞 0 · 访问量 11

猜你喜欢

转载自blog.csdn.net/qq_30230591/article/details/105266208