最终树的混淆矩阵与准确率
在之前的练习中,您共构建了 4 棵经过剪枝的决策树。可以看到,各树的最终切分次数差异较大:
ptree_undersample # 7 splits
ptree_prior # 9 splits
ptree_loss_matrix # 24 splits
ptree_weights # 6 splits
现在需要判断哪棵树在准确率方面表现最佳。为此,您将先使用测试集进行预测,并为每棵树构建混淆矩阵。在预测时加入参数 type = "class"。这样就无需设置阈值。
不过需要注意的是,不仅要关注准确率,还要关注灵敏度(召回率)和特异度。另外,预测概率而不是二元值(0 或 1)的好处是可以调整阈值。但相应的难点在于如何选择阈值。下一章我们会回到这个话题。
如果需要回顾,准确率的计算方式如下: $$\textrm{Classification accuracy} = \frac{(TP + TN)}{(TP + FP + TN + FN)}$$
本练习是课程的一部分
R 中的信用风险建模
练习说明
- 使用
predict()为这 4 棵树分别生成预测。将test_set传入参数newdata。别忘了包含type = "class"! - 为每棵决策树构建混淆矩阵。使用
table()函数,先放入"真实"状态(使用test_set$loan_status),然后放入预测结果。 - 使用各自的混淆矩阵计算准确率。
交互式实操练习
通过完成这段示例代码来试试这个练习。
# Make predictions for each of the pruned trees using the test set.
pred_undersample <- predict(ptree_undersample, newdata = test_set, type = "class")
pred_prior <-
pred_loss_matrix <-
pred_weights <-
# construct confusion matrices using the predictions.
confmat_undersample <- table(test_set$loan_status, pred_undersample)
confmat_prior <-
confmat_loss_matrix <-
confmat_weights <-
# Compute the accuracies
acc_undersample <- sum(diag(confmat_undersample)) / nrow(test_set)
acc_prior <-
acc_loss_matrix <-
acc_weights <-