評估 KNN 效能
剛剛我們觀察到 KNN 分數的幾個現象。首先,訓練分數一開始很高,隨著 n 增加而下降,這很常見。不過測試集表現在 5 時達到高峰,因此我們會在最終的 KNN 模型中採用這個設定。
就像先前做過數次的那樣,我們會用視覺化來檢查效能。這有助於了解模型在不同實際值區間的預測品質。我們會對經過縮放的特徵,使用 knn 模型的 .predict() 方法取得預測值。接著使用 matplotlib 的 plt.scatter() 繪製實際值與預測值的散佈圖。
本練習屬於課程
Python 金融 Machine Learning
練習說明
- 在
KNeighborsRegressor中將n_neighbors設為先前練習找到的最佳值 5。 - 使用
knn模型,分別對scaled_train_features與scaled_test_features取得預測值。 - 繪製
test_targets對test_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()