Each row has predictors \((x_1, x_2)\) drawn from a normal distribution with means 0, standard deviations 1, and correlation \(\rho\), and a response \(y = 3x_1 + 1.5x_2 + \varepsilon\) with \(\varepsilon \sim N(0, \sigma^2)\). Every variable has mean 0, so the fits have no intercept. The test MSE uses one set of 500 new rows for every fit.
With two predictors of standard deviation 1, each slope's variance is about \(\sigma^2 / \big(n(1-\rho^2)\big)\), which is \(\sigma^2/n\) times the variance inflation factor (VIF). Along the direction \(\beta_1 - \beta_2\) the variance is multiplied by \(1/(1-\rho)\), and along \(\beta_1 + \beta_2\) by \(1/(1+\rho)\). That is why the estimates spread along the line \(\beta_1 + \beta_2 = 4.5\).
Setting the gradient of \(\tfrac{1}{2n}\text{SSE} + \tfrac{\lambda}{2}\sum_j \beta_j^2\), which is \(-\tfrac{1}{n}X^\top(y - X\beta) + \lambda\beta\), to zero gives this formula. Adding \(n\lambda\) to each diagonal entry raises the small eigenvalue of \(X^\top X\), about \(n(1-\rho)\), to about \(n(1-\rho+\lambda)\), so the variance along \(\beta_1 - \beta_2\) falls sharply.
The ridge estimate averages \((X^\top X + n\lambda I)^{-1}X^\top X\,\beta\), which is shorter than \(\beta\) for every \(\lambda > 0\). Test MSE is \(\sigma^2\) plus the squared bias of the predictions plus their variance, so it rises once the added bias outgrows the variance that ridge removes.
The objective here is written as glmnet writes it, with \(\tfrac{1}{2n}\text{SSE}\). Minimizing \(\text{SSE} + \lambda'\sum_j\beta_j^2\) gives the same set of fits with \(\lambda' = n\lambda\).
Each draw is one fixed set of random samples: draw k is what R produces after set.seed(k). Draw new samples moves to the next draw, and Part 1 of The Script reproduces draw 1 exactly.
solve(crossprod(X) + diag(n * lambda, 2), crossprod(X, y)) returns the ridge estimate for one sample, and car::vif(lm(y ~ x1 + x2)) returns the VIF. Part 1 of The Script.
Each loss turns a residual \(e\) into a cost, and a line's total loss adds the costs over the points.
Setting the derivatives of \(\sum e_i^2\) to zero gives the normal equations, whose solution is the least squares line. The absolute value has no derivative at 0, so the median (L1) line is found by linear programming instead. It passes through two of the points, and about as many points lie above it as below.
With \(\tau = 0.5\), the quantile loss is half the absolute loss, so its best line is the median line. Other values of \(\tau\) fit the \(\tau\) quantile of \(y\) at each \(x\).
The δ slider changes the Huber curve and the Huber total. The Huber line comes from MASS::rlm() with its default \(k = 1.345\), applied to residuals divided by their typical absolute size (the median absolute deviation), and it does not move with δ.
Clean linear: \(y = 1 + 2x\) plus noise with standard deviation 0.5. With outlier: the same, with the rightmost point moved 3 standard deviations of y below the lowest point. Unequal variance: the same line, with a noise standard deviation of \(0.3(x + 0.5)\), which grows from 0.15 at \(x = 0\) to 1.65 at \(x = 5\). Curved: \(y = 1 + 0.5x^{1.5}\) plus noise with standard deviation 0.5.
lm(y ~ x), quantreg::rq(y ~ x, tau = 0.5), and MASS::rlm(y ~ x). Part 2 of The Script.
The outliers are placed at evenly spaced x values from 0.6 to 1.1 times the largest x, each below the true line by the chosen number of standard deviations of the clean y values.
The L1 line minimizes \(\sum |y_i - \beta_0 - \beta_1 x_i|\). Lowering a point that is already below a line raises its residual by the same amount for every line that stays above it, so the minimizing line does not change. Least squares weights each residual by its own size, since the derivative of \(e^2\) is \(2e\), so a far point has a large influence on the fit.
Huber loss is squared within 1.345 scaled residuals and absolute beyond that. MASS::rlm() fits it by refitting least squares repeatedly with updated weights (iteratively reweighted least squares), with the scale estimated from the median absolute deviation.
Least squares suits clean data with normal errors. Median regression suits heavy-tailed errors or known outliers. Huber treats small residuals as least squares does and large ones as median regression does.
lm(), quantreg::rq(tau = 0.5), and MASS::rlm() on the same data. Part 3 of The Script.
Minimizing \(\tfrac{1}{2n}\text{SSE} + \lambda \times \text{penalty}(\beta)\) gives the same estimate as minimizing SSE subject to \(\text{penalty}(\beta) \le t\) for some budget \(t\). The gold region is that budget, drawn through the current estimate, and the dashed ember ellipse is the SSE contour that touches it.
\(\alpha = 1\) is the LASSO, \(\alpha = 0\) is ridge, and values between are the elastic net.
With one predictor of standard deviation 1, the LASSO estimate is the least squares slope moved toward 0 by \(\lambda\) and stopped at 0, while ridge divides by \(1 + \lambda\), which never reaches 0:
With two slopes, the exact minimizer comes from trying each of the nine ways \(\beta_1\) and \(\beta_2\) can be positive, negative, or zero, and keeping the one where no small change lowers the objective. glmnet's LASSO agrees with it to within 0.003. glmnet's ridge and elastic net with standardize = FALSE do not: glmnet rescales y internally, which divides the squared part of the penalty by the root mean square of y.
\(\rho\) tilts and stretches the ellipses, which moves the point where they first touch the region.
glmnet(X, y, alpha = 1, lambda = 0.316, intercept = FALSE, standardize = FALSE) fits the LASSO, and solve(crossprod(X) + diag(n * lambda, 2), crossprod(X, y)) fits ridge. Part 4 of The Script.
Sparse: ten predictors with pairwise correlation 0.3 and true coefficients \((3, 1.5, -2, 0, \dots, 0)\). Dense: eight predictors with correlation 0.3, all eight coefficients nonzero. Correlated: six predictors with correlation 0.8 and true coefficients \((3, 1.5, -2, 0, 0, 0)\). Every set adds noise with standard deviation 1. mtcars: miles per gallon on six standardized car measurements, with no true model.
glmnet rescales each predictor to standard deviation 1 before it applies the penalty, so the penalty treats every coefficient the same whatever its predictor's units, and it reports the coefficients in the original units.
cv.glmnet's cvm is the average of the ten held-out-fold MSEs at each \(\lambda\), and cvsd is its standard error. \(\lambda_{\min}\) minimizes cvm. \(\lambda_{1se}\) is the largest \(\lambda\) with cvm at most \(\text{cvm}(\lambda_{\min}) + \text{cvsd}(\lambda_{\min})\).
The ten folds come from sample(rep(1:10, length = n)) right after the data are drawn, which is what cv.glmnet does inside. Every method on one data draw uses the same folds.
fit <- glmnet(X, y, alpha = 1), plot(fit, xvar = "lambda") (which uses the natural log of λ, where these plots use log₁₀), cv <- cv.glmnet(X, y, alpha = 1, nfolds = 10), and coef(cv, s = "lambda.1se"). Part 5 of The Script.
The rows are split once per data draw, 70 percent for training and the rest for testing, with sample(n, floor(0.7 * n)). Every method on that draw uses the same split, so their test MSEs are comparable.
With Choose λ by cross-validation checked, λ is \(\lambda_{\min}\) from ten-fold cv.glmnet() on the training rows only, and glmnet then refits at that λ. Unchecked, λ comes from the slider.
lm(y_train ~ X_train), with an intercept. Its training MSE is the lowest any linear model can reach on the training rows, because least squares minimizes exactly that.
The test set is a small sample of 30 rows at n = 100, so a different split can change which method has the lowest test MSE. Check a method's test MSE on several draws before trusting one comparison.
cv <- cv.glmnet(X_train, y_train, alpha = 1), then predict(cv, newx = X_test, s = "lambda.min"), and mean((y_test - pred)^2). Part 6 of The Script.
| Call | What it returns |
|---|---|
glmnet(X, y, alpha = 1) | The whole LASSO path over glmnet's own grid of λ values. alpha = 0 is ridge; values between are the elastic net. |
plot(fit, xvar = "lambda") | The coefficient paths against the natural log of λ. |
cv.glmnet(X, y, alpha = 1, nfolds = 10) | Ten-fold cross-validation at every λ: cvm (the average held-out error), cvsd (its standard error), and the two chosen values of λ, lambda.min and lambda.1se. |
coef(cv, s = "lambda.1se") | The coefficients at a chosen λ, with zeros for the predictors the LASSO removed. |
predict(cv, newx = X_test, s = "lambda.min") | Predictions for new rows, for the test MSE. |
quantreg::rq(y ~ x, tau = 0.5) | The median (L1) regression line; other values of tau give quantile lines. |
MASS::rlm(y ~ x) | The Huber regression line. |