从rpart.object获取原始名称

时间:2015-04-05 16:19:44

标签: r rpart

我保存了使用R中的rpart包创建的模型。我试图从这些保存的模型中检索一些信息;特别是来自 rpart.object 。虽然文档 - rpart doc - 很有帮助,但有一些事情尚不清楚:

  1. 如何找出哪些变量是分类的,哪些是数字的?目前,我所做的是参考 splits 矩阵中的'index'列。我注意到,仅对于数字变量,该条目不是整数。有更清洁的方法吗?
  2. csplit 矩阵指的是分类变量可以使用整数获取的各种值,即R将原始名称映射为整数。有没有办法访问这个映射?对于前者如果我的原始变量,例如Country可以采用任何值France, Germany, Japan等,则csplit矩阵会让我知道某个分割基于Country == 1, 2。在这里,rpart已将France, Germany的引用分别替换为1, 2。如何从模型文件中获取原始名称 - France, Germany, Japan - ?另外,我怎么知道名称和整数之间的映射是什么?

1 个答案:

答案 0 :(得分:2)

通常,terms组件会有这种信息。 See ?rpart::rpart.object

fit <- rpart::rpart(Kyphosis ~ Age + Number + Start, data = kyphosis)
fit$terms  # notice that the attribute dataClasses has the information
attr(fit$terms, "dataClasses")
#------------
 Kyphosis       Age    Number     Start 
 "factor" "numeric" "numeric" "numeric" 

该示例在其结构中没有csplit节点,因为没有hte变量是因子。你可以很容易地做一个:

> fit <- rpart::rpart(Kyphosis ~ Age + factor(findInterval(Number,c(0,4,6,Inf))) + Start, data = kyphosis)
> fit$csplit
     [,1] [,2] [,3]
[1,]    1    1    3
[2,]    1    1    3
[3,]    3    1    3
[4,]    1    3    3
[5,]    3    1    3
[6,]    3    3    1
[7,]    3    1    3
[8,]    1    1    3
> attr(fit$terms, "dataClasses")
                                     Kyphosis 
                                     "factor" 
                                          Age 
                                    "numeric" 
factor(findInterval(Number, c(0, 4, 6, Inf))) 
                                     "factor" 
                                        Start 
                                    "numeric" 

整数只是因子变量的值,因此“映射”与从as.numeric()到因子levels()的值相同。如果我试图构建一个fit$csplit - 矩阵的字符矩阵版本来代替因子变量中的级别名称,那么这将是成功的一条途径:

> kyphosis$Numlev <- factor(findInterval(kyphosis$Number, c(0, 4, 6, Inf)), labels=c("low","med","high"))
> str(kyphosis)
'data.frame':   81 obs. of  5 variables:
 $ Kyphosis: Factor w/ 2 levels "absent","present": 1 1 2 1 1 1 1 1 1 2 ...
 $ Age     : int  71 158 128 2 1 1 61 37 113 59 ...
 $ Number  : int  3 3 4 5 4 2 2 3 2 6 ...
 $ Start   : int  5 14 5 1 15 16 17 16 16 12 ...
 $ Numlev  : Factor w/ 3 levels "low","med","high": 1 1 2 2 2 1 1 1 1 3 ...
> fit <- rpart::rpart(Kyphosis ~ Age +Numlev + Start, data = kyphosis)
> Levels <- fit$csplit
> Levels[] <- levels(kyphosis$Numlev)[Levels]
> Levels
     [,1]   [,2]   [,3]  
[1,] "low"  "low"  "high"
[2,] "low"  "low"  "high"
[3,] "high" "low"  "high"
[4,] "low"  "high" "high"
[5,] "high" "low"  "high"
[6,] "high" "high" "low" 
[7,] "high" "low"  "high"
[8,] "low"  "low"  "high"

对评论的回应:如果你只有模型,那么使用str()来查看它。我在我创建的示例中看到一个“有序”叶子,其中的因子标签存储在名为“xlevels”的属性中:

$ ordered            : Named logi [1:3] FALSE FALSE FALSE
  ..- attr(*, "names")= chr [1:3] "Age" "Numlev" "Start"
 - attr(*, "xlevels")=List of 1
  ..$ Numlev: chr [1:3] "low" "med" "high"
 - attr(*, "ylevels")= chr [1:2] "absent" "present"
 - attr(*, "class")= chr "rpart"