glmer的反变换系数和比例独立变量用于预测

时间:2018-11-15 17:31:42

标签: r regression scale lme4

我使用lme4包安装了混合模型。在拟合模型之前,我使用scale()函数转换了自变量。现在,我想使用predict()在图表上显示结果,因此我需要将预测数据恢复到原始比例。我该怎么做?

简化示例:

database <- mtcars

# Scale data
database$wt <- scale(mtcars$wt)
database$am <- scale(mtcars$am)

# Make model
model.1 <- glmer(vs ~ scale(wt) + scale(am) + (1|carb), database, family = binomial, na.action = "na.fail")

# make new data frame with all values set to their mean
xweight <- as.data.frame(lapply(lapply(database[, -1], mean), rep, 100))

# make new values for wt
xweight$wt <- (wt = seq(min(database$wt), max(database$wt), length = 100))

#  predict from new values
a <- predict(model.1, newdata = xweight, type="response", re.form=NA)

# returns scaled prediction

我尝试使用this example对预测进行反变换:

# save scale and center values
scaleList <- list(scale = attr(database$wt, "scaled:scale"),
              center = attr(database$wt, "scaled:center"))

# back-transform predictions
a.unscaled <- a * scaleList$scale + scaleList$center

# Make model with unscaled data to compare
un.model.1 <- glmer(vs ~ wt + am + (1|carb), mtcars, family = binomial, na.action = "na.fail")

# make new data frame with all values set to their mean
un.xweight <- as.data.frame(lapply(lapply(mtcars[, -1], mean), rep, 100))

# make new values for wt
un.xweight$wt <- (wt = seq(min(mtcars$wt), max(mtcars$wt), length = 100))

#  predict from new values
b <- predict(un.model.1, newdata = xweight, type="response", re.form=NA)

all.equal(a.unscaled,b)
# [1] "Mean relative difference: 0.7223061"

这不起作用-不应有任何区别。 我做错了什么?

我也查看了许多类似的问题,但没有设法将其应用于我的案例(How to unscale the coefficients from an lmer()-model fitted with a scaled responseunscale and uncenter glmer parametersScale back linear regression coefficients in R from scaled and centered datahttps://stats.stackexchange.com/questions/302448/back-transform-mixed-effects-models-regression-coefficients-for-fixed-effects-f)。 / p>

1 个答案:

答案 0 :(得分:2)

您的方法存在的问题是,它仅基于wt变量“未缩放”,而您缩放了回归模型中的所有变量。一种有效的方法是使用在原始数据帧上使用的居中/缩放值来调整新(预测)数据帧中的所有变量:

## scale variable x using center/scale attributes
## of variable y
scfun <- function(x,y) {
    scale(x, 
          center=attr(y,"scaled:center"), 
          scale=attr(y,"scaled:scale"))
}
## scale prediction frame
xweight_sc <- transform(xweight,
                        wt = scfun(wt, database$wt),
                        am = scfun(am, database$am))
## predict
p_unsc <- predict(model.1, 
                  newdata=xweight_sc, 
                  type="response", re.form=NA)

将此p_unsc与您根据未缩放模型(代码中的b)所做的预测(即all.equal(b,p_unsc))进行比较,得出TRUE。

另一种合理的方法是

    使用链接问题之一(例如this one)中介绍的“不缩放”方法,
  • 不缩放/不居中所有参数,生成系数向量beta_unsc
  • 根据预测框架构造适当的模型矩阵:
X <- model.matrix(formula(model,fixed.only=TRUE), 
         newdata=pred_frame)
  • 计算线性预测变量并进行逆变换:
pred <- plogis(X %*% beta_unsc)