如何解读决策树的图像

如何解读决策树的图像
如下代码所得图像

导入必要的包

library(rpart)
library(rpart.plot)

读取Swiss数据集

data(swiss)

划分训练集和测试集

set.seed(123)
indices <- sample(1:nrow(swiss), nrow(swiss) * 0.8)
train_data <- swiss[indices, ]
test_data <- swiss[-indices, ]

创建决策树模型

model <- rpart(Fertility ~ ., data = train_data, method = "class")

绘制决策树

rpart.plot(model, extra = 1, under = TRUE, fallen.leaves = TRUE, box.palette = "Blues",
branch.lty = 1, shadow.col = "gray", main = "决策树")

对测试集进行预测

predictions <- predict(model, test_data, type = "class")

计算准确率

accuracy <- sum(predictions == test_data$Fertility) / nrow(test_data)
print(paste("准确率:", accuracy))