設定臨界值(cut-off)
我們已經示範過,如何設定臨界值會影響你得到的混淆矩陣品質。接下來,你將把預測向量轉換成二元值向量,用來表示貸款的狀態。R 的 ifelse() 函式在這裡很有用。
在臨界值的情境下使用 ifelse(),可以這樣寫:
ifelse(predictions > 0.3, 1, 0)
第一個引數用來測試預測向量中的某個值是否大於 0.3。若為 TRUE,R 會回傳「1」(在第二個引數指定);若為 FALSE,R 會回傳「0」(在第三個引數指定),分別代表「違約」與「未違約」。
本練習屬於課程
R 的信用風險建模
練習說明
- 主控台已提供完整的羅吉斯迴歸模型與預測向量的程式碼。
- 以 0.15 為臨界值,使用
ifelse()和predictions_all_full建立向量pred_cutoff_15。 - 使用
table()檢視混淆矩陣(在第一個引數輸入真實值,也就是test_set$loan_status)。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# The code for the logistic regression model and the predictions is given below
log_model_full <- glm(loan_status ~ ., family = "binomial", data = training_set)
predictions_all_full <- predict(log_model_full, newdata = test_set, type = "response")
# Make a binary predictions-vector using a cut-off of 15%
# Construct a confusion matrix