代码如下:
#encoding:utf-8 import pandas as pd import numpy as np import matplotlib.pyplot as plt import matplotlib from matplotlib.colors import ListedColormap from adalinegd import AdalineGD zhfont1=matplotlib.font_manager.FontProperties(fname='C:\Windows\Fonts\simsun.ttc') file="G:/PycharmProjects/test2/iris.data.csv" df=pd.read_csv(file,header=None) #print(df.head(10)) y=df.loc[0:100,4].values y=np.where(y=='Iris-setosa',-1,1) X=df.loc[0:100,[0,2]].values def plot_decision_regions(X,y,classifier,resolution=0.02): marker=('s','x','o','v') colors=('red','blue','lightgreen','gray','cyan') cmap=ListedColormap(colors[:len(np.unique(y))]) x1_min,x1_max=X[:,0].min()-1,X[:,0].max() x2_min,x2_max=X[:,1].min()-1,X[:,1].max() print(x1_min,x1_max) print(x2_min,x2_max) xx1,xx2=np.meshgrid(np.arange(x1_min,x1_max,resolution),np.arange(x2_min,x2_max,resolution)) # print(np.arange(x2_min,x2_max,resolution).shape) # print(np.arange(x2_min,x2_max,resolution)) # print(xx2.shape) # print(xx2) Z=classifier.predict(np.array([xx1.ravel(),xx2.ravel()]).T) print(xx1.ravel()) print(xx2.ravel()) print(Z) Z=Z.reshape(xx1.shape) plt.contourf(xx1,xx2,Z,alpha=0.4,cmap=cmap) plt.xlim(xx1.min(),xx1.max()) plt.ylim(xx2.min(),xx2.max()) for idx ,c1 in enumerate(np.unique(y)): plt.scatter(x=X[y==c1, 0],y=X[y==c1, 1],alpha=0.8,c=cmap(idx), marker=marker[idx],label=c1) ada=AdalineGD(0.0001,50) ada.fit(X,y)#训练 plot_decision_regions(X,y,classifier=ada) plt.title('Adaline-Gradient descent') plt.xlabel('花瓣长度',fontproperties=zhfont1) plt.ylabel('花径长度',fontproperties=zhfont1) plt.legend(loc='upper left') plt.show() plt.plot(range(1,len(ada.cost_)+1),ada.cost_,marker='o') plt.xlabel('Epochs') plt.ylabel('sum-squard-error') plt.show()