importmatplotlibimportmatplotlib.pyplotaspltimportnumpyasnp#Traning set and global variabletrain_set=np.array([[3,3,1],[4,3,1],[1,1,-1]])w=np.array([0,0])b=0#Learning rater=1#Gradient descent to Update w and bdefUpdate(item):globalw,b#w->w+r*xi*yi,y->y+r*yiw+=r*item[-1]*item[:-1]b+=r*item[-1]print("After updating,w={},b={}".format(w,b))defCheck():flag=Falseforitemintrain_set:jud=0#if yi*(w*x+b)<=0 ,proves that this point is at the wrong positionjud+=(w*item[:-1]).sum()+bjud*=item[-1]ifjud<=0:flag=TrueUpdate(item)breakreturnflagif__name__=="__main__":Class_flag=Falseforiinrange(100):ifnotCheck():Class_flag=TruebreakifClass_flag:print("The classification can be done in less than 100 iterations.")#Draw the picturex_1=[3,4]x_2=[3,3]plt.scatter(x_1,x_2,c='red',s=100,label='1')x_11=[1]x_21=[1]plt.scatter(x_11,x_21,c='blue',s=100,label='-1')x_111=np.linspace(0,5,100)x_211=(w[0]*x_111+b)/(-w[1])plt.plot(x_111,x_211)plt.xticks(range(0,5,1))plt.yticks(range(0,5,1))plt.xlabel("x1",fontdict={'size':16})plt.ylabel("x2",fontdict={'size':16})plt.legend(loc='best')plt.show()else:print("The classification can not be done in less than 100 iterations.")