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