神经网络--单层感知器

python 代码

import numpy as np
import matplotlib.pyplot as plt

#输入数据
X = np.array([[1,2,4],
              [1,3,3],
              [1,5,2],
              [1,1,2],
              [1,1,3],
              [1,2,1]
             ])
#标签
Y = np.array([1,1,1,-1,-1,-1] )
#权值初始化,1行3列,取值范围-1到1
W = (np.random.random(3)-0.5)*2
print(W)
#学习率设置
lr = 0.5
#神经网络输出
O = 0
n=0
X.shape[0]

def update():
    global X,Y,W,lr,n,O
    n+=1
    O = np.sign(np.dot(X,W.T))
    #print('mat:O')
    #print(O)
    #print(Y-O)
    W_C = lr*((Y-O).dot(X))/int(X.shape[0])
    W = W + W_C

for _ in range(1000):
    update()#更新权值
    #print(W)#打印当前权值
    #print(n)#打印迭代次数
    #O = np.sign(np.dot(X,W.T))#计算当前输出
    if(O == Y.T).all(): #如果实际输出等于期望输出,模型收敛,循环结束
        print(W)
        print('loop:',n)
        print('Finished')
        break
        
    #正样本
row=X.shape[0]
half=int(row/2)


x1 = X[0:half,1]
y1 = X[0:half,2]
#负样本
x2 = X[half:row,1]
y2 = X[half:row,2]

#计算分界线的斜率以及截距
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()

输出:

[-0.68791     0.26176538  0.22569507]
[-4.68791     1.26176538  0.5590284 ]
loop: 39
Finished
k= -2.257068484812345
d= 8.385817265458877

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值