0

我的问题之后 ,我想知道我应该添加什么来获取节点的值并将其连接到它的名称。我有一个 J48 决策树:

library(RWeka) 
data(iris)
res = J48(Species ~., data = iris)
> res
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

并得到以下字符串:

( Petal.Width ( ) Petal.Width ( Petal.Length ( ) Petal.Width ( ) ) )

我想得到以下(值的串联):

( Petal.Width0.6 ( ) Petal.Width1.7 ( Petal.Length4.9 ( ) Petal.Width1.5 ( ) ) )

这是我使用的代码:

library("partykit")
pres <- as.party(res)
partykit:::.list.rules.party(pres)

nam <- names(pres$data)
tr <- as.list(pres$node)
str <- "("
update_str <- function(x) {
  if(is.null(x$kids)) {
    str <<- paste(str, ")")
  } else {
    str <<- paste(str, nam[x$split$varid], "(")
    for(i in x$kids) update_str(tr[[i]])
  }
}
update_str(tr[[1]])
   > str
[1] "( Petal.Width ( ) Petal.Width ( Petal.Length ( ) Petal.Width ( ) ) )"
4

1 回答 1

0

Just change the recursion:

update_str <- function(x) {
  if(is.null(x$kids)) {
    str <<- paste(str, ")")
  } else {
    str <<- paste(str, nam[x$split$varid], x$split$breaks, "(")
    for(i in x$kids) update_str(tr[[i]])
  }
}

update_str(tr[[1]])

> str
[1] "( Petal.Width 0.6 ( ) Petal.Width 1.7 ( Petal.Length 4.9 ( ) Petal.Width 1.5 ( ) ) )"
于 2016-04-04T12:26:19.503 回答