我使用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 response,unscale and uncenter glmer parameters,Scale back linear regression coefficients in R from scaled and centered data,https://stats.stackexchange.com/questions/302448/back-transform-mixed-effects-models-regression-coefficients-for-fixed-effects-f)。 / p>
答案 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。
另一种合理的方法是
beta_unsc
X <- model.matrix(formula(model,fixed.only=TRUE),
newdata=pred_frame)
pred <- plogis(X %*% beta_unsc)