用更多選項建立最後一棵樹
在這個練習中,你會使用影片中提到的一些最後的引數。你會變更 rpart.control() 函式中的部分設定,並在 rpart() 中用引數 weights 加入權重。向量 case_weights 已經幫你建立並載入到工作空間。這個向量對訓練集中非違約樣本給予權重 1,對違約樣本給予權重 3。對違約指定較高的權重時,模型會更重視正確分類違約樣本。
本練習屬於課程
R 的信用風險建模
練習說明
- 設定隨機種子為 345。
- 在提供的程式碼中,將
case_weights傳入rpart()的weights引數。 - 使用
rpart.control的引數分別將節點允許的最小分割數設為 5(minsplit),以及葉節點允許的最少觀測數設為 2(minbucket)。 - 使用函式 plotcp() 檢視交叉驗證錯誤率在哪裡可降到最低。
- 使用
which.min()找出在tree_weights$cp中"xerror"最小的那一列。將其指定給index。 - 使用提供的程式碼選出使交叉驗證錯誤最小的
cp。 - 使用使交叉驗證錯誤率最小的複雜度參數來修剪決策樹。將修剪後的樹存為
ptree_weights。 - 使用函式
prp()繪製修剪後的樹。加入第二個引數extra,並將其設為 1。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# set a seed and run the code to obtain a tree using weights, minsplit and minbucket
set.seed(345)
tree_weights <- rpart(loan_status ~ ., method = "class",
data = training_set,
control = rpart.control(minsplit = ___, minbucket = ___, cp = 0.001))
# Plot the cross-validated error rate for a changing cp
# Create an index for of the row with the minimum xerror
index <- which.min(___$___[ , "xerror"])
# Create tree_min
tree_min <- tree_weights$cp[index, "CP"]
# Prune the tree using tree_min
# Plot the pruned tree using the rpart.plot()-package