评估 KNN 表现
我们刚刚观察了 KNN 分数的一些现象。首先,训练集分数一开始很高,并且随着 n 增大而下降,这是常见情况。不过,测试集性能在 5 达到峰值,因此我们将在最终的 KNN 模型中使用该设置。
与前面多次所做的一样,我们将通过可视化来检查模型表现。这有助于查看模型在不同真实值区间的预测效果。我们将对已缩放的特征使用 .predict() 方法,从 knn 模型获取预测值。然后使用 matplotlib 的 plt.scatter() 创建真实值与预测值的散点图。
本练习是课程的一部分
Python 金融机器学习
练习说明
- 将
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()