import matplotlib.pyplot as plt import numpy as np X=np.array([[1,3,3], [1,4,3], [1,1,1]]) Y=np.array([1,1,-1]) W=(np.random.random(3)-0.5)*2 print(W) lr=0.01 n=0 def update(): global X,Y,W,lr,n n+=1 Y_p=np.sign(np.dot(X,W)) #涉及到向量,dot转置与否都可 W_C=lr*((Y-Y_p.T).T.dot(X)) W=W+W_C.T for _ in range(100): update() print(W) print(n) Y_p=np.sign(np.dot(X,W)) if(Y_p==Y.T).all(): print("完成") 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()