开始使用免费开始使用

在更改先验概率后剪枝

在视频中,您已经学习到,为了避免过拟合,需要对树进行剪枝。前面练习里出现了一些很大的树。现在请将所学应用到实践中,对先验概率已更改的树进行剪枝。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
编辑并运行代码