⚡ 编程实验室🏗️ HTML🎨 CSS⚡ JavaScript🐍 Python🗄️ SQL☕ Java⚛️ React💚 Vue🟢 Node.js⚙️ C语言🐘 PHP🐹 Go🔷 TypeScript🐬 MySQL🔧 C++🎯 C#🦀 Rust🅱️ Bootstrap💡 jQuery🎸 Django🍃 MongoDB👗 Sass🎪 Kotlin📊 R语言📋 XML📊 Excel🐘 PostgreSQL🐳 Docker🅰️ Angular🎮 游戏🏠 网站首页

R决策树

使用rpart包构建分类与回归决策树,学习剪枝与可视化 · 难度:入门 · +15XP

决策树:可解释的机器学习模型

决策树通过树形结构模拟决策过程,每个内部节点代表一个特征判断,叶子节点代表结果。

1. 构建分类树

library(rpart)
library(rpart.plot)
data(iris)
tree_model <- rpart(Species ~ ., data=iris, method='class')
rpart.plot(tree_model, main='鸢尾花分类树')

2. 查看树结构

print(tree_model)
summary(tree_model)

3. 预测与评估

pred <- predict(tree_model, iris, type='class')
confusion <- table(Predicted=pred, Actual=iris$Species)
confusion
accuracy <- sum(diag(confusion)) / sum(confusion)
accuracy

4. 剪枝防止过拟合

plotcp(tree_model)  # 查看复杂度参数
pruned_tree <- prune(tree_model, cp=0.02)
rpart.plot(pruned_tree)

5. 回归树示例

data(mtcars)
reg_tree <- rpart(mpg ~ ., data=mtcars, method='anova')
rpart.plot(reg_tree)

决策树关键参数:

参数作用
minsplit内部节点最小样本数
maxdepth树的最大深度
cp复杂度参数,控制剪枝

练习提示:使用rpartiris数据构建决策树,设置maxdepth=3并绘制。

Ctrl+Enter
🚀 升级VIP
解锁全部课程+AI助手

🏆 学习排行

加载中...

📊 统计

📖 71 篇
0 完成
🔥 0