[TOC] 更新、更全的《機器學習》的更新網站,更有python、go、數據結構與算法、爬蟲、人工智能教學等着你:http://www.javashuo.com/article/p-vozphyqp-cm.htmlhtml
import numpy as np import matplotlib.pyplot as plt from matplotlib.colors import ListedColormap from matplotlib.font_manager import FontProperties from sklearn import datasets from sklearn.neighbors import KNeighborsClassifier %matplotlib inline font = FontProperties(fname='/Library/Fonts/Heiti.ttc')
iris_data = datasets.load_iris() X = iris_data.data[:, [2, 3]] y = iris_data.target label_list = ['山鳶尾', '雜色鳶尾', '維吉尼亞鳶尾']
def plot_decision_regions(X, y, classifier): # 構造顏色映射關係 marker_list = ['o', 'x', 's'] color_list = ['r', 'b', 'g'] cmap = ListedColormap(color_list[:len(np.unique(y))]) # 構造網格採樣點並使用算法訓練陣列中每一個元素 x1_min, x1_max = X[:, 0].min() - 1, X[:, 0].max() + 1 # 第0列的範圍 x2_min, x2_max = X[:, 1].min() - 1, X[:, 1].max() + 1 # 第1列的範圍 t1 = np.linspace(x1_min, x1_max, 666) # 橫軸採樣多少個點 t2 = np.linspace(x2_min, x2_max, 666) # 縱軸採樣多少個點 x1, x2 = np.meshgrid(t1, t2) # 生成網格採樣點 y_hat = classifier.predict(np.array([x1.ravel(), x2.ravel()]).T) # 預測值 y_hat = y_hat.reshape(x1.shape) # 使之與輸入的形狀相同 # 經過網格採樣點畫出等高線圖 plt.contourf(x1, x2, y_hat, alpha=0.2, cmap=cmap) plt.xlim(x1.min(), x1.max()) plt.ylim(x2.min(), x2.max()) for ind, clas in enumerate(np.unique(y)): plt.scatter(X[y == clas, 0], X[y == clas, 1], alpha=0.8, s=50, c=color_list[ind], marker=marker_list[ind], label=label_list[clas])
knn = KNeighborsClassifier(n_neighbors=10, p=2) # p=2爲歐幾里得距離;p=1爲曼哈頓距離 knn.fit(X, y)
KNeighborsClassifier(algorithm='auto', leaf_size=30, metric='minkowski', metric_params=None, n_jobs=None, n_neighbors=10, p=2, weights='uniform')
plot_decision_regions(X, y, classifier=knn) plt.xlabel('花瓣長度(cm)', fontproperties=font) plt.ylabel('花瓣寬度(cm)', fontproperties=font) plt.legend(prop=font) plt.show()
![png](http://www.chenyoude.com/ml/02-19 k近鄰算法(鳶尾花分類)_10_0.png?x-oss-process=style/watermark)python