
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
PowerBI 累计曲线制作指南:从 DAX 度量到可视化落地 在业务数据分析中,“累计趋势” 是衡量业务进展的核心视角 —— 无论是 “ ...
2025-08-15Python 函数 return 多个数据:用法、实例与实战技巧 在 Python 编程中,函数是代码复用与逻辑封装的核心载体。多数场景下,我们 ...
2025-08-15CDA 数据分析师:引领商业数据分析体系构建,筑牢企业数据驱动根基 在数字化转型深化的今天,企业对数据的依赖已从 “零散分析” ...
2025-08-15随机森林中特征重要性(Feature Importance)排名解析 在机器学习领域,随机森林因其出色的预测性能和对高维数据的适应性,被广 ...
2025-08-14t 统计量为负数时的分布计算方法与解析 在统计学假设检验中,t 统计量是常用的重要指标,其分布特征直接影响着检验结果的判断。 ...
2025-08-14CDA 数据分析师与业务数据分析步骤 在当今数据驱动的商业世界中,数据分析已成为企业决策和发展的核心驱动力。CDA 数据分析师作 ...
2025-08-14前台流量与后台流量:数据链路中的双重镜像 在商业数据分析体系中,流量数据是洞察用户行为与系统效能的核心依据。前台流量与 ...
2025-08-13商业数据分析体系构建与 CDA 数据分析师的协同赋能 在企业数字化转型的浪潮中,商业数据分析已从 “可选工具” 升级为 “核 ...
2025-08-13解析 CDA 数据分析师:数据时代的价值挖掘者 在数字经济高速发展的今天,数据已成为企业核心资产,而将数据转化为商业价值的 ...
2025-08-13解析 response.text 与 response.content 的核心区别 在网络数据请求与处理的场景中,开发者经常需要从服务器返回的响应中提取数 ...
2025-08-12MySQL 统计连续每天数据:从业务需求到技术实现 在数据分析场景中,连续日期的数据统计是衡量业务连续性的重要手段 —— 无论是 ...
2025-08-12PyTorch 中 Shuffle 机制:数据打乱的艺术与实践 在深度学习模型训练过程中,数据的呈现顺序往往对模型性能有着微妙却关键的影响 ...
2025-08-12Pandas 多列条件筛选:从基础语法到实战应用 在数据分析工作中,基于多列条件筛选数据是高频需求。无论是提取满足特定业务规则的 ...
2025-08-12人工智能重塑 CDA 数据分析领域:从工具革新到能力重构 在数字经济浪潮与人工智能技术共振的 2025 年,数据分析行业正经历着前所 ...
2025-08-12游戏流水衰退率:计算方法与实践意义 在游戏行业中,流水(即游戏收入)是衡量一款游戏商业表现的核心指标之一。而游戏流水衰退 ...
2025-08-12CDA 一级:数据分析入门的基石 在当今数据驱动的时代,数据分析能力已成为职场中的一项重要技能。CDA(Certified Data Anal ...
2025-08-12破解游戏用户流失困局:从数据洞察到留存策略 在游戏行业竞争白热化的当下,用户流失率已成为衡量产品健康度的核心指标。一款游 ...
2025-08-11数据时代的黄金入场券:CDA 认证解锁职业新蓝海 一、万亿级市场需求下的数据分析人才缺口 在数字化转型浪潮中,数据已成为企业核 ...
2025-08-11DBeaver 实战:实现两个库表结构同步的高效路径 在数据库管理与开发工作中,保持不同环境(如开发库与生产库、主库与从库)的表 ...
2025-08-08t 检验与卡方检验:数据分析中的两大统计利器 在数据分析领域,统计检验是验证假设、挖掘数据规律的重要手段。其中,t 检验和卡 ...
2025-08-08