【发布时间】:2016-03-26 01:45:56
【问题描述】:
我有一个模型,我对变量 x 进行了缩放,然后使用缩放后的 x 和缩放后的 x 的平方作为预测变量。即lm(y ~ I(scale(x)) + I(scale(x)^2)。我想让系数适用于原始 x 单位,但我很难弄清楚如何做到这一点。我认为问题在于缩放后的平方,但我不知道。
This answer 让我非常接近,我想。同样,差异可能是缩放后的平方。
下面是一个 R 脚本,显示了我创建假数据和尝试取消缩放的过程。抱歉,我想它有点长。
奇怪的是,最后,我得到了平方项的重新缩放权,但不是线性项或截距。鉴于我使用上述答案中的方法,我猜我会得到平方系数错误!
如何“取消缩放”参数?
set.seed(1)
# ---- Create Covariates ----
# Define dimensions for simulation
n <- 100
# Covariate Simulation Parameters
mean.temp <- 10
sd.temp <- 5
mean.depth <- 200
sd.depth <- 20
# Simulate Covariates
temperature <- rnorm(n=n, mean=mean.temp, sd=sd.temp)
depth <- rnorm(n=n, mean=mean.depth, sd=sd.depth)
# Create Unscaled Data Matrix
dmat <- data.frame(
temp=temperature, temp2=temperature^2,
depth=depth, depth2=depth^2
)
# Scale Covariates
temp.scale <- scale(temperature)
depth.scale <- scale(depth)
# Create Scaled Data Matrix
dmat.scale <- data.frame(
temp=temp.scale, temp2=temp.scale^2,
depth=depth.scale, depth2=depth.scale^2
)
# Record Scaling Factors
mu.vec <- c(
"temp.mu"=attr(temp.scale,'scaled:center'),
"temp2.mu"= attr(temp.scale,'scaled:center')^2, # is this right?
"depth.mu"=attr(depth.scale,'scaled:center'),
"depth2.mu"= attr(depth.scale,'scaled:center')^2 # is this right?
)
sd.vec <- c(
"temp.sd"=attr(temp.scale,'scaled:scale'),
"temp2.sd"= attr(temp.scale,'scaled:scale')^2,
"depth.sd"=attr(depth.scale,'scaled:scale'),
"depth2.sd"= attr(depth.scale,'scaled:scale')^2
)
# ---- Create Parameters ----
beta <- matrix(c(0.5, 0.1, -0.8, 1.2, -0.1),ncol=1)
# ---- Simulate ----
eps <- rnorm(n=n, mean=0, sd=0.001)
y <- (cbind(1,as.matrix(dmat))%*%beta + eps)[,1]
# ---- Fit Models ----
mod <- lm(y~as.matrix(dmat))
mod.scale <- lm(y~as.matrix(dmat.scale))
beta.orig <- coef(mod)
beta.scale <- coef(mod.scale)
# ---- Rescale Function ----
# From: https://stackoverflow.com/a/23643740/2343633
rescale.coefs <- function(beta,mu,sigma) {
beta2 <- beta ## inherit names etc.
beta2[-1] <- sigma[1]*beta[-1]/sigma[-1]
beta2[1] <- sigma[1]*beta[1]+mu[1]-sum(beta2[-1]*mu[-1])
beta2
}
beta.rescale <- rescale.coefs(beta.scale, mu=c(0,mu.vec), sigma=c(1,sd.vec))
# ---- Compare ----
beta.orig
beta.rescale
【问题讨论】:
标签: r regression