注意
前往末尾下載完整的範例程式碼。或透過 JupyterLite 或 Binder 在您的瀏覽器中執行此範例
最近鄰居迴歸#
展示使用 k 最近鄰居解決迴歸問題,以及使用重心和常數權重內插目標。
# Authors: The scikit-learn developers
# SPDX-License-Identifier: BSD-3-Clause
產生樣本資料#
在這裡,我們產生一些資料點來訓練模型。我們也在訓練資料的整個範圍內產生資料,以視覺化模型在整個區域中的反應。
import matplotlib.pyplot as plt
import numpy as np
from sklearn import neighbors
rng = np.random.RandomState(0)
X_train = np.sort(5 * rng.rand(40, 1), axis=0)
X_test = np.linspace(0, 5, 500)[:, np.newaxis]
y = np.sin(X_train).ravel()
# Add noise to targets
y[::5] += 1 * (0.5 - np.random.rand(8))
擬合迴歸模型#
在這裡,我們訓練模型並視覺化預測中 uniform
和 distance
權重如何影響預測值。
n_neighbors = 5
for i, weights in enumerate(["uniform", "distance"]):
knn = neighbors.KNeighborsRegressor(n_neighbors, weights=weights)
y_ = knn.fit(X_train, y).predict(X_test)
plt.subplot(2, 1, i + 1)
plt.scatter(X_train, y, color="darkorange", label="data")
plt.plot(X_test, y_, color="navy", label="prediction")
plt.axis("tight")
plt.legend()
plt.title("KNeighborsRegressor (k = %i, weights = '%s')" % (n_neighbors, weights))
plt.tight_layout()
plt.show()

腳本的總執行時間: (0 分鐘 0.220 秒)
相關範例