从插入符号序列对象中提取特征 classes/types

Extract feature classes/types from caret train object

使用内置的鸢尾花数据集,我可以这样训练模型:

model <- train(Species~., data=iris, method='xgbTree')

我可以提取特征的名称,但是当我尝试获取它们的 类 时,它是 returns 个字符,因为它们只是字符串。

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"