使用内置的 iris 数据集,我可以训练这样的模型:
model <- train(Species~., data=iris, method='xgbTree')
我可以提取特征的名称,但是当我尝试获取它们的类时,它会返回字符,因为它们只是字符串。
model$coefnames
## "Sepal.Length" "Sepal.Width" "Petal.Length" "Petal.Width"
lapply(model$coefnames, class)
## "character" "character" "character" "character"
但是,当您尝试放入另一种类型的变量来进行预测时,插入符号似乎知道预期的类型。
test<- data.frame(Sepal.Length=1,
Sepal.Width=2,
Petal.Length=3,
Petal.Width="x") # character instead of numeric
predict(model, newdata=test)
## Error: variable 'Petal.Width' was fitted with type "numeric" but type "factor" was supplied
有什么方法可以仅使用模型对象本身来提取用于训练模型的特征类型吗?我能得到的最接近的是使用 dplyr 函数 type.convert 但这需要知道输入。我理想的函数会像这样运行:
model_types(model$coefnames)
## "numeric" "numeric" "numeric" "numeric"
最佳答案
此信息作为模型条款的属性存储
attr(terms(model), "dataClasses")
# Species Sepal.Length Sepal.Width Petal.Length Petal.Width
# "factor" "numeric" "numeric" "numeric" "numeric"
关于r - 从插入符序列对象中提取要素类/类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45925950/