Caret::train - 值未填充

12

我正在尝试通过将"knnImpute"传递给Caret的train()方法的preProcess参数来插补值。根据以下示例,似乎这些值没有被插补,仍然为NA,然后被忽略了。我做错了什么?

非常感谢任何帮助。

library("caret")

set.seed(1234)
data(iris)

# mark 8 of the cells as NA, so they can be imputed
row <- sample (1:nrow (iris), 8)
iris [row, 1] <- NA

# split test vs training
train.index <- createDataPartition (y = iris[,5], p = 0.80, list = F)
train <- iris [ train.index, ]
test  <- iris [-train.index, ]

# train the model after imputing the missing data
fit <- train (Species ~ ., 
              train, 
              preProcess = c("knnImpute"), 
              na.action  = na.pass, 
              method     = "rpart" )
test$species.hat <- predict (fit, test)

# there is 1 obs. (of 30) in the test set equal to NA  
# this 1 obs. was not returned from predict
Error in `$<-.data.frame`(`*tmp*`, "species.hat", value = c(1L, 1L, 1L,  : 
  replacement has 29 rows, data has 30

更新:我已经能够直接使用preProcess函数来填补值。我仍然不理解为什么这似乎不能在train函数内部发生。

# attempt to impute using nearest neighbors
x <- iris [, 1:4]
pp <- preProcess (x, method = c("knnImpute"))
x.imputed <- predict (pp, newdata = x)

# expect all NAs were populated with an imputed value
stopifnot( all (!is.na (x.imputed)))
stopifnot( length (x) == length (x.imputed))
1个回答

4

请参考?predict.train

 ## S3 method for class 'train'
 predict(object, newdata = NULL, type = "raw", na.action = na.omit, ...)

这里也有一个na.omit
 > length(predict (fit, test))
 [1] 29
 > length(predict (fit, test, na.action = na.pass))
 [1] 30

马克斯


2
这展示了如何使用predict函数直接处理NA值 - 是否有任何方法在train()函数内指定缺失值的处理方式?否则它不会包含在CV循环内。 - Misconstruction
1
@Misconstruction 记得在trainpredict中都包含 na.action = na.pass - adatum

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接