import numpy as np
import matplotlib.pyplot as plt
#輸入數據
X = np.array([[3,3],
[4,3],
[1,1],
[0,2]])
# 添加偏置項
X = np.concatenate((np.ones((4,1)),X),axis=1)
print(X)
# 標籤
Y = np.array([[1],
[1],
[-1],
[-1]])
# 權值初始化,3行1列,取值範圍-1到1
W = (np.random.random([3,1])-0.5) *2
print(W)
# 學習率設置
lr = 0.11
# 神經網絡輸出
O = 0
def update():
global X,Y,W,lr
O = np.sign(np.dot(X,W))
W_C = lr * (X.T.dot(Y-O))/int(X.shape[0])
W = W + W_C
for i in range(100):
update() # 更新當前權值
print(W) # 打印當前權值
print(i) # 打印迭代次數
O = np.sign(np.dot(X,W))
if (O == Y).all():
print('Finished')
print('epoch',i)
break
#正樣本
x1 = [3,4]
y1 = [3,3]
#負樣本
x2 = [1,0]
y2 = [1,2]
#計算分界線的斜率以及截距
# w0 + w1x1 + w2x2 = 0
# x1 看作x x2看作y
# y = -w0/w2 - w1/w2(x)
k = -W[1] / W[2]
d = -W[0] / W[2]
xdata = (0,5)
plt.figure()
plt.plot(xdata,xdata * k +d,'r')
plt.scatter(x1,y1,c='b')
plt.scatter(x2,y2,c='y')
plt.show()