我希望没有惩罚的 LASSO ($\lambda=0$) 产生与 OLS 拟合相同(或非常相似)的系数估计。但是,我在 R 中得到不同的系数估计值,将相同的数据 (x,y) 放入
glmnet(x, y , alpha=1, lambda=0)
对于 LASSO 适合没有惩罚和lm(y ~ x)
适合 OLS。
这是为什么?
我希望没有惩罚的 LASSO ($\lambda=0$) 产生与 OLS 拟合相同(或非常相似)的系数估计。但是,我在 R 中得到不同的系数估计值,将相同的数据 (x,y) 放入
glmnet(x, y , alpha=1, lambda=0)
对于 LASSO 适合没有惩罚和lm(y ~ x)
适合 OLS。这是为什么?
您使用的功能错误。x
应该是模型矩阵。不是原始预测值。当你这样做时,你会得到完全相同的结果:
x <- rnorm(500)
y <- rnorm(500)
mod1 <- lm(y ~ x)
xmm <- model.matrix(mod1)
mod2 <- glmnet(xmm, y, alpha=1, lambda=0)
coef(mod1)
coef(mod2)
我遇到了同样的问题,四处询问无济于事,然后我通过电子邮件发送给给出答案的包维护者(Trevor Hastie)。当系列高度相关时,就会出现问题。解决方案是降低glmnet()
函数调用中的阈值(而不是 via glmnet.control()
)。下面的代码使用内置数据集EuStockMarkets
并应用 VAR 和lambda=0
. 对于 XSMI,OLS 系数在 1 以下,默认glmnet
系数在 1 以上,相差约 0.03,与OLSglmnet
系数thresh=1e-14
非常接近(相差 0 1.8e-7
)。
# Use built-in panel data with integrated series
data("EuStockMarkets")
selected_market <- 2
# Take logs for good measure
EuStockMarkets <- log(EuStockMarkets)
# Get dimensions
num_entities <- dim(EuStockMarkets)[2]
num_observations <- dim(EuStockMarkets)[1]
# Build the response with the most recent observations at the top
Y <- as.matrix(EuStockMarkets[num_observations:2, selected_market])
X <- as.matrix(EuStockMarkets[(num_observations - 1):1, ])
# Run OLS, which adds an intercept by default
ols <- lm(Y ~ X)
ols_coef <- coef(ols)
# run glmnet with lambda = 0
fit <- glmnet(y = Y, x = X, lambda = 0)
lasso_coef <- coef(fit)
# run again, but with a stricter threshold
fit_threshold <- glmnet(y = Y, x = X, lambda = 0, thresh = 1e-14)
lasso_threshold_coef <- coef(fit_threshold)
# build a dataframe to compare the two approaches
comparison <- data.frame(ols = ols_coef,
lasso = lasso_coef[1:length(lasso_coef)],
lasso_threshold = lasso_threshold_coef[1:length(lasso_threshold_coef)]
)
comparison$difference <- comparison$ols - comparison$lasso
comparison$difference_threshold <- comparison$ols - comparison$lasso_threshold
# Show the two values for the autoregressive parameter and their difference
comparison[1 + selected_market, ]
R
返回:
ols lasso lasso_threshold difference difference_threshold
XSMI 0.9951249 1.022945 0.9951248 -0.02782045 1.796699e-07
我使用 Hastie 书中的“前列腺”示例数据集运行了下一个代码:
out.lin1 = lm( lpsa ~ . , data=yy )
out.lin1$coeff
out.lin2 = glmnet( as.matrix(yy[ , -9]), yy$lpsa, family="gaussian", lambda=0, standardize=T )
coefficients(out.lin2)
并且系数的结果是相似的。当我们使用标准化选项时,glmnet() 返回的系数是输入变量的原始单位。请检查您使用的是“高斯”系列
来自 glmnet 帮助:另请注意,对于“高斯”,glmnet 在计算其 lambda 序列之前将 y 标准化为具有单位方差(然后对结果系数进行非标准化);如果您想用其他软件重现/比较结果,最好提供一个标准化的 y。