Tho*_*mas 5 regression r 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
Run Code Online (Sandbox Code Playgroud)
我尝试使用这个示例来反向转换预测:
# 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"
Run Code Online (Sandbox Code Playgroud)
这是行不通的——不应该有任何区别。我做错了什么?
我也研究了许多类似的问题,但没有设法将任何问题应用于我的案例(How to unscale the coss from an lmer()-modelfitting with ascaled response,unscale and uncenter glmer参量,Scale back Linear regressioncoefficients)在R中来自缩放和居中的数据,https://stats.stackexchange.com/questions/302448/back-transform-mixed-effects-models-regression-coefficients-for-fixed-effects-f)。
您的方法的问题在于,它仅根据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)
Run Code Online (Sandbox Code Playgroud)
将此p_unsc与未缩放模型(b在您的代码中)的预测进行比较,即all.equal(b,p_unsc)给出 TRUE。
另一种合理的方法是
beta_unscX <- model.matrix(formula(model,fixed.only=TRUE),
newdata=pred_frame)
Run Code Online (Sandbox Code Playgroud)
pred <- plogis(X %*% beta_unsc)
Run Code Online (Sandbox Code Playgroud)