我正在建立一个预测模型,并使用mice包在我的训练集中估算NA。由于我需要为测试集重复使用相同的插补方案,因此如何将其应用于测试数据?

# generate example data
set.seed(333)
mydata <- data.frame(a = as.logical(rbinom(100, 1, 0.5)),
                     b = as.logical(rbinom(100, 1, 0.2)),
                     c = as.logical(rbinom(100, 1, 0.8)),
                     y = as.logical(rbinom(100, 1, 0.6)))

na_a <- as.logical(rbinom(100, 1, 0.3))
na_b <- as.logical(rbinom(100, 1, 0.3))
na_c <- as.logical(rbinom(100, 1, 0.3))
mydata$a[na_a] <- NA
mydata$b[na_b] <- NA
mydata$c[na_c] <- NA

# create train/test sets
library(caret)
inTrain <- createDataPartition(mydata$y, p = .8, list = FALSE)
train <- mydata[ inTrain, ]
test <-  mydata[-inTrain, ]

# impute NAs in train set
library(mice)
imp <- mice(train, method = "logreg")
train_imp <- complete(imp)

# apply imputation scheme to test set
test_imp <- unknown_function(test, imp$unknown_data)

最佳答案

prockenschaub为此创建了一个可爱的函数,称为mice.reuse()

library(mice)
library(scorecard)

# function to impute new observations based on the previous imputation model
source("https://raw.githubusercontent.com/prockenschaub/Misc/master/R/mice.reuse/mice.reuse.R")

# split data into train and test
data_list <- split_df(airquality, y = NULL, ratio = 0.75, seed = 186)

imp <- mice(data = data_list$train,
            seed = 500,
            m = 5,
            method = "pmm",
            print = FALSE)


# impute test data based on train imputation model
test_imp <- mice.reuse(imp, data_list$test, maxit = 1)

07-24 09:22