LASSO与$ \ lambda = 0 $和OLS在R glmnet中产生不同的结果

时间:2016-07-14 06:30:15

标签: r least-squares lasso lm

我希望LASSO没有惩罚($ \ lambda = 0 $)来产生与OLS拟合相同(或非常相似)的系数估计值。但是,我在R中得到不同的系数估计值,将相同的数据(x,y)放入

  • glmnet(x, y , alpha=1, lambda=0)适用于LASSO并且没有任何惩罚和
  • lm(y ~ x)适用于OLS。

为什么?

4 个答案:

答案 0 :(得分:4)

您使用的功能错误。 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)

答案 1 :(得分:1)

我已经使用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)

并且系数的结果相似。当我们使用standardize选项时,glmnet()返回的系数是输入变量的原始单位。 请检查您使用的是“高斯”家庭

答案 2 :(得分:1)

我遇到了同样的问题,被问到无济于事,然后我通过电子邮件发送了包维护者(Trevor Hastie),他给出了答案。当序列高度相关时会出现问题。解决方案是降低glmnet()函数调用中的阈值(而不是通过glmnet.control())。下面的代码使用内置数据集EuStockMarkets并将VAR应用于lambda=0。对于XSMI,OLS系数低于1,默认glmnet系数高于1,差值约为0.03,glmnet系数与thresh=1e-14非常接近OLS系数(相差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

答案 3 :(得分:0)

来自glmnet的帮助:请注意,对于“高斯”,glmnet标准化y在计算之前具有单位方差 它的lambda序列(然后使得到的系数不标准化);如果你想复制 - duce /将结果与其他软件进行比较,最好提供标准化的y。