用 Matplotlib 繪製 k-NN 決策邊界


要在 matplotlib 中繪製 k-NN 決策邊界,我們可以採取以下步驟。

步驟

  • 設定圖形大小並調整子圖之間和周圍的邊距。

  • 為鄰居數初始化變數 n_neighbors

  • 載入並返回 iris 資料集(分類)。

  • 建立 xy 資料點。

  • 製作深色和淺色清單。

  • 實施 k 近鄰投票的分類器。

  • 建立 xmin, xmax, yminymax 資料點。

  • 建立一個新圖形或啟用一個現有圖形。

  • 建立一個輪廓圖。

  • 建立一個具有 X 資料集的散點圖。

  • 設定 xy 軸標籤、標題和軸的刻度。

  • 要顯示圖形,請使用 Show() 方法。

示例

import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from matplotlib.colors import ListedColormap
from sklearn import neighbors, datasets

plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True

n_neighbors = 15
iris = datasets.load_iris()
X = iris.data[:, :2]
y = iris.target
h = .02

cmap_light = ListedColormap(['orange', 'cyan', 'cornflowerblue'])
cmap_bold = ['darkorange', 'c', 'darkblue']


clf = neighbors.KNeighborsClassifier(n_neighbors, weights='uniform')
clf.fit(X, y)

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.contourf(xx, yy, Z, cmap=cmap_light)

sns.scatterplot(x=X[:, 0], y=X[:, 1], hue=iris.target_names[y],
palette=cmap_bold, alpha=1.0, edgecolor="black")

plt.xlim(xx.min(), xx.max())
plt.ylim(yy.min(), yy.max())

plt.title("3-Class classification (k = %i, 'uniform' = '%s')"
% (n_neighbors, 'uniform'))

plt.xlabel(iris.feature_names[0])
plt.ylabel(iris.feature_names[1])

plt.Show()

輸出

它將產生以下輸出 −

更新時間: 2021-10-08

6K+ 瀏覽量

開始您的 職業生涯

完成課程以獲取認證

開始
廣告
© . All rights reserved.