开始使用免费开始使用

使用 KFold 索引

您已经创建了 splits,其中包含 candy-data 数据集用于完成 5 折交叉验证的索引。为更好地估计同事的随机森林模型在新数据上的表现,您希望将该模型运行在刚创建的 5 组不同的训练与验证索引上。

在本练习中,您将使用这些索引,通过 5 次不同的切分来检验该模型的准确率。已提供一个 for 循环来帮助您完成此过程。

本练习是课程的一部分

Python 中的模型验证

查看课程

练习说明

  • 使用 train_indexval_index 在创建训练集与验证集时索引 Xy 的相应位置。
  • 使用训练数据集拟合 rfc
  • 使用 rfc 在验证数据集上生成预测,并打印验证准确率。

交互式实操练习

通过完成这段示例代码来试试这个练习。

from sklearn.ensemble import RandomForestRegressor
from sklearn.metrics import mean_squared_error

rfc = RandomForestRegressor(n_estimators=25, random_state=1111)

# Access the training and validation indices of splits
for train_index, val_index in splits:
    # Setup the training and validation data
    X_train, y_train = X[____], y[____]
    X_val, y_val = X[____], y[____]
    # Fit the random forest model
    rfc.____(____, ____)
    # Make predictions, and print the accuracy
    predictions = rfc.____(____)
    print("Split accuracy: " + str(mean_squared_error(y_val, predictions)))
编辑并运行代码