資料探勘-Iris資料集分析-決策邊界_根據花瓣資料繪製(七)
阿新 • • 發佈:2019-01-08
# coding: utf-8 # 使用花瓣測量資料繪製 2D散點圖,並繪出決策邊界 import numpy as np import matplotlib.pyplot as plt from matplotlib.colors import ListedColormap from sklearn import datasets from sklearn.neighbors import KNeighborsClassifier #matplot顯示圖例中的中文問題 : https://www.zhihu.com/question/25404709/answer/67672003 import matplotlib.font_manager as fm #mac中的字型問題請看: https://zhidao.baidu.com/question/161361596.html myfont = fm.FontProperties(fname='/Library/Fonts/Xingkai.ttc') iris=datasets.load_iris() x=iris.data[:,2:4] #取出花瓣的長和寬 y=iris.target #取出類別 #計算散點圖的軸的邊界 x_min,x_max=x[:,0].min() -.5, x[:,0].max()+.5 y_min, y_max=x[:,1].min()-.5, x[:,1].max()+.5 #繪製邊界 cmap_light=ListedColormap(['#AAAAFF','#AAFFAA','#FFAAAA']) h=.02 xx,yy=np.meshgrid(np.arange(x_min,x_max,h),np.arange(y_min,y_max,h)) knn=KNeighborsClassifier() knn.fit(x,y) Z=knn.predict( np.c_[xx.ravel(),yy.ravel()]) Z=Z.reshape(xx.shape) plt.figure() plt.pcolormesh(xx,yy,Z,cmap=cmap_light) plt.title(u'鳶尾花分類預測決策邊界_根據花瓣長寬',fontproperties=myfont) plt.xlabel(u'花瓣長',fontproperties=myfont) plt.ylabel(u'花瓣寬',fontproperties=myfont) plt.scatter(x[:,0],x[:,1],c=y) plt.xlim( xx.min(), xx.max() ) plt.ylim( yy.min(),yy.max() ) plt.savefig('python_8_7_帶決策邊界的2D散點圖_根據花瓣資料繪製.png') plt.show()