Question

Je suis en train d'attribuer des valeurs en passant "knnImpute" pour le prétraitement de l'argument du Signe du train() la méthode.Basé sur l'exemple suivant, il apparaît que les valeurs ne sont pas imputés, reste que NA et sont alors ignorées.Ce que je fais mal?

Toute aide est très appréciée.

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

Mise à JOUR:J'ai été en mesure d'utiliser la fonction preProcess directement à imputer les valeurs.Je ne comprends toujours pas pourquoi cela ne semble pas se produire dans le train de la fonction.

# 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))
Était-ce utile?

La solution

Voir ?predict.train:

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

Il y a un na.omit ici aussi:

 > length(predict (fit, test))
 [1] 29
 > length(predict (fit, test, na.action = na.pass))
 [1] 30

Max

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top