如何知道在构建的树模型中实际使用了哪些变量?
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
但是,如何将实际使用的变量的索引提取到一个向量中呢?
回答:
你可以使用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"
编辑2:
你是对的!试试这个:
> summary(fit)$used[1] Petal.Length Petal.Width Sepal.LengthLevels: <leaf> Sepal.Length Sepal.Width Petal.Length Petal.Width