如果我通过以下方式构建J48树:
library(RWeka)
fit <- J48(Species~., data=iris)我得到以下结果:
> fit
J48 pruned tree
------------------
Petal.Width <= 0.6: setosa (50.0)
Petal.Width > 0.6
| Petal.Width <= 1.7
| | Petal.Length <= 4.9: versicolor (48.0/1.0)
| | Petal.Length > 4.9
| | | Petal.Width <= 1.5: virginica (3.0)
| | | Petal.Width > 1.5: versicolor (3.0/1.0)
| Petal.Width > 1.7: virginica (46.0/1.0)
Number of Leaves : 5
Size of the tree : 9我希望将Number of Leaves转换为变量N (因此N将获得5),并将Size of the tree转换为S (因此S将获得9)。
有办法直接从J48树获取这些信息吗?
发布于 2015-09-22 08:24:50
正如前面@LyzandeR所指出的,直接在J48对象上这样做并不容易。通常,RWeka中的拟合函数返回的对象通常在R端包含相对较少的信息(例如,只包含调用和拟合预测)。主要内容通常是对Weka构建的Java对象的引用,Weka自己的方法可以通过.jcall应用到Java端,然后在R中返回。
但是,对于J48树来说,很容易将来自Java端的信息转换为标准函数和方法可用的R对象。partykit包提供了一个强制函数,它将J48树转换为constparty对象(具有常量的递归分区)。然后,可以使用length()、width()或depth()等方法分别查询节点数、树叶数和树的深度。
library("RWeka")
fit <- J48(Species ~ ., data = iris)
library("partykit")
p <- as.party(fit)
length(p)
## [1] 9
width(p)
## [1] 5
depth(p)
## [1] 4此外,predict()、plot()、print()和许多其他工具都可用于party对象。
我建议对@LyzandeR建议的文本解析使用这种方法,因为as.party转换不依赖于潜在的容易出错的文本计算。相反,它在内部调用Weka自己的graph生成器(通过.jcall),然后将其解析为constparty结构。
发布于 2015-09-21 11:22:24
有趣的是,看起来fit的输出是在print.Weka_classifier中的.jcall函数中创建的,从getAnywhere(print.Weka_classifier)中可以看到这一点。这使得从打印输出中提取值变得更加困难(但并非不可能)。
为了存储这两个值,您可以这样做:
library(RWeka)
fit <- J48(Species~., data=iris)
#store the print output in a
a <- capture.output(fit)
> a
[1] "J48 pruned tree" "------------------"
[3] "" "Petal.Width <= 0.6: setosa (50.0)"
[5] "Petal.Width > 0.6" "| Petal.Width <= 1.7"
[7] "| | Petal.Length <= 4.9: versicolor (48.0/1.0)" "| | Petal.Length > 4.9"
[9] "| | | Petal.Width <= 1.5: virginica (3.0)" "| | | Petal.Width > 1.5: versicolor (3.0/1.0)"
[11] "| Petal.Width > 1.7: virginica (46.0/1.0)" ""
[13] "Number of Leaves : \t5" ""
[15] "Size of the tree : \t9"
# get the output length, so that this can work for a tree
# with any size/number of leaves
out_length = length(a)
# then save the number from the fourth to last element to N
N <- as.numeric(gsub('\\D', '', a[out_length - 3]))
#then save the number from second to last element to S
S <- as.numeric(gsub('\\D', '', a[out_length - 1]))你看到了:
> N
[1] 5
> S
[1] 9https://stackoverflow.com/questions/32693128
复制相似问题