使用損失矩陣修剪樹
在這個練習中,你會修剪以損失矩陣建出的決策樹,讓錯分為違約的代價高於錯分為非違約。
本練習屬於課程
R 的信用風險建模
練習說明
- 先執行程式碼以設定隨機種子,並再次建立
tree_loss_matrix。 - 使用函式 plotcp() 檢視交叉驗證誤差的結構。
- 從 cp 圖來看,你會發現以最小交叉驗證誤差來修剪,會得到和未修剪一樣大的樹,因為交叉驗證誤差在
cp = 0.001時達到最小。由於你希望把樹縮小一點,請嘗試用cp = 0.0012788來修剪。對這個複雜度參數,交叉驗證誤差已非常接近最小觀察值。把修剪後的樹命名為ptree_loss_matrix。 - 工作區已載入套件
rpart.plot。使用函式prp()(包含引數extra = 1)來繪製修剪後的樹。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# set a seed and run the code to construct the tree with the loss matrix again
set.seed(345)
tree_loss_matrix <- rpart(loan_status ~ ., method = "class", data = training_set,
parms = list(loss=matrix(c(0, 10, 1, 0), ncol = 2)),
control = rpart.control(cp = 0.001))
# Plot the cross-validated error rate as a function of the complexity parameter
# Prune the tree using cp = 0.0012788
# Use prp() and argument extra = 1 to plot the pruned tree