我保存了使用R中的rpart包创建的模型。我试图从这些保存的模型中检索一些信息;特别是来自 rpart.object 。虽然文档 - rpart doc - 很有帮助,但有一些事情尚不清楚:
Country
可以采用任何值France, Germany, Japan
等,则csplit矩阵会让我知道某个分割基于Country == 1, 2
。在这里,rpart已将France, Germany
的引用分别替换为1, 2
。如何从模型文件中获取原始名称 - France, Germany, Japan
- ?另外,我怎么知道名称和整数之间的映射是什么?答案 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"