其他分享
首页 > 其他分享> > 实现单层感知器

实现单层感知器

作者:互联网

单层感知器

一个例子:【注释、解释在代码中】

假如设定b=0.7,x1、x2、x3的输入初始权重为0.5,0.6,0.4,且输入数据与标签如下:

testArray = np.array([[0,0,0,-1],
         [0,0,1,-1],
         [0,1,1,1],
         [1,1,0,1]])
import pandas as pd
testD = pd.DataFrame(testArray,index=None,columns=['x1','x2','x3','Y'])
testD

在这里插入图片描述

import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
# 输入数据 x1、x2、x3
X = np.array([[1,3,3],
            [1,4,3],
            [1,1,1]])

# 标签
Y = np.array([1,1,-1])
# 权值初始化,1行3列,取值范围-1~1
W = (np.random.random(3)-0.5)*2
# print(W)
#学习率设置
learn_rate=0.11
# 计算的迭代次数
n=0
# 神经网络输出
output_y = 0
def update():
    global X,Y,W,learn_rate,n
    n+=1
    output_y = np.sign(np.dot(X,W.T))
    W_change = learn_rate*(Y-output_y.T).dot(X)/int(X.shape[0])
    W = W_change+W  #改变参数W,相当于权重
   
for _ in range(100):
    update()#更新权值
    print(W) #打印当前权值
    print(n) #打印迭代次数
    output_y = np.sign(np.dot(X,W.T)) #计算当前输出
    if(output_y == Y.T).all(): #如果实际输出等于期望输出,模型收敛,循环结束。
        print("完成!")
        print("epoch:【已经收敛完毕】",n)
        break

#正样本
x1 = [3,4]
y1 = [3,3]
#负样本
x2 = [1]
y2 = [1]

# 计算机分界线的斜率以及截距
k = -W[1]/W[2]
d = -W[0]/W[2]
print("k=",k)
print("d=",d)

xdata = np.linspace(0,5)
plt.figure()
plt.plot(xdata,xdata*k+d,'r')
plt.plot(x1,y1,'bo')
plt.plot(x2,y2,'yo')
plt.show()

最终,迭代12次之后收敛趋于稳定。
在这里插入图片描述
观察图形可知有效的区分开了数据:
在这里插入图片描述

标签:感知器,实现,print,x2,plt,np,x3,x1,单层
来源: https://blog.csdn.net/qq_42658739/article/details/101096239