树中使用的变量
Posted
技术标签:
【中文标题】树中使用的变量【英文标题】:Used Variables in Tree 【发布时间】:2013-08-20 14:10:11 【问题描述】:我怎样才能知道在构造树中实际使用了哪些变量?
model = tree(status~., set.train)
如果我写,我可以看到变量:
summary(model)
tree(formula = status ~ ., data = set.train)
Variables actually used in tree construction:
[1] "spread1" "MDVP.Fhi.Hz." "DFA" "D2" "RPDE" "MDVP.Shimmer" "Shimmer.APQ5"
Number of terminal nodes: 8
Residual mean deviance: 0.04225 = 5.831 / 138
Distribution of residuals:
Min. 1st Qu. Median Mean 3rd Qu. Max.
-0.9167 0.0000 0.0000 0.0000 0.0000 0.6667
但是我怎样才能在向量中得到实际使用的变量的索引?
【问题讨论】:
【参考方案1】:您可以使用str()
函数查看对象的结构。在那里查看时,您应该会看到几个不同的地方来提取用于制作树模型的变量,这里是一个示例:
> library(tree)
>
> fit <- tree(Species ~., data=iris)
> attr(fit$terms,"term.labels")
[1] "Sepal.Length" "Sepal.Width" "Petal.Length" "Petal.Width"
编辑:由于您特别要求提供索引,因此您只需 match()
那些返回数据集中的变量名称(尽管它们可能总是按顺序排列 - 我之前没有使用过 tree
包,所以我不能说)。
> match(attr(fit$terms,"term.labels"),names(iris))
[1] 1 2 3 4
> names(iris)[match(attr(fit$terms,"term.labels"),names(iris))]
[1] "Sepal.Length" "Sepal.Width" "Petal.Length" "Petal.Width"
EDIT2:
你是对的!试试这个:
> summary(fit)$used
[1] Petal.Length Petal.Width Sepal.Length
Levels: <leaf> Sepal.Length Sepal.Width Petal.Length Petal.Width
【讨论】:
哦.. 但是,如果您查看 summary(fit),您会发现您编写的结果与树中实际使用的变量不匹配。例如 Sepal.Width 实际上不包含在树中。 好电话。您可以从summary()
对象中获取它。【参考方案2】:
我想这就是你要找的东西
fit <- rpart(Species ~ Sepal.Length + Sepal.Width + Petal.Length + Petal.Width, data=iris)
used.var <- setdiff(levels(fit$frame$var), "<leaf>")
【讨论】:
这将用于 R 4.0 和 rpart 4.1-15 的 var ")【参考方案3】:很久以前,使用包 rpart 而不是树。我认为在 rpart::printcp() 中编码的 rpart 中使用的 Brian Ripley 的解决方案仍然很有趣。它是这样的:
library(rpart)
r.rp <- rpart(Species ~ Sepal.Length + Sepal.Width + Petal.Length + Petal.Width, data=iris)
r.rp
# extract from rpart::printcp()
frame <- r.rp$frame
leaves <- frame$var == "<leaf>"
used <- unique(frame$var[!leaves])
if (!is.null(used))
cat("Variables actually used in tree construction:\n")
print(sort(as.character(used)), quote = FALSE)
cat("\n")
【讨论】:
【参考方案4】:如果您愿意切换到类似的包rpart
,您可以直接从fit
获得按重要性排序的使用变量
fit <- rpart(Species ~., data=iris)
fit$variable.importance
【讨论】:
这提供了比树中有时使用的更多的变量。以上是关于树中使用的变量的主要内容,如果未能解决你的问题,请参考以下文章