在改變先驗機率下修剪決策樹
在影片中,你學到為了避免過度擬合,需要對決策樹進行修剪。前面的練習產生了一些很大的樹;現在你要把所學付諸實作,針對先驗機率已調整過的情況,修剪先前建立的樹。rpart 套件已載入至你的工作環境。
你會先設定隨機種子,以確保結果可重現(影片也有提到),因為你將檢視交叉驗證的誤差結果。這些結果包含隨機性,若用不同的種子再次執行,數值可能會略有差異。
在本練習中,你會學到如何找出能最小化交叉驗證誤差的複雜度參數(CP),然後依據該值修剪你的樹。
本練習屬於課程
R 的信用風險建模
練習說明
tree_prior已載入你的工作環境。- 使用
plotcp()視覺化tree_prior的複雜度參數與交叉驗證誤差(X-val Relative Error)之間的關係。 - 使用
printcp()列出包含 CP、分裂次數與誤差的表格。看看你能否找出tree_prior中哪一個分裂對應的交叉驗證誤差最小。 - 使用
which.min()找出在tree_prior$cptable中,哪一列的交叉驗證誤差"xerror"為最小。將結果指定給index。 - 在欄位
"CP"中,依index由tree_prior$cptable取值,建立tree_min。 - 使用
prune()函式取得修剪後的樹,將其命名為ptree_prior。 - 套件
rpart.plot已載入至你的工作環境。使用 prp()(預設設定)繪製修剪後的樹。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# tree_prior is loaded in your workspace
# Plot the cross-validated error rate as a function of the complexity parameter
# Use printcp() to identify for which complexity parameter the cross-validated error rate is minimized.
# Create an index for of the row with the minimum xerror
index <- which.min(___$___[ , "xerror"])
# Create tree_min
tree_min <- tree_prior$cptable[index, "CP"]
# Prune the tree using tree_min
ptree_prior <- prune(___, cp = ___)
# Use prp() to plot the pruned tree