開始使用免費開始

評估 KNN 效能

剛剛我們觀察到 KNN 分數的幾個現象。首先,訓練分數一開始很高,隨著 n 增加而下降,這很常見。不過測試集表現在 5 時達到高峰,因此我們會在最終的 KNN 模型中採用這個設定。

就像先前做過數次的那樣,我們會用視覺化來檢查效能。這有助於了解模型在不同實際值區間的預測品質。我們會對經過縮放的特徵,使用 knn 模型的 .predict() 方法取得預測值。接著使用 matplotlibplt.scatter() 繪製實際值與預測值的散佈圖。

本練習屬於課程

Python 金融 Machine Learning

檢視課程

練習說明

  • KNeighborsRegressor 中將 n_neighbors 設為先前練習找到的最佳值 5。
  • 使用 knn 模型,分別對 scaled_train_featuresscaled_test_features 取得預測值。
  • 繪製 test_targetstest_predictions 的散佈圖,並將標籤設為 test

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

# Create the model with the best-performing n_neighbors of 5
knn = KNeighborsRegressor(____)

# Fit the model
knn.fit(scaled_train_features, train_targets)

# Get predictions for train and test sets
train_predictions = ____
test_predictions = ____

# Plot the actual vs predicted values
plt.scatter(train_predictions, train_targets, label='train')
plt.scatter(____)
plt.legend()
plt.show()
編輯並執行程式碼