最終決策樹的混淆矩陣與正確率
在前幾個練習中,你建立了相當多經過修剪的決策樹,總共有 4 棵。可以看到各樹的最終分割次數差異很大:
ptree_undersample # 7 splits
ptree_prior # 9 splits
ptree_loss_matrix # 24 splits
ptree_weights # 6 splits
現在重要的是判斷哪一棵樹在正確率方面表現最佳。為了取得正確率,你會先使用測試集做預測,並為每棵樹建立混淆矩陣。進行這些預測時,請加入引數 type = "class"。這麼做就不需要設定臨界值(cut-off)。
不過,需要留意的不僅是正確率,靈敏度(sensitivity)與特異度(specificity)也同樣重要。此外,預測機率而非二元值(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 <-