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()