使用更多选项构建最后一棵树
在本练习中,您将使用视频中讨论过的一些最终参数。我们会修改 rpart.control() 函数中的部分设置,并在 rpart() 中通过 weights 参数加入权重。向量 case_weights 已为您构建并加载到工作空间中。该向量对训练集中未违约样本赋予权重 1,对违约样本赋予权重 3。通过为违约赋予更高权重,模型会更重视对违约的正确分类。
本练习是课程的一部分
R 中的信用风险建模
练习说明
- 设置随机种子为 345。
- 在提供的代码中,将
case_weights传入rpart()的weights参数。 - 使用
rpart.control中的参数,分别将节点允许的最小分裂样本数minsplit设为 5,将叶节点允许的最小观测数minbucket设为 2。 - 使用函数 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