开始使用免费开始使用

剪枝决策树

过拟合是分析中的经典问题,尤其在决策树算法中更为常见。树一旦完全生长,往往能在训练样本上给出很高的预测准确率,但在测试集上的表现却未必理想。为此,通常会通过以下方式来控制决策树的生长:

  • 对树进行"剪枝",限制其最大深度。
  • 限制每个叶节点的最少观测数量。

在本练习中,您将:

  • 对树进行剪枝,将最大深度限制为 5 层;
  • 将其拟合到员工数据上;
  • 在训练集和测试集上测试预测结果。

变量 features_traintarget_trainfeatures_testtarget_test 已在您的工作区中可用。

本练习是课程的一部分

HR Analytics:用 Python 预测员工流失

查看课程

练习说明

  • 初始化 DecisionTreeClassifier,将树的最大深度限制为 5。
  • 使用训练集中的 featurestarget 来拟合决策树模型。
  • 检查模型在训练集与测试集上的预测准确率。

交互式实操练习

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

# Initialize the DecisionTreeClassifier while limiting the depth of the tree to 5
model_depth_5 = DecisionTreeClassifier(____=5, random_state=42)

# Fit the model
____.fit(features_train,target_train)

# Print the accuracy of the prediction for the training set
print(____.____(features_train,target_train)*100)

# Print the accuracy of the prediction for the test set
print(model_depth_5.score(____,____)*100)
编辑并运行代码