开始使用免费开始使用

加入损失矩阵

第三,您可以加入一个损失矩阵,用于改变两类误分类的重要性:将违约错分为非违约,与将非违约错分为违约。这里要强调:把真实的违约错分为非违约应当受到更高的惩罚。您可以在参数 parms 中传入损失矩阵来实现。

parms = list(loss = matrix(c(0, cost_def_as_nondef, cost_nondef_as_def, 0), ncol=2))

这样就构造了一个 2x2 的矩阵,主对角线为 0,非对角线为自定义的损失惩罚。默认的损失矩阵是非对角线全为 1。

本练习是课程的一部分

R 中的信用风险建模

查看课程

练习说明

  • 修改提供的代码,加入损失矩阵:当把真实违约错分为非违约时,惩罚应提高到 10 倍。也就是将 cost_def_as_nondef 替换为 10,将 cost_nondef_as_def 替换为 1。与前面练习相同,加入 rpart.control,将复杂度参数放宽到 0.001。
  • 使用函数 plot 和树对象名绘制决策树。添加第二个参数 uniform = TRUE 以获得等长分支,并使用 text() 搭配树对象名为树添加标签。

交互式实操练习

通过完成这段示例代码来试试这个练习。

# Change the code below such that a decision tree is constructed using a loss matrix penalizing 10 times more heavily for misclassified defaults.
tree_loss_matrix <- rpart(loan_status ~ ., method = "class",
                          data =  training_set)


# Plot the decision tree


# Add labels to the decision tree

编辑并运行代码