Estimated slopes, one point per sample

◆ The Blueprint
The model

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.

Why the slopes vary
$$\text{Var}(\hat\beta) = \sigma^2 (X^\top X)^{-1}$$

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\).

Ridge in matrix form
$$\hat\beta_{\text{ridge}} = (X^\top X + n\lambda I)^{-1} X^\top y$$

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 bias

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 scale of λ

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\).

The draws

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.

In R

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.

Your line and its residuals

Loss for each residual

◆ The Blueprint
The four losses

Each loss turns a residual \(e\) into a cost, and a line's total loss adds the costs over the points.

$$e^2, \qquad |e|, \qquad \rho_\delta(e) = \begin{cases} e^2/2 & |e| \le \delta \\ \delta\,(|e| - \delta/2) & |e| > \delta \end{cases}, \qquad \rho_\tau(e) = e\,\big(\tau - \mathbf{1}[e < 0]\big)$$
Why the best lines differ

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.

Quantile loss

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 Huber line

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 δ.

The four data sets

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.

In R

lm(y ~ x), quantreg::rq(y ~ x, tau = 0.5), and MASS::rlm(y ~ x). Part 2 of The Script.

Data and fitted lines

◆ The Blueprint
The outliers

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.

One outlier, two losses
$$e = 10: \qquad e^2 = 100, \qquad |e| = 10$$
Why the L1 line does not move

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

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.

When to use each

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.

In R

lm(), quantreg::rq(tau = 0.5), and MASS::rlm() on the same data. Part 3 of The Script.

SSE contours and the penalty region

◆ The Blueprint
Penalty and budget

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.

The three objectives
$$\tfrac{1}{2n}\text{SSE} + \lambda\Big[\alpha\,(|\beta_1| + |\beta_2|) + \tfrac{1-\alpha}{2}(\beta_1^2 + \beta_2^2)\Big]$$

\(\alpha = 1\) is the LASSO, \(\alpha = 0\) is ridge, and values between are the elastic net.

Why corners give zeros

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:

$$\hat\beta_{\text{LASSO}} = \text{sign}(\hat\beta_{\text{LS}})\,\max\big(|\hat\beta_{\text{LS}}| - \lambda,\ 0\big)$$
$$\hat\beta_{\text{ridge}} = \frac{\hat\beta_{\text{LS}}}{1 + \lambda}$$
The exact solution

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.

Correlation

\(\rho\) tilts and stretches the ellipses, which moves the point where they first touch the region.

In R

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.

Coefficient paths

Ten-fold cross-validation error

◆ The Blueprint
The data sets

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.

Standardization

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.

λmin and λ1se

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 folds

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.

In R

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.

Coefficients

Your fits

◆ The Blueprint
The split

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.

How λ is set

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.

Least squares

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.

Why test MSE varies

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.

In R

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.

The functions, one by one
CallWhat 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.
regularization_in_R.R