開始使用免費開始

使用損失矩陣修剪樹

在這個練習中,你會修剪以損失矩陣建出的決策樹,讓錯分為違約的代價高於錯分為非違約。

本練習屬於課程

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
編輯並執行程式碼