提取要素类/从插入符号火车对象
问题描述:
类型使用内置虹膜数据集,我可以训练一个模型,如:提取要素类/从插入符号火车对象
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"
太感谢了,知道它是在那里的地方。 – tjq