如何用R语言实现决策树C5.0模型

Python012

如何用R语言实现决策树C5.0模型,第1张

你可以利用R软件中{RWeka}包的J48()函数

参考文献:

R. Quinlan (1993). C4.5: Programs for Machine Learning. Morgan Kaufmann Publishers, San Mateo, CA.

R语言特征:

1. type.convert()函数主要用在read.table()函数中,返回向量和因子类型,当输入为double型时会丢失精度。

>type.convert(c('abc','bcd')) # 返回因子类型

[1] abc bcd

Levels: abc bcd

>type.convert(c(as.double(1.12121221111),'1.121')) # double型丢失精度

[1] 1.121212 1.121000

2. 如果一个文件包含有小数位的数据,通过read.table()函数读取时,会指定为numeric类型。

新建一个文件num.csv包括小数

1,2,1.11

2.1,3,4.5

用read.table读取文件,并查看列的类型。

>num<-read.table(file="num.csv",sep=",") # 读文件

>num

V1 V2 V3

1 1.0 2 1.11

2 2.1 3 4.50

>class(num)

[1] "data.frame"

>class(num$V1)# 查看列的类型为numeric

[1] "numeric"

3. tools包用Rdiff()函数的参数useDiff为FALSE时,与POSIX系统的diff -b命令类似。

新建文件num2.csv

3,2,1.11

2.1,3,4.5

用Rdiff()比较两个文件num.csv和num2.csv。

>Rdiff('num.csv','num2.csv',useDiff = FALSE)

1c1

<1,2,1.11

---

>3,2,1.11

[1] 1

4. 新函数anyNA(),结果与 any(is.na(.))一致,性能更好。

>is.na(c(1, NA))

[1] FALSE TRUE

>any(is.na(c(1, NA)))

[1] TRUE

>anyNA(c(1, NA))

[1] TRUE

5. arrayInd()和which()函数增加useNames参数,用于列名的匹配。我在测试过程,不太理解这个参数的意义。

>which

function (x, arr.ind = FALSE, useNames = TRUE)

6. is.unsorted()函数支持处理原始数据的向量。

>is.unsorted(1:10) # 排序的向量

[1] FALSE

>is.unsorted(sample(1:10)) # 无序的向量

[1] TRUE

7. 用于处理table的as.data.frame()函数和as.data.frame.table()函数,支持向provideDimnames(sep,base)函数传参数。我在测试过程中,也不理解具体是什么更新。

8. uniroot()函数增加新的可选参数extendInt,允许自动扩展取值范围,并增加返回对象参数init.it。

>f1 <- function(x) (121 - x^2)/(x^2+1) # 函数f1

>f2 <- function(x) exp(-x)*(x - 12) # 函数f2

>try(uniroot(f1, c(0,10))) # 在(0,10)的区间求f1函数的根

Error in uniroot(f1, c(0, 10)) :

f() values at end points not of opposite sign

>try(uniroot(f2, c(0, 2))) # 在(0,2)的区间求f2函数的根

Error in uniroot(f2, c(0, 2)) :

f() values at end points not of opposite sign

>str(uniroot(f1, c(0,10),extendInt="yes")) # 通过extendInt参数扩大取值搜索范围

List of 5

$ root : num 11

$ f.root: num -3.63e-06

$ iter : int 12

$ init.it : int 4

$ estim.prec: num 6.1e-05

>str(uniroot(f2, c(0,2), extendInt="yes")) # 通过extendInt参数扩大取值搜索范围

List of 5

$ root : num 12

$ f.root: num 4.18e-11

$ iter : int 23

$ init.it : int 9

$ estim.prec: num 6.1e-05

9. switch(f,)函数,当参数f是因子类型时,会出警告提示,需要转换字符串参数。

>switch(ff[1], A = "I am A", B="Bb..", C=" is C")# ->"A" # 警告提示

[1] "I am A"

Warning message:

In switch(ff[1], A = "I am A", B = "Bb..", C = " is C") :

EXPR is a "factor", treated as integer.

Consider using 'switch(as.character( * ), ...)' instead.

>switch(as.character(ff[1]), A = "I am A", B="Bb..", C=" is C") # 转型为字符串处理

[1] " is C"

10. 解析器已经更新,使用更少的内存。

决策树的典型算法有ID3,C4.5,CART等。国际权威的学术组织,数据挖掘国际会议ICDM (the IEEE International Conference on Data Mining)在2006年12月评选出了数据挖掘领域的十大经典算法中,C4.5算法排名第一。