构建随机森林模型
您将继续使用 Pima Indians 数据集来预测个体是否患有糖尿病。这一次使用随机森林分类器。在完成训练集-测试集划分后,您将把模型拟合在训练数据上,并查看特征重要性。
特征和目标数据集已分别预加载为 X 和 y。所需的包和函数也已为您准备好。
本练习是课程的一部分
Python 中的降维
练习说明
- 将测试集比例设为 25%,执行 75%-25% 的训练集-测试集划分。
- 将随机森林分类器拟合到训练数据。
- 计算测试集上的准确率。
- 按特征打印各自的特征重要性。
交互式实操练习
通过完成这段示例代码来试试这个练习。
# Perform a 75% training and 25% test data split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=____, random_state=0)
# Fit the random forest model to the training data
rf = RandomForestClassifier(random_state=0)
rf.____(____, ____)
# Calculate the accuracy
acc = accuracy_score(____, ____)
# Print the importances per feature
print(dict(zip(X.columns, rf.____.round(2))))
# Print accuracy
print(f"{acc:.1%} accuracy on test set.")