開始使用免費開始

在改變先驗機率下修剪決策樹

在影片中,你學到為了避免過度擬合,需要對決策樹進行修剪。前面的練習產生了一些很大的樹;現在你要把所學付諸實作,針對先驗機率已調整過的情況,修剪先前建立的樹。rpart 套件已載入至你的工作環境。

你會先設定隨機種子,以確保結果可重現(影片也有提到),因為你將檢視交叉驗證的誤差結果。這些結果包含隨機性,若用不同的種子再次執行,數值可能會略有差異。

在本練習中,你會學到如何找出能最小化交叉驗證誤差的複雜度參數(CP),然後依據該值修剪你的樹。

本練習屬於課程

R 的信用風險建模

檢視課程

練習說明

  • tree_prior 已載入你的工作環境。
  • 使用 plotcp() 視覺化 tree_prior 的複雜度參數與交叉驗證誤差(X-val Relative Error)之間的關係。
  • 使用 printcp() 列出包含 CP、分裂次數與誤差的表格。看看你能否找出 tree_prior 中哪一個分裂對應的交叉驗證誤差最小。
  • 使用 which.min() 找出在 tree_prior$cptable 中,哪一列的交叉驗證誤差 "xerror" 為最小。將結果指定給 index
  • 在欄位 "CP" 中,依 indextree_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
編輯並執行程式碼