R语言开发之决策树了解下

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/luyaran/article/details/82785271

决策树是以树的形式表示选择及其结果的图形,图中的节点表示事件或选择,并且图形的边缘表示决策规则或条件。

它主要用于使用R的机器学习和数据挖掘应用程序。

使用决策的例子我们可以看下。

将接收的邮件预测是否为垃圾邮件,根据这些信息中的因素,预测肿瘤是癌症或预测贷款作为良好或不良的信用风险。

通常,使用观察数据也称为训练数据创建模型,然后使用一组验证数据来验证和改进模型。

R具有用于创建和可视化决策树的包,对于新的预测变量,我们使用该模型来确定数据的类别(是/否,垃圾邮件/非垃圾邮件),在R中,R包“party”用于创建决策树,并且,包“party”中包含用于创建和分析决策树的ctree()函数,来看下语法:

ctree(formula, data)

参数描述如下:

  • formula - 是描述预测变量和响应变量的公式。
  • data - 是使用的数据集的名称。

我们可以使用一个名为readingSkills的R内置数据集创建一个决策树,大意就是,如果要知道变量:"age","shoesize","score"以及该人员是否是母语者,则描述某人员的阅读技能的得分,先来看下数据集:

# Load the party package. It will automatically load other dependent packages.
library("party")

# Print some records from data set readingSkills.
print(head(readingSkills))

输出结果为:

  nativeSpeaker age shoeSize    score
1           yes   5 24.83189 32.29385
2           yes   6 25.95238 36.63105
3            no  11 30.42170 49.60593
4           yes   7 28.66450 40.28456
5           yes  11 31.88207 55.46085
6           yes  10 30.07843 52.83124

接下来,我们就要使用ctree()函数创建决策树并查看其生成的图表,如下:

# Load the party package. It will automatically load other dependent packages.
library(party)

# Create the input data frame.
input.dat <- readingSkills[c(1:105),]

# Give the chart file a name.
png(file = "decision_tree.png")

# Create the tree.
  output.tree <- ctree(
  nativeSpeaker ~ age + shoeSize + score, 
  data = input.dat)

# Plot the tree.
plot(output.tree)

# Save the file.
dev.off()

输出的结果如下:

null device 
          1 
Loading required package: methods
Loading required package: grid
Loading required package: mvtnorm
Loading required package: modeltools
Loading required package: stats4
Loading required package: strucchange
Loading required package: zoo

Attaching package: ‘zoo’

The following objects are masked from ‘package:base’:

    as.Date, as.Date.numeric

Loading required package: sandwich

产生的图片如下:

从上面所示的决策树,我们可以得出结论:任何阅读技巧(readingSkills)评分小于38.3,年龄超过6岁的人不是本地(使用母语)演讲者。

好啦,本次记录就到这里了。

如果感觉不错的话,请多多点赞支持哦。。。

猜你喜欢

转载自blog.csdn.net/luyaran/article/details/82785271