
1.准备数据
[plain] view plain copy
> install.packages("tree")
> library(tree)
> library(ISLR)
> attach(Carseats)
> High=ifelse(Sales<=8,"No","Yes") //set high values by sales data to calssify
> Carseats=data.frame(Carseats,High) //include the high data into the data source
> fix(Carseats)
2.生成决策树
[plain] view plain copy
> tree.carseats=tree(High~.-Sales,Carseats)
> summary(tree.carseats)
[plain] view plain copy
//output training error is 9%
Classification tree:
tree(formula = High ~ . - Sales, data = Carseats)
Variables actually used in tree construction:
[1] "ShelveLoc" "Price" "Income" "CompPrice" "Population"
[6] "Advertising" "Age" "US"
Number of terminal nodes: 27
Residual mean deviance: 0.4575 = 170.7 / 373
Misclassification error rate: 0.09 = 36 / 400
3. 显示决策树
[plain] view plain copy
> plot(tree . carseats )
> text(tree .carseats ,pretty =0)
4.Test Error
[plain] view plain copy
//prepare train data and test data
//We begin by using the sample() function to split the set of observations sample() into two halves, by selecting a random subset of 200 observations out of the original 400 observations.
> set . seed (1)
> train=sample(1:nrow(Carseats),200)
> Carseats.test=Carseats[-train,]
> High.test=High[-train]
//get the tree model with train data
> tree. carseats =tree (High~.-Sales , Carseats , subset =train )
//get the test error with tree model, train data and predict method
//predict is a generic function for predictions from the results of various model fitting functions.
> tree.pred = predict ( tree.carseats , Carseats .test ,type =" class ")
> table ( tree.pred ,High. test)
High. test
tree. pred No Yes
No 86 27
Yes 30 57
> (86+57) /200
[1] 0.715
5.决策树剪枝
[plain] view plain copy
/**
Next, we consider whether pruning the tree might lead to improved results. The function cv.tree() performs cross-validation in order to cv.tree() determine the optimal level of tree complexity; cost complexity pruning is used in order to select a sequence of trees for consideration.
For regression trees, only the default, deviance, is accepted. For classification trees, the default is deviance and the alternative is misclass (number of misclassifications or total loss).
We use the argument FUN=prune.misclass in order to indicate that we want the classification error rate to guide the cross-validation and pruning process, rather than the default for the cv.tree() function, which is deviance.
If the tree is regression tree,
> plot(cv. boston$size ,cv. boston$dev ,type=’b ’)
*/
> set . seed (3)
> cv. carseats =cv. tree(tree .carseats ,FUN = prune . misclass ,K=10)
//The cv.tree() function reports the number of terminal nodes of each tree considered (size) as well as the corresponding error rate(dev) and the value of the cost-complexity parameter used (k, which corresponds to α.
> names (cv. carseats )
[1] " size" "dev " "k" " method "
> cv. carseats
$size //the number of terminal nodes of each tree considered
[1] 19 17 14 13 9 7 3 2 1
$dev //the corresponding error rate
[1] 55 55 53 52 50 56 69 65 80
$k // the value of the cost-complexity parameter used
[1] -Inf 0.0000000 0.6666667 1.0000000 1.7500000
2.0000000 4.2500000
[8] 5.0000000 23.0000000
$method //miscalss for classification tree
[1] " misclass "
attr (," class ")
[1] " prune " "tree. sequence "
[plain] view plain copy
//plot the error rate with tree node size to see whcih node size is best
> plot(cv. carseats$size ,cv. carseats$dev ,type=’b ’)
/**
Note that, despite the name, dev corresponds to the cross-validation error rate in this instance. The tree with 9 terminal nodes results in the lowest cross-validation error rate, with 50 cross-validation errors. We plot the error rate as a function of both size and k.
*/
> prune . carseats = prune . misclass ( tree. carseats , best =9)
> plot( prune . carseats )
> text( prune .carseats , pretty =0)
//get test error again to see whether the this pruned tree perform on the test data set
> tree.pred = predict ( prune . carseats , Carseats .test , type =" class ")
> table ( tree.pred ,High. test)
High. test
tree. pred No Yes
No 94 24
Yes 22 60
> (94+60) /200
[1] 0.77
数据分析咨询请扫描二维码
若不方便扫码,搜微信号:CDAshujufenxi
在手游行业,“次日留存率” 是衡量一款游戏生死的 “第一道关卡”—— 它不仅反映了玩家对游戏的初始接受度,更直接决定了后续 ...
2025-10-13分库分表,为何而生? 在信息技术发展的早期阶段,数据量相对较小,业务逻辑也较为简单,单库单表的数据库架构就能够满足大多数 ...
2025-10-13在企业数字化转型过程中,“数据孤岛” 是普遍面临的痛点:用户数据散落在 APP 日志、注册系统、客服记录中,订单数据分散在交易 ...
2025-10-13在数字化时代,用户的每一次行为 —— 从电商平台的 “浏览→加购→购买”,到视频 APP 的 “打开→搜索→观看→收藏”,再到银 ...
2025-10-11在机器学习建模流程中,“特征重要性分析” 是连接 “数据” 与 “业务” 的关键桥梁 —— 它不仅能帮我们筛选冗余特征、提升模 ...
2025-10-11在企业的数据体系中,未经分类的数据如同 “杂乱无章的仓库”—— 用户行为日志、订单记录、商品信息混杂存储,CDA(Certified D ...
2025-10-11在 SQL Server 数据库操作中,“数据类型转换” 是高频需求 —— 无论是将字符串格式的日期转为datetime用于筛选,还是将数值转 ...
2025-10-10在科研攻关、工业优化、产品开发中,正交试验(Orthogonal Experiment)因 “用少量试验覆盖多因素多水平组合” 的高效性,成为 ...
2025-10-10在企业数据量从 “GB 级” 迈向 “PB 级” 的过程中,“数据混乱” 的痛点逐渐从 “隐性问题” 变为 “显性瓶颈”:各部门数据口 ...
2025-10-10在深度学习中,“模型如何从错误中学习” 是最关键的问题 —— 而损失函数与反向传播正是回答这一问题的核心技术:损失函数负责 ...
2025-10-09本文将从 “检验本质” 切入,拆解两种方法的核心适用条件、场景边界与实战选择逻辑,结合医学、工业、教育领域的案例,让你明确 ...
2025-10-09在 CDA 数据分析师的日常工作中,常会遇到这样的困惑:某电商平台 11 月 GMV 同比增长 20%,但究竟是 “长期趋势自然增长”,还 ...
2025-10-09Pandas 选取特定值所在行:6 类核心方法与实战指南 在使用 pandas 处理结构化数据时,“选取特定值所在的行” 是最高频的操作之 ...
2025-09-30球面卷积神经网络(SCNN) 为解决这一痛点,球面卷积神经网络(Spherical Convolutional Neural Network, SCNN) 应运而生。它通 ...
2025-09-30在企业日常运营中,“未来会怎样” 是决策者最关心的问题 —— 电商平台想知道 “下月销量能否达标”,金融机构想预判 “下周股 ...
2025-09-30Excel 能做聚类分析吗?基础方法、进阶技巧与场景边界 在数据分析领域,聚类分析是 “无监督学习” 的核心技术 —— 无需预设分 ...
2025-09-29XGBoost 决策树:原理、优化与工业级实战指南 在机器学习领域,决策树因 “可解释性强、处理非线性关系能力突出” 成为基础模型 ...
2025-09-29在标签体系的落地链路中,“设计标签逻辑” 只是第一步,真正让标签从 “纸上定义” 变为 “业务可用资产” 的关键,在于标签加 ...
2025-09-29在使用 Excel 数据透视表进行多维度数据汇总时,折叠功能是梳理数据层级的核心工具 —— 通过点击 “+/-” 符号可展开明细数据或 ...
2025-09-28在使用 Pandas 处理 CSV、TSV 等文本文件时,“引号” 是最容易引发格式混乱的 “隐形杀手”—— 比如字段中包含逗号(如 “北京 ...
2025-09-28