最終的な決定木の混同行列と精度
ここ数回の演習で、剪定済みの決定木を合計4本作成しました。ご覧のとおり、最終的な分割数は木によって大きく異なります。
ptree_undersample # 7 splits
ptree_prior # 9 splits
ptree_loss_matrix # 24 splits
ptree_weights # 6 splits
次に大事なのは、どの木が精度の面で最も良いかを確認することです。精度を得るために、まずテストデータを使って予測を行い、各木に対して混同行列を作成します。予測では引数に type = "class" を指定します。これにより、カットオフを設定する必要がなくなります。
ただし、重要なのは精度だけではなく、感度や特異度も同様に重要である点に注意してください。さらに、2値(0/1)ではなく確率を予測すると、カットオフを動かせる利点があります。一方で、その場合の難しさはカットオフの選び方です。この点については次の章で扱います。
念のため、精度の計算方法を示します。 $$\textrm{Classification accuracy} = \frac{(TP + TN)}{(TP + FP + TN + FN)}$$
この演習はコースの一部です
R で学ぶクレジットリスク・モデリング
演習の手順
predict()を使って4本すべての木で予測を行います。引数newdataにはtest_setを指定します。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 <-