当某些输入具有缺失值 (NA) 时使用 randomForest (R) 进行预测

机器算法验证 r 随机森林 预言 缺失数据
2022-03-27 00:59:35

我有一个很好的randomForest分类模型,我想在预测新案例类别的应用程序中使用它。新案例不可避免地存在缺失值。Predict 不适用于 NA。那我该怎么做呢?

data(iris)
# create first the new case with missing values
na.row<-45
na.col<-c(3,5)
case.na<-iris[na.row,]
case.na[,na.col]<-NA

iris.rf <- randomForest(Species ~ ., data=iris[-na.row,])
# print(iris.rf)

myrf.pred <- predict(iris.rf, case.na[-5], type="response")
myrf.pred
[1] <NA>

我试过了missForest我将原始数据和新案例结合起来,用 摇晃它missForest,并在我的新案例中获得了 NA 的估算值。不过计算量太大了。

data.imp <- missForest(data.with.na)

但是必须有一种方法可以使用 rf-model 来预测具有缺失值的新案例,对吧?

1个回答

您别无选择,只能估算值或更改模型。一个不错的选择可能是 Hmisc 包中的 aregImpute。我认为它比 rfimpute 更轻,这是拘留你的原因,第一个包示例(还有其他示例):

# Check that aregImpute can almost exactly estimate missing values when
# there is a perfect nonlinear relationship between two variables
# Fit restricted cubic splines with 4 knots for x1 and x2, linear for x3
set.seed(3)
x1 <- rnorm(200)
x2 <- x1^2
x3 <- runif(200)
m <- 30
x2[1:m] <- NA
a <- aregImpute(~x1+x2+I(x3), n.impute=5, nk=4, match='closest')
a
matplot(x1[1:m]^2, a$imputed$x2)
abline(a=0, b=1, lty=2)

x1[1:m]^2
a$imputed$x2

# Multiple imputation and estimation of variances and covariances of
# regression coefficient estimates accounting for imputation
# Example 1: large sample size, much missing data, no overlap in
# NAs across variables
x1 <- factor(sample(c('a','b','c'),1000,TRUE))
x2 <- (x1=='b') + 3*(x1=='c') + rnorm(1000,0,2)
x3 <- rnorm(1000)
y  <- x2 + 1*(x1=='c') + .2*x3 + rnorm(1000,0,2)
orig.x1 <- x1[1:250]
orig.x2 <- x2[251:350]
x1[1:250] <- NA
x2[251:350] <- NA
d <- data.frame(x1,x2,x3,y)
# Find value of nk that yields best validating imputation models
# tlinear=FALSE means to not force the target variable to be linear
f <- aregImpute(~y + x1 + x2 + x3, nk=c(0,3:5), tlinear=FALSE,
                data=d, B=10) # normally B=75
f
# Try forcing target variable (x1, then x2) to be linear while allowing
# predictors to be nonlinear (could also say tlinear=TRUE)
f <- aregImpute(~y + x1 + x2 + x3, nk=c(0,3:5), data=d, B=10)
f

# Use 100 imputations to better check against individual true values
f <- aregImpute(~y + x1 + x2 + x3, n.impute=100, data=d)
f
par(mfrow=c(2,1))
plot(f)
modecat <- function(u) {
 tab <- table(u)
 as.numeric(names(tab)[tab==max(tab)][1])
}
table(orig.x1,apply(f$imputed$x1, 1, modecat))
par(mfrow=c(1,1))
plot(orig.x2, apply(f$imputed$x2, 1, mean))
fmi <- fit.mult.impute(y ~ x1 + x2 + x3, lm, f, 
                       data=d)
sqrt(diag(vcov(fmi)))
fcc <- lm(y ~ x1 + x2 + x3)
summary(fcc)   # SEs are larger than from mult. imputation

您提到您有许多新的观察结果在自变量上有缺失值。即使你有很多这样的情况,如果对于每个新的观察,它的一个或两个变量中只有一个缺失,并且你的变量数量并不小,也许只是用中位数或平均值填充漏洞(它们是连续的吗?)可以工作。

另一件可能有趣的事情是进行次要变量重要性分析。随机森林 R 实现计算两个重要性度量和各自的图:

varImpPlot(yourRandomForestModel) # yourRandomForestModel must have the argument importance=TRUE 

您可以在模型训练中只包含“重要”变量,直到与“完整模型”相比,预测准确性不会受到太大影响。也许您保留了缺失数量较少的变量。它可以帮助您减少问题的规模。