最近鄰分類?
最近鄰居分類的樣本用法。 它將繪制每個類別的決策邊界。


輸入:
print(__doc__)
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap
from sklearn import neighbors, datasets
n_neighbors = 15
# 導入需要處理的數據
iris = datasets.load_iris()
# 我們僅采用前兩個特征。我們可以通過使用二維數據集來避免使用復雜的切片
X = iris.data[:, :2]
y = iris.target
h = .02 # 設置網格中的步長
# 提取色譜
cmap_light = ListedColormap(['orange', 'cyan', 'cornflowerblue'])
cmap_bold = ListedColormap(['darkorange', 'c', 'darkblue'])
for weights in ['uniform', 'distance']:
# 我們創建最近鄰分類器的實例并擬合數據。
clf = neighbors.KNeighborsClassifier(n_neighbors, weights=weights)
clf.fit(X, y)
# 繪制決策邊界。 為此,我們將為網格[x_min,x_max] x [y_min,y_max]中的每個點分配顏色。
x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1
y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1
xx, yy = np.meshgrid(np.arange(x_min, x_max, h),
np.arange(y_min, y_max, h))
Z = clf.predict(np.c_[xx.ravel(), yy.ravel()])
# 將結果放入顏色圖
Z = Z.reshape(xx.shape)
plt.figure()
plt.pcolormesh(xx, yy, Z, cmap=cmap_light)
# 繪制訓練數據
plt.scatter(X[:, 0], X[:, 1], c=y, cmap=cmap_bold,
edgecolor='k', s=20)
plt.xlim(xx.min(), xx.max())
plt.ylim(yy.min(), yy.max())
plt.title("3-Class classification (k = %i, weights = '%s')"
% (n_neighbors, weights))
plt.show()
腳本的總運行時間:0分鐘1.987秒