开始使用免费开始使用

使用损失矩阵剪枝

在本练习中,您将对使用损失矩阵构建的树进行剪枝,从而对"违约被错分"为非违约施加比"非违约被错分"为违约更高的惩罚。

本练习是课程的一部分

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
编辑并运行代码