我正在使用插入符号拟合模型,但我缺少一些数据。我记得在传递参数以训练“preProcess =”medianImpute”之前有一次,但是我收到了一个意外错误:
library(caret)
x <- mtcars
x[1:5, "cyl"] <- c(NA, NA, NA, NA, NA)
mod.mt <- train(
mpg ~.,
method = "rpart", # decision tree
tuneLength = 3,
preProcess = "medianImpute",
data = x)
Run Code Online (Sandbox Code Playgroud)
给出:
Error in na.fail.default(list(mpg = c(21, 21, 22.8, 21.4, 18.7, 18.1, :
missing values in object
Run Code Online (Sandbox Code Playgroud)
因为我正在使用 preProcess 我以为我是在告诉 caret 对任何缺失值使用中值插补。所以这个错误是出乎意料的?
预处理代码仅在 x 是简单矩阵或数据框时才起作用。使用带有公式界面的 train 时,基本上不起作用。
下面的代码有效。或者先做preProces,predict然后train(代码的第二部分)。
mod.mt <- train(
x = x[,2:10],
y = x$mpg,
method = "rpart", # decision tree
tuneLength = 3,
preProcess = "medianImpute"
)
# first impute / predict
d <- preProcess(x, "medianImpute")
x1 <- predict(d, x)
mod.mt <- train(
mpg ~.,
data = x1,
method = "rpart", # decision tree
tuneLength = 3
)
Run Code Online (Sandbox Code Playgroud)