单层感知器代码完整实例

np.random.random(10)是生成10个0-1的随机数,没有负值。
numpy.random.rand()产生从[0,1)[0,1)[0,1)之间的随机数,没有负值。
numpy.random.randn()产生服从正态分布的随机数,会出现负值。
三个输入神经元,一个输出神经元。

import numpy as np
import matplotlib.pyplot as plt
# 输入数据
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)

#学习率设置
lr = 0.1
# 计算迭代次数
n = 0
#神经网络输出
O = 0

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

    return W
for _ in range(100):
    W = update()
    print(W)
    print(n)

    O = np.sign(np.dot(X, W.T))
    if (O == Y.T).all():   #如果实际输出等于期望输出,模型收敛,循环结束
        print('Finished')
        break

#正样本
x1 = [3,4]
y1 = [3,3]
#fu样本
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()

在这里插入图片描述
在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值