如何在R中得到rpart (CART)决策树的属性?

时间:2022-06-27 02:41:23

I have the following rpart:

我有以下的部分:

library("partykit")
library("rpart")
res = rpart(Species ~., data = iris)
pres <- as.party(res)

> pres

Model formula:
Species ~ Sepal.Length + Sepal.Width + Petal.Length + Petal.Width

Fitted party:
[1] root
|   [2] Petal.Length < 2.45: setosa (n = 50, err = 0.0%)
|   [3] Petal.Length >= 2.45
|   |   [4] Petal.Width < 1.75: versicolor (n = 54, err = 9.3%)
|   |   [5] Petal.Width >= 1.75: virginica (n = 46, err = 2.2%)

Number of inner nodes:    2
Number of terminal nodes: 3

I would like to take each split node and its value and write them in the following order:

我想对每个拆分节点及其值进行如下排序:

{Petal.Length 2.45 {Petal.Width 1.75} } 

Where each level is separated from its higher level by {. I would like to do it very similar to what was done for J48 here.

其中,每一层都与它的高层分开。我想把它和J48做的很相似。

1 个解决方案

#1


0  

The solution is:

解决方案是:

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], x$split$breaks, "(")
    for(i in x$kids) update_str(tr[[i]])
  }
}
update_str(tr[[1]])
> str
[1] "( Petal.Length 2.45 ( ) Petal.Width 1.75 ( ) )"

#1


0  

The solution is:

解决方案是:

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], x$split$breaks, "(")
    for(i in x$kids) update_str(tr[[i]])
  }
}
update_str(tr[[1]])
> str
[1] "( Petal.Length 2.45 ( ) Petal.Width 1.75 ( ) )"