Tutorials › Regression Analysis (Undergraduate) › Cross-Validation for Penalized Regression

Ridge and Lasso Regression · Tutorial 678 of 991

Cross-Validation for Penalized Regression

Build a fold-based cross-validation procedure that compares ridge or lasso penalties by their average held-out prediction error.

Advanced 10 min read

What You'll Learn

  • Define K-fold cross-validation for penalized regression
  • Fit ridge or lasso models across a fixed lambda grid
  • Calculate pooled held-out mean squared error
  • Understand why each observation receives an out-of-fold prediction
  • Select the lambda with the smallest cross-validation score
  • Recognize common pitfalls in fold assignment and score calculation

Why Cross-Validate a Penalty?

Ridge and lasso regression use a penalty parameter, \(\lambda\), to control how strongly coefficient estimates are shrunk. A small penalty allows a closer fit to the training data; a larger penalty imposes more shrinkage. The question is not simply which value fits the observed data most closely, because a model can fit its training data well and still predict new observations poorly. Cross-validation compares candidate penalties by repeatedly evaluating predictions on observations that were not used to fit the corresponding model.

The central idea is to divide the available observations into folds. Each fold takes a turn as a temporary test set, while the remaining folds form the training set. For every candidate \(\lambda\), fit the penalized model on each training set and predict the observations in its held-out fold. Combine the held-out errors to obtain a cross-validation score for that penalty.

Definition: In \(K\)-fold cross-validation, the \(n\) observed cases are partitioned into \(K\) nonempty, mutually exclusive folds. For each fold, a model is fitted using the other \(K-1\) folds and evaluated on that held-out fold. A cross-validation score summarizes prediction error across the held-out predictions from all folds.

The Model and the Cross-Validation Score

Suppose the response is quantitative and there are \(p\) predictors. For a given training set and candidate value \(\lambda\), ridge or lasso fits a penalized regression model. With an unpenalized intercept and the common sum-of-squares convention, the objectives can be written as

$$ \text{Ridge:}\quad \sum_{i\in\mathcal{T}}(y_i-\beta_0-\mathbf{x}_i^\mathsf{T}\boldsymbol{\beta})^2 +\lambda\sum_{j=1}^p\beta_j^2, \qquad \text{Lasso:}\quad \sum_{i\in\mathcal{T}}(y_i-\beta_0-\mathbf{x}_i^\mathsf{T}\boldsymbol{\beta})^2 +\lambda\sum_{j=1}^p|\beta_j|. $$

Here \(\mathcal{T}\) denotes the training cases for a particular fold, \(y_i\) is the response, and \(\mathbf{x}_i\) is the predictor vector. The intercept is not included in either penalty. The exact scale used for the loss can vary across definitions and software, so a value of \(\lambda\) has meaning only with its stated objective convention. Within one analysis, use the same convention for all folds and candidate values.

Let \(k(i)\) be the fold containing case \(i\). For each candidate \(\lambda\), let \(\hat{y}_{i,-k(i)}(\lambda)\) be the prediction for case \(i\) from the model fitted without that case's fold. With squared-error loss, the pooled cross-validation score is

$$ \operatorname{CV}(\lambda) = \frac{1}{n}\sum_{i=1}^n \left(y_i-\hat{y}_{i,-k(i)}(\lambda)\right)^2. $$

The score is a mean squared prediction error in squared response units. A smaller score indicates lower average squared error on these held-out cases. When all folds have equal size, this pooled score is also the simple average of the \(K\) fold-specific mean squared errors. If fold sizes differ, pooling by observations weights each fold according to its number of held-out cases.

Constructing the Procedure

Choose a set of candidate penalties, often called a lambda grid, before comparing their cross-validation scores. The grid should span values that produce meaningfully different amounts of shrinkage. Use the same fold assignment for every candidate \(\lambda\), so differences between scores are not obscured by changing which observations are held out.

1
Set up the folds and grid.
Partition the observations into \(K\) folds and specify the candidate \(\lambda\) values. The fold structure should match the way observations can reasonably be treated as independent cases; for example, repeated observations from one person should not automatically be split across training and held-out folds.
2
Fit within each training fold.
For every fold and every candidate value, fit the chosen ridge or lasso model using only the other \(K-1\) folds. Any quantities needed to fit or transform the predictors, such as scaling constants, must be determined from that training portion.
3
Predict the held-out cases.
Use the fitted model to predict the responses for every observation in the omitted fold. Record each held-out prediction with its observed response.
4
Aggregate and compare.
For each \(\lambda\), calculate the pooled mean squared error from all out-of-fold predictions. Select the candidate with the smallest cross-validation score if the goal is to minimize this squared prediction error.

The key restriction is that a held-out response cannot help fit the model that predicts it. This is what makes the error a held-out error rather than a training error. Cross-validation does not guarantee that the chosen penalty will be best on every future data set; it provides a data-based estimate for comparing candidate penalties under the conditions represented by the folds.

Worked Example: Comparing Two Penalties From Held-Out Errors

Suppose six hypothetical observations have already been assigned to folds and each has received an out-of-fold prediction for two ridge fits. For \(\lambda=0.1\), the held-out residuals (observed response minus prediction) are \(1,-1,2,0,-1,1\). For \(\lambda=0.5\), suppose they are \(1.5,-0.5,2,0,-1.5,0.5\). Calculate the cross-validation score for each candidate.

For \(\lambda=0.1\), the sum of squared held-out residuals is

$$ 1^2+(-1)^2+2^2+0^2+(-1)^2+1^2 =1+1+4+0+1+1=8. $$

There are six observations, so

$$ \operatorname{CV}(0.1)=\frac{8}{6}=\frac{4}{3}\approx 1.333. $$

For \(\lambda=0.5\), the sum is

$$ 1.5^2+(-0.5)^2+2^2+0^2+(-1.5)^2+0.5^2 =2.25+0.25+4+0+2.25+0.25=9, $$

giving \(\operatorname{CV}(0.5)=9/6=1.500\). Since \(1.333<1.500\), the \(\lambda=0.1\) fit has the smaller cross-validation mean squared error among these two candidates. The comparison concerns predictive error under this fold scheme, not which fit has coefficients closer to some unknown true coefficients.

Why the Pooled Score Has This Form

Each observation belongs to exactly one held-out fold. It therefore contributes exactly one out-of-fold squared error for a particular \(\lambda\). The pooled score is the arithmetic mean of these \(n\) errors, rather than the error from a model trained on all \(n\) observations.

To see how this relates to fold-specific scores, let \(n_k\) be the number of cases in fold \(k\), and let \(\operatorname{MSE}_k(\lambda)\) be the mean squared error among that fold's held-out predictions. The sum of squared errors in fold \(k\) is \(n_k\operatorname{MSE}_k(\lambda)\). Summing across folds and dividing by \(n\) gives

$$ \operatorname{CV}(\lambda) = \frac{\sum_{k=1}^K n_k\operatorname{MSE}_k(\lambda)}{n}. $$

When \(n_k=n/K\) for every fold, this becomes the unweighted average of the fold-specific mean squared errors. When fold sizes differ, the expression weights each fold by its number of observations. This distinction prevents a small fold from counting as much as a large fold merely because both are one fold.

The fold fits also explain why this procedure is computationally repeated: with \(G\) candidate penalties and \(K\) folds, it requires \(G K\) model fits for a given method, apart from any additional refit after tuning. Ridge and lasso can each be evaluated this way. The same folds and loss allow a consistent comparison of candidate penalties within a method; comparing different model families may require separate care about the analysis goal and fitting conventions.

Worked Example: A Complete Three-Fold Ridge Calculation

Consider hypothetical observations \((x,y)=(0,1),(1,3),(2,4)\), with one predictor and an intercept. Use leave-one-out cross-validation, which is \(K=3\) here, and evaluate ridge with \(\lambda=0.5\). For a training set, the ridge slope with centered predictor is

$$ \hat{\beta}_1(\lambda)=\frac{S_{xy}}{S_{xx}+\lambda}, \qquad \hat{\beta}_0=\bar{y}-\hat{\beta}_1\bar{x}, $$

where \(S_{xx}=\sum (x_i-\bar{x})^2\) and \(S_{xy}=\sum (x_i-\bar{x})(y_i-\bar{y})\), calculated on that training set. This slope formula follows by minimizing the centered ridge objective \(\sum[(y_i-\bar y)-b(x_i-\bar x)]^2+\lambda b^2\): differentiating with respect to \(b\) gives \(-2S_{xy}+2b(S_{xx}+\lambda)=0\), and hence the displayed result.

Hold out \((0,1)\). The training observations are \((1,3)\) and \((2,4)\). They have \(\bar{x}=1.5\), \(\bar{y}=3.5\), \(S_{xx}=0.5\), and \(S_{xy}=0.5\). Thus \(\hat{\beta}_1=0.5/(0.5+0.5)=0.5\), and \(\hat{\beta}_0=3.5-(0.5)(1.5)=2.75\). The prediction at \(x=0\) is \(2.75\), so the squared error is \((1-2.75)^2=3.0625\).

Hold out \((1,3)\). The training observations are \((0,1)\) and \((2,4)\). Here \(\bar{x}=1\), \(\bar{y}=2.5\), \(S_{xx}=2\), and \(S_{xy}=3\). Therefore \(\hat{\beta}_1=3/(2+0.5)=1.2\) and \(\hat{\beta}_0=2.5-(1.2)(1)=1.3\). The prediction at \(x=1\) is \(2.5\), giving squared error \((3-2.5)^2=0.25\).

Hold out \((2,4)\). The training observations are \((0,1)\) and \((1,3)\). Their means are \(\bar{x}=0.5\) and \(\bar{y}=2\). In particular, \(S_{xx}=0.5\) and \(S_{xy}=1\), since

$$ S_{xy}=(0-0.5)(1-2)+(1-0.5)(3-2)=0.5+0.5=1. $$

It follows that \(\hat{\beta}_1=1/(0.5+0.5)=1\) and \(\hat{\beta}_0=2-(1)(0.5)=1.5\). The prediction at \(x=2\) is \(3.5\), and the squared error is \((4-3.5)^2=0.25\). The three held-out errors therefore give

$$ \operatorname{CV}(0.5) =\frac{3.0625+0.25+0.25}{3} =\frac{3.5625}{3} =1.1875. $$

This score is in squared response units. Each fit used only two observations, and each case was evaluated only in the fold where it was held out.

Worked Example: Correcting for Unequal Fold Scores

Suppose four hypothetical held-out observations produce residuals \(5/3,1,3/2,31/6\) at \(\lambda=1\). The observed responses and corresponding out-of-fold predictions could be \(5\) and \(10/3\), \(4\) and \(3\), \(6\) and \(9/2\), and \(8\) and \(17/6\), respectively. In particular, the final residual is \(8-17/6=48/6-17/6=31/6\).

The pooled score is

$$ \operatorname{CV}(1) = \frac{25/9+1+9/4+961/36}{4} = \frac{100/36+36/36+81/36+961/36}{4} = \frac{1178}{144} = \frac{589}{72} \approx 8.181. $$

If the first two errors belonged to one fold and the last two to another, the fold sizes would be equal, so averaging the two fold MSEs would give the same result. The arithmetic also illustrates why residuals should be checked before squaring: the last squared error is \((31/6)^2=961/36\), not \(841/36\).

Common Mistakes and Practical Checks

  • Using training error to choose \(\lambda\). Training error evaluates observations used to fit the model and can favor overly flexible fits. Use the out-of-fold predictions for the cross-validation score.
  • Forgetting that a residual must be squared. The score above is mean squared error, not mean absolute error and not the average signed residual. Check each residual and its square before adding.
  • Averaging fold scores equally when fold sizes differ. The pooled observation-level score weights folds by size. An unweighted mean of fold scores is equivalent only when fold sizes are equal, or when equal fold weighting is the explicitly intended target.
  • Changing the folds for every candidate penalty. Use the same fold assignment across the grid to make comparisons less affected by random differences in held-out cases.
  • Treating the minimizing grid value as an exact optimum. The selected value is the best among the candidates evaluated under the chosen folds and loss. It need not be the best possible value over a continuous range or the best value for every future sample.

Cross-validation matters because penalization is intended to manage the balance between fitting the observed cases and predicting new ones. A carefully calculated held-out score gives a direct, interpretable comparison of that balance across ridge or lasso penalty values. The conclusion should remain tied to the chosen loss, folds, and candidate grid.

Check Your Understanding

Answer each question using the definitions and calculations above.

  1. In five-fold cross-validation, how many observations are held out in each fit, and what data are used to fit that model?
  2. For residuals \(-2,1,0\) across three held-out observations, calculate the pooled mean squared error.
  3. Why should the same fold assignment generally be used for every candidate \(\lambda\) in a grid?
  4. If fold sizes are unequal, how does the pooled cross-validation score weight the fold-specific mean squared errors?
  5. A candidate \(\lambda\) has the smallest cross-validation score among those tested. What does this support, and what does it not establish?