类别不平衡的处理
类别不平衡会显著影响预测结果,这可以从 recall 与 accuracy 分数的差异中看出来。为了解决不平衡,通常会为每个类别赋予相同的权重。使用 sklearn 的 DecisionTreeClassifier 中的 class_weight 参数,可以将类别权重设为 "balanced"。
现在来修正模型中的类别不平衡问题:
- 首先,设置一个类别权重均衡的模型;
- 然后,将其拟合到训练数据;
- 最后,在测试集上检查其准确率。
变量 features_train、target_train、features_test 和 target_test 已在工作区中提供。
本练习是课程的一部分
HR Analytics:用 Python 预测员工流失
练习说明
- 初始化决策树分类器,通过限制最大深度为 5 来剪枝您的树,并平衡类别权重。
- 拟合新模型。
- 打印该模型在测试集上的预测准确率
score(以百分数表示)。
交互式实操练习
通过完成这段示例代码来试试这个练习。
# Initialize the DecisionTreeClassifier
model_depth_5_b = DecisionTreeClassifier(____=5,class_weight="____",random_state=42)
# Fit the model
model_depth_5_b.____(features_train,target_train)
# Print the accuracy of the prediction (in percentage points) for the test set
print(model_depth_5_b.____(features_test,____)*100)