如何知道构造树中实际使用了哪些变量?
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
但我怎样才能进入矢量,实际使用哪些变量的索引?
答案 0 :(得分:6)
您可以使用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
答案 1 :(得分:0)
从那以后,使用包rpart而不是tree。我认为Brian Ripley在rpart中使用的解决方案(以rpart :: printcp()编码)仍然很有趣。它是这样的:
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")
}
答案 2 :(得分:0)
我认为这就是您要寻找的
fit <- rpart(Species ~ Sepal.Length + Sepal.Width + Petal.Length + Petal.Width, data=iris)
used.var <- setdiff(levels(fit$frame$var), "<leaf>")
答案 3 :(得分:-2)
如果您愿意切换到类似的程序包rpart
,您可以直接从fit
fit <- rpart(Species ~., data=iris)
fit$variable.importance