[英]LASSO with $\lambda = 0$ and OLS produce different results in R glmnet
我期望LASSO沒有懲罰($ \\ lambda = 0 $)來產生與OLS擬合相同(或非常相似)的系數估計。 但是,我在R中得到不同的系數估計值,將相同的數據(x,y)放入其中
glmnet(x, y , alpha=1, lambda=0)
適合沒有懲罰和 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)
我已經使用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()返回的系數是輸入變量的原始單位。 請檢查您使用的是“高斯”系列
我遇到了同樣的問題,被問到無濟於事,然后我通過電子郵件發送了包維護者(Trevor Hastie)給出了答案。 當序列高度相關時會出現問題。 解決方案是降低glmnet()
函數調用的閾值(而不是通過glmnet.control()
)。 下面的代碼使用內置數據集EuStockMarkets
並應用lambda=0
的VAR。 對於XSMI,OLS系數低於1,默認glmnet
系數高於1,差值約為0.03,而使用thresh=1e-14
的glmnet
系數非常接近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
來自glmnet的幫助:還要注意,對於“高斯”,glmnet在計算其lambda序列之前將y標准化為單位方差(然后對結果系數進行非標准化); 如果您希望與其他軟件重現/比較結果,最好提供標准化的y。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.