Linear regression: least squares, ridge, lasso and elastic net
| Problem | Fit to data, optionally with weighted or correlated errors, or with a penalty that shrinks or selects the weights |
| Devised by | Adrien-Marie Legendre (1805) and Carl Friedrich Gauss (1809), least squares; Alexander Aitken (1935), generalised least squares; Andrey Tikhonov (1943) and Arthur Hoerl and Robert Kennard (1970), ridge regression; Robert Tibshirani (1996), the lasso; Hui Zou and Trevor Hastie (2005), the elastic net; Jerome Friedman, Trevor Hastie and Robert Tibshirani (2007), coordinate descent |
| Accuracy | Optimality conditions satisfied to (least squares, ridge) and (lasso, elastic net) |
| Cost | Least squares and ridge: by SVD or normal equations. Elastic net: per sweep of coordinate descent |
| Read first | Foundations: models, data, preprocessing and metrics, Linear least squares |
| API | LinearRegression, GeneralLeastSquares, Ridge, ElasticNet |
Overview
Linear regression predicts a number as a weighted sum of the features plus an intercept. It is the oldest learning method and still the first to try: fast, interpretable, and with a complete statistical theory. Polynomial and other basis expansions make it fit curves, since the model only needs to be linear in the weights. Its weakness is variance: with many or correlated features, or few samples, the least-squares weights become large and unstable. Penalties cure this: ridge shrinks all the weights, the lasso sets some exactly to zero, and the elastic net combines the two.
Where it is used
Linear regression is the first model to try for a numerical relationship.
- Science and engineering. Calibration curves, dose-response, material properties as a function of temperature or composition, and trend lines.
- Economics and the social sciences. Relating outcomes to predictors with estimates of uncertainty.
- Regularisation. Ridge regression stabilises ill-conditioned problems (many correlated sensors); the lasso selects a few relevant variables, as in genomics and spectroscopy.
- Signal processing. Linear prediction and channel estimation are regression problems.
History
Adrien-Marie Legendre published the method of least squares in 1805 to fit comet orbits; Carl Friedrich Gauss, who claimed to have used it since 1795, justified it in 1809 by normal errors, and later (1821) proved it optimal among linear unbiased estimators, the Gauss-Markov theorem. Francis Galton’s work on heredity gave “regression” its name (1886). Alexander Aitken (1935) extended least squares to correlated errors. Andrey Tikhonov (1943) regularised ill-posed integral equations, and Arthur Hoerl and Robert Kennard (1970) introduced the same idea to statistics as ridge regression. Robert Tibshirani’s lasso (1996) brought the penalty and variable selection, Bradley Efron and colleagues (2004) traced its whole solution path with LARS, and Hui Zou and Trevor Hastie (2005) proposed the elastic net. Jerome Friedman, Hastie and Tibshirani (2007, 2010) showed that simple coordinate descent solves these problems faster than anything else, the basis of the glmnet package.
The idea
Least squares
The model. The data are samples, each with features, collected as the rows of an matrix , together with a vector of the values to be predicted. The model predicts
with a weight for each feature and an intercept .
The fit. The weights are chosen to minimise the residual sum of squares , the sum of squared differences between the observed and predicted values. The intercept can be treated as one more weight by appending a column of ones to . This is exactly the linear least-squares problem of the linear algebra chapter, whose solution satisfies the normal equations : at the minimum, the residual is orthogonal to every column of .
The library does not solve the normal equations, since forming squares the condition number. It uses the singular value decomposition, which also behaves sensibly when the weights are not uniquely determined, because features are collinear or outnumber the samples: it then returns the solution of smallest norm.
Overfitting. Least squares finds the best fit to the training data, which is not the same as the best prediction of new data. A flexible enough model can follow the noise in the training points as well as the trend. With 20 points, a polynomial of degree 15 has almost enough freedom to pass through all of them, and swings wildly in between; a polynomial of degree 3, or a penalised degree-15 fit (below), follows the underlying curve:
Figure 11.1. Polynomial fits.
Weighted and generalised least squares
Ordinary least squares treats every observation alike. That is right when the errors all have the same variance and are independent of each other, and wasteful otherwise: a measurement known to be noisy should count for less than a precise one.
When the errors are independent with known variances , weighted least squares minimises . Each residual is measured in units of its own standard deviation, so that noisy points count for less.
More generally, if the errors have covariance matrix (so that they may also be correlated), generalised least squares minimises , and this is the best linear unbiased estimator. It needs no new algorithm. Factorise by Cholesky and multiply both and by . The transformed errors have covariance : they are uncorrelated with unit variance. The transformation is said to whiten the problem, which is then solved by ordinary least squares.
Figure 11.2. Weighted least squares.
| estimator | mean slope (true 2) | sd of slope | mean intercept (true 1) | sd of intercept |
|---|---|---|---|---|
| ordinary least squares | 1.9992 | 0.1602 | 1.0104 | 0.5396 |
| weighted least squares | 2.0006 | 0.0942 | 1.0055 | 0.1471 |
Over 2000 simulated data sets of 50 points.
Both estimators are unbiased, but weighting by the inverse variance cuts the spread of the slope by 40% and of the intercept by a factor of 3.7.
Ridge regression
Overfitting shows itself in the weights: to follow noise, a flexible model needs large weights of opposite signs that nearly cancel. Ridge regression discourages them by adding a penalty on the size of the weights to the quantity being minimised:
The parameter sets the strength of the penalty: is least squares, and as all the weights are driven to zero. The intercept is not penalised (the data are centred first), since there is no reason to prefer predictions near zero.
Setting the gradient to zero gives a modified form of the normal equations,
The matrix is positive definite for any , so the solution exists and is unique even with more features than samples, where least squares is not.
What the penalty does. The SVD shows it precisely. The least-squares solution divides each component of the data (along the singular direction ) by the singular value . A small marks a direction in feature space along which the data hardly vary, so that the weight along it is poorly determined; dividing by it amplifies the noise. Ridge multiplies each component of the least-squares solution by
For this factor is close to 1 and the component is untouched. For it is close to 0 and the component is suppressed. Ridge damps precisely the directions where noise is amplified most.
The trade-off (the bias-variance decomposition explains it). The penalised weights are biased towards zero, but vary less from one training sample to another. A little bias in exchange for a large reduction in variance improves the predictions; too much makes them worse. The error on test data is lowest at an intermediate :
Figure 11.3. Ridge error.
The lasso and the elastic net
The lasso replaces the squared penalty by the sum of absolute values, . The change looks minor, but it has a striking effect: the solution is sparse. As grows, weights become exactly zero one by one, so the lasso selects features as well as shrinking them.
Why the absolute value gives zeros. A problem with a single weight shows the mechanism. Minimise , where is the value the weight would take without a penalty. For the derivative is , which vanishes at ; this is a valid solution only if . Similarly if . For neither applies, and the minimum is at the corner . Altogether
the soft-thresholding function: values smaller than are set to zero, and larger ones are moved towards zero by . The absolute value has a constant slope right down to zero, so a weak pull from the data cannot overcome it. The squared penalty of ridge, by contrast, has a slope that vanishes at zero: its solution is , which shrinks but never reaches zero.
The elastic net uses both penalties:
with the lasso and a scaled ridge. The mixture helps with correlated features. Among a group of features that carry the same information the lasso tends to keep one, chosen almost arbitrarily, and discard the rest; the ridge part spreads the weight among them. On eight features of which three matter (and one is correlated with the first):
Ridge shrinks all weights smoothly towards zero and never reaches it; the lasso sets the irrelevant weights to zero at once and the real ones only for large .
Coordinate descent
The elastic-net objective cannot be minimised by setting a gradient to zero, because is not differentiable where , and that is exactly where many of the solution’s weights lie. But the one-weight problem above has a closed-form answer, and that suggests an algorithm: optimise one weight at a time, holding the others fixed.
With all weights but fixed, let be the residual computed without feature , that is minus the contributions of all the other features, and let be column of . As a function of alone the objective is
a one-weight problem of the kind just solved. Its minimiser is
The numerator measures how strongly feature is correlated with what the other features have left unexplained. If that correlation is below the threshold , the weight is set to zero.
Coordinate descent cycles through the weights, updating each by this formula and keeping the residual up to date, until the weights stop changing. Optimising one coordinate at a time does not work for every function, but it does here: the objective is convex (so, as the optimisation background shows, any stationary point is the global minimum), and its non-differentiable part is a sum of terms each involving a single weight, which together guarantee convergence to the global minimum.
Algorithm
Least squares.
- Append a column of ones to (if an intercept is wanted).
- Compute the SVD of the augmented matrix and form the minimum-norm solution, treating negligible singular values as zero.
- The last coefficient is the intercept ; the others are the weights .
Weighted and generalised least squares.
- For independent errors with weights , multiply row of and entry of by . For a general covariance, factor and replace and by and , computed by triangular solves.
- Solve the transformed problem by ordinary least squares.
Ridge.
- Centre: subtract the column means from and the mean from .
- Solve .
- Recover the intercept, , so that the fitted plane passes through the mean of the data.
Elastic net (coordinate descent).
- Centre and as for ridge. Start with and the residual .
- For each feature in turn: add its current contribution back to the residual, ; compute the new by the soft-threshold formula; subtract the new contribution, .
- If the largest change in any weight during the sweep is below the tolerance, stop; otherwise repeat step 2.
- Recover the intercept as for ridge.
One sweep costs , because keeping the residual up to date makes each coordinate update .
Implementation
fn fit(&mut self, x: VR2D, y: VR1D) -> Result<(), ErrorsJSL> {
check_xy(x, y.len())?;
let design = if self.fit_intercept { with_ones(x) } else { x.to_owned() };
let sol = design.least_squares(&y.to_owned()).map_err(|_| ErrorsJSL::RuntimeError("The least-squares solve failed."))?;
let coef: Array1<f64> = sol.solution;
if self.fit_intercept {
self.intercept = coef[coef.len() - 1];
self.weights = coef.slice(ndarray::s![..coef.len() - 1]).to_owned();
} else {
self.intercept = 0.0;
self.weights = coef;
}
self.fitted = true;
Ok(())
}
let (wd, wy): (R2D, R1D) = if let Some(cov) = &self.covariance {
if cov.dim() != (n, n) {
return Err(ErrorsJSL::IncompatibleArraySizes((cov.nrows(), n)));
}
let l = cov.cholesky(UPLO::Lower).map_err(|_| ErrorsJSL::InvalidInputRange("The covariance must be symmetric positive definite."))?;
let wd = l.solve_triangular(UPLO::Lower, lib_jsl_linalg::Diag::NonUnit, &design).map_err(|_| ErrorsJSL::RuntimeError("Whitening failed."))?;
let wy = l.solve_triangular(UPLO::Lower, lib_jsl_linalg::Diag::NonUnit, &y.to_owned()).map_err(|_| ErrorsJSL::RuntimeError("Whitening failed."))?;
(wd, wy)
} else {
let w = self.weights_per_sample.as_ref().ok_or(ErrorsJSL::Misconfiguration("No error model was given."))?;
if w.len() != n {
return Err(ErrorsJSL::IncompatibleArraySizes((w.len(), n)));
}
if w.iter().any(|&v| !v.is_finite() || v <= 0.0) {
return Err(ErrorsJSL::InvalidInputRange("Sample weights must be positive and finite."));
}
let s: Array1<f64> = w.mapv(f64::sqrt);
(R2D::from_shape_fn(design.dim(), |(i, j)| design[[i, j]] * s[i]), R1D::from_iter(y.iter().zip(&s).map(|(a, b)| a * b)))
};
fn fit(&mut self, x: VR2D, y: VR1D) -> Result<(), ErrorsJSL> {
check_xy(x, y.len())?;
if self.alpha.is_nan() || self.alpha < 0.0 {
return Err(ErrorsJSL::InvalidInputRange("The penalty alpha must be non-negative."));
}
let (x_mean, y_mean) = (column_means(x), y.sum() / y.len() as f64);
let xc = R2D::from_shape_fn(x.dim(), |(i, j)| x[[i, j]] - x_mean[j]);
let yc = y.mapv(|v| v - y_mean);
let mut gram: Array2<f64> = xc.t().dot(&xc);
for j in 0..gram.nrows() {
gram[[j, j]] += self.alpha;
}
self.weights = gram.solve(&xc.t().dot(&yc)).map_err(|_| ErrorsJSL::RuntimeError("Singular normal equations (try a larger alpha)."))?;
self.intercept = y_mean - x_mean.dot(&self.weights);
self.fitted = true;
Ok(())
}
for sweep in 1..=self.max_iterations {
let mut max_change: f64 = 0.0;
for j in 0..p {
if col_sq[j] == 0.0 {
continue;
}
// rho = (1/n) x_j · (resid + x_j w_j): the correlation with the partial residual.
let rho = xc[j].iter().zip(&resid).map(|(a, r)| a * r).sum::<f64>() / n as f64 + col_sq[j] * w[j];
let new = soft_threshold(rho, l1) / (col_sq[j] + l2);
let delta = new - w[j];
if delta != 0.0 {
resid.iter_mut().zip(&xc[j]).for_each(|(r, a)| *r -= a * delta);
w[j] = new;
}
max_change = max_change.max(delta.abs());
}
self.iterations = sweep;
if max_change < self.tolerance {
break;
}
}
- Ridge’s multiplies a sum of squares; the elastic net’s multiplies a mean (), as in scikit-learn, so the two scales differ by .
- Coordinate descent stops after
max_iterationssweeps without an error; checkiterations().
In practice
//! Linear regression with and without penalties on a problem with irrelevant, correlated features.
use lib_jsl_core::{R1D, R2D};
use lib_jsl_machine_learning::common::{MlRng, Regressor};
use lib_jsl_machine_learning::metrics::mean_squared_error;
use lib_jsl_machine_learning::supervised::regression::{ElasticNet, LinearRegression, Ridge};
fn data(n: usize, rng: &mut MlRng) -> (R2D, R1D) {
// Twenty features; only the first three matter, and feature 3 nearly copies feature 0.
let mut x = R2D::from_shape_fn((n, 20), |_| rng.gaussian(0.0, 1.0));
for i in 0..n {
x[[i, 3]] = x[[i, 0]] + 0.1 * x[[i, 3]];
}
let y = R1D::from_iter((0..n).map(|i| 3.0 * x[[i, 0]] - 2.0 * x[[i, 1]] + 1.5 * x[[i, 2]] + rng.gaussian(0.0, 1.0)));
(x, y)
}
fn main() {
let mut rng = MlRng::new(1);
let (x, y) = data(30, &mut rng);
let (x_test, y_test) = data(1000, &mut rng);
let models: Vec<(&str, Box<dyn Regressor>)> = vec![
("least squares", Box::new(LinearRegression::new())),
("ridge, α = 10", Box::new(Ridge::new(10.0))),
("lasso, α = 0.2", Box::new(ElasticNet::lasso(0.2))),
("elastic net, α = 0.2, ρ = 0.5", Box::new(ElasticNet::new(0.2, 0.5))),
];
for (name, mut model) in models {
model.fit(x.view(), y.view()).unwrap();
let mse = mean_squared_error(y_test.view(), model.predict(x_test.view()).unwrap().view()).unwrap();
println!("{name:<30} test MSE {mse:.3}");
}
let mut lasso = ElasticNet::lasso(0.2);
lasso.fit(x.view(), y.view()).unwrap();
let kept: Vec<String> = lasso.weights().iter().enumerate().filter(|(_, w)| **w != 0.0).map(|(j, w)| format!("w{j} = {w:+.2}")).collect();
println!("lasso keeps {} of 20 weights: {}", lasso.nonzero(), kept.join(", "));
}
least squares test MSE 4.001
ridge, α = 10 test MSE 2.068
lasso, α = 0.2 test MSE 1.352
elastic net, α = 0.2, ρ = 0.5 test MSE 1.417
lasso keeps 7 of 20 weights: w0 = +2.91, w1 = -2.47, w2 = +1.27, w4 = -0.13, w8 = -0.11, w14 = +0.01, w16 = +0.16
With 30 samples and 20 features, least squares has a test error four times the noise variance; the lasso finds the three real features, drops the near-copy , and comes closest to the noise level of 1.
Strengths
- Fast, deterministic and interpretable; SVD-based least squares handles collinearity.
- Penalties give stable predictions with many features, and the lasso selects them.
Weaknesses
- Linear in the features: curves need basis expansions chosen by hand.
- Squared error is sensitive to outliers (see support vector regression for an ε-insensitive loss).
- Penalties depend on feature scales; standardise first. The penalty strength must be chosen, typically by cross-validation.
Exercises
- Derive the normal equations by setting the gradient of to zero, and show that the residual is orthogonal to the columns of .
- Show that ridge regression is least squares on the data augmented with rows and zero targets.
- Derive the soft-threshold update of coordinate descent for the lasso from the subgradient of .
- Show that if the lasso solution is .
- Show that the generalised least-squares estimator has covariance , and that it is no larger than that of ordinary least squares.
Hints and answers
- gives , which says that the residual is orthogonal to every column of .
- is the squared norm of the stacked residual .
- For , with and , the subgradient condition gives .
- At the subgradient condition requires for every ; this is exactly the stated bound.
- The GLS estimator is with covariance . By the Gauss-Markov theorem applied to the whitened model it is the best linear unbiased estimator, so its covariance is no larger than OLS’s.
Further reading
- T. Hastie, R. Tibshirani and J. Friedman, The Elements of Statistical Learning, 2nd ed., Springer, 2009, chapter 3.
- R. Tibshirani, “Regression shrinkage and selection via the lasso”, Journal of the Royal Statistical Society B 58 (1996) 267–288.
- H. Zou and T. Hastie, “Regularization and variable selection via the elastic net”, Journal of the Royal Statistical Society B 67 (2005) 301–320.
- J. Friedman, T. Hastie and R. Tibshirani, “Regularization paths for generalized linear models via coordinate descent”, Journal of Statistical Software 33 (2010) 1–22.
- A. E. Hoerl and R. W. Kennard, “Ridge regression: biased estimation for nonorthogonal problems”, Technometrics 12 (1970) 55–67.