Motivation
Least squares answers a question about a fixed feature matrix: which coefficients minimize the residual sum of squares? Choosing the features is a further question. A polynomial of sufficiently high degree can interpolate observations at distinct inputs, yet interpolation alone does not determine how accurately it predicts another response. Training residuals describe agreement with observations that helped choose the coefficients.
Model validation examines predictions at observations withheld from fitting. It makes the distinction between estimating coefficients and selecting a model operational: the training set determines a fitted function, while a validation set compares candidate feature choices or penalty strengths. After selection, the chosen procedure can be fitted again using all development data. A separate final test set evaluates that selected procedure without participating in the choice.
Ridge regression introduces another choice. It balances squared residuals against the squared size of the coefficients. Understanding this balance requires stating the loss scale, which coefficients are penalized, and how the features are measured. Cross-validation then compares these choices through prediction error rather than through the penalized training objective itself.
There is a simple reason why training error cannot settle the model choice. Suppose a new feature matrix contains every column of an old one together with additional columns. Every old coefficient vector extends to a new vector by assigning zero to the added coefficients, producing exactly the old predictions. Minimizing over the larger collection can therefore only decrease or preserve training SSE. The improvement could reflect a useful pattern, or it could absorb fluctuations specific to these observations. The training optimization has no withheld responses with which to distinguish those possibilities. Validation supplies a separate prediction comparison after the optimization has finished.
Definitions
Let and be disjoint, nonempty sets of training and validation indices. A model fitted using is denoted . For squared error, define
The same fitted function occurs in both expressions. Computing validation loss does not refit its coefficients using the validation responses. A candidate model includes the feature construction, preprocessing, and fitting rule, so these parts must also be learned within each training split.
Measuring prediction error
For an evaluation set of size , write . Three common metrics are
MSE has squared response units; MAE and RMSE have response units. Squaring gives large residuals more influence, whereas absolute loss grows linearly with their magnitude. RMSE and MSE rank predictions identically on the same evaluation set because the square root is increasing. MAE may give a different ranking. Choose the metric to express the prediction task before comparing candidates.
With the evaluation-set mean , define
Here the baseline always predicts that evaluation-set mean. Negative means the candidate has larger squared error than this baseline. On training data, ordinary least squares in a model containing a free constant has : the constant predictor is among its competitors. That comparison does not apply to held-out predictions. When all evaluation responses coincide, SST is zero and this definition has no value; MSE remains available. In particular, a one-observation validation fold cannot supply this .
To justify the training bound, evaluate the least-squares objective at the response mean. Its SSE equals SST, so the minimizing SSE lies between zero and SST. Division by positive SST gives the bound. This argument uses the same observations for fitting and computing the two sums. A validation response mean is a comparison baseline, not a coefficient estimated from the training subset. Also, averaging fold RMSEs and taking the square root of pooled MSE generally differ: the square root is applied at different stages of the calculation.
Median and percentage errors
Two further summaries use the middle of the error distribution:
For an even sample size, average the two middle ordered values. MdSE has squared response units; MdAE has response units. Means reflect the average error across all observations, while medians describe its middle magnitude. The two summaries can therefore distinguish different features of a residual distribution.
For and predictions , residuals are . MSE is and MdSE is ; MAE is and MdAE is . The mean absolute percentage error is
MAPE expresses relative error as a percentage. All four observed responses above are nonzero, and their absolute relative errors are , giving . This definition requires every observed response to be nonzero.
Learning a feature scale
For a nonconstant training feature, its training mean and population standard deviation give
Use the same and when transforming validation inputs. Training min-max scaling similarly uses training extrema and requires a positive training range. A constant feature can be removed before standardization; the intercept already represents a constant contribution. A future transformed value can lie outside the training interval. Its location records a new input, rather than an error in the transformation.
For and , the fully penalized ridge objective in this section is
This uses the unnormalized sum of squared errors. An objective has the same minimizer when . If the penalty is written , then . These parameters are numerical descriptions of the chosen objective, so their normalization belongs with the reported value.
Theorem/proposition
Proposition
A unique ridge fit at every positive penalty
For every real and and every , is positive definite. The unique minimizer of is characterized by
This conclusion includes rank-deficient design matrices. Positive definiteness provides both existence and uniqueness of the coefficient vector.
Proposition
The training tradeoff as the penalty increases
Fix and , and let . Define
Then and . A larger penalty reduces or preserves the coefficient norm and increases or preserves the training residual sum of squares. The inequalities make no ordering claim about validation error.
Proof sketch or proof idea
For any nonzero vector ,
Differentiation of gives . Its unique zero solves the displayed linear system. More directly, expansion around this solution yields
Every nonzero change therefore increases the objective. This argument proves a global minimum, including when ordinary least squares has several coefficient solutions.
The same ridge problem is an ordinary least-squares problem on augmented observations:
The additional rows contribute exactly the coefficient penalty. More generally, replacing by a matrix gives a Tikhonov penalty . Its minimizer is unique precisely when the only vector annihilated by both and is zero. Indeed, the corresponding quadratic form is . This criterion explains why leaving an intercept unpenalized can still give a unique fit: the data matrix observes the constant direction even though the penalty does not constrain it.
For the second proposition, optimality at the two penalty values gives
Adding yields , so . The first inequality then implies .
The spectrum explains which directions shrink. If for orthonormal eigenvectors and , then
Here is the minimum-norm ordinary least-squares solution. A zero-eigenvalue direction has , hence and ridge coefficient zero in that direction. Small positive receive stronger relative shrinkage. This is a statement about orthogonal spectral coordinates; an individual coefficient in the original feature coordinates need not move monotonically toward zero.
Ridge with a coefficient-norm budget
The same fitting preference can be expressed through a constraint. Write and consider
This is a ball of radius . For a positive penalty, let . Any vector satisfying that budget obeys
Canceling the penalty bound shows that the ridge vector minimizes the constrained loss. This construction links the selected penalty to its budget through the fitted coefficient norm.
Conversely, take . The zero vector is strictly feasible, so the convex differentiable problem satisfies Slater's condition. Its Karush–Kuhn–Tucker (KKT) conditions are necessary and sufficient:
Here the Lagrangian is . Dividing its stationarity equation by two gives the displayed first line, with the same SSE penalty convention used above. Convexity makes a stationary point minimize the Lagrangian. Feasibility and complementary slackness then certify the constrained minimum. A positive multiplier gives the unique ridge vector; at a zero multiplier the stationarity equation is ordinary least squares, whose coefficients need not be unique.
A slack norm constraint forces . A constraint holding with equality can also have zero multiplier when an ordinary least-squares minimizer lies on the boundary. Positive multipliers therefore do not describe every possible budget. At , strict feasibility fails and the only feasible vector is zero; a finite ridge penalty need not reach it. If the intercept is unpenalized, constrain only the slope vector and leave the intercept free.
For a scalar example, take and . Then
The constrained solution projects onto . Budget gives and . Budget gives on the boundary with ; budget gives the same coefficient strictly inside the ball, again with zero multiplier. Budget forces , while for every finite . In this example, the zero budget is attained only in the limit .
Worked examples
Worked example
Example 1: transform a withheld input with the training scale
Suppose one training feature takes values and , and a validation input is . The training mean is and population standard deviation is , so the training standardized values are and ; the validation standardized value is .
Training min-max scaling instead gives , , and validation value . Both procedures reuse their training parameters. Recomputing the mean or range after inserting the validation input changes the transformation used to define the fitted model. It lets the held-out observations influence a stage of fitting before their prediction errors are measured.
If another cross-validation fold has different training observations, recompute its scale from those observations. The preprocessing belongs to the fitting procedure, rather than to a single preliminary pass over the complete data.
Worked example
Example 2: a constant model under leave-one-out validation
Fit a constant to responses , , and . Using all three gives , residual sum of squares , and training MSE .
For leave-one-out cross-validation, refit the constant three times. Holding out leaves training mean ; holding out leaves mean ; holding out leaves mean . Thus
Each held-out prediction was obtained without that response. Using the full-data mean for all three predictions would reproduce the training MSE, not leave-one-out error. The calculation compares a full-data fit with three fits using two observations; their difference is visible even for a model with just one coefficient.
Worked example
Example 3: ridge separates residual error from coefficient size
Take , , and , with both coefficients penalized. Then
The predictions are and residuals . Therefore
Ordinary least squares gives , with zero residual error and squared coefficient norm . Its value in the same objective is , exceeding . Ridge accepts residual error to reduce the combined objective. The two spectral shrinkage factors are and , matching the two coefficients above.
These two computations can be reproduced directly:
import numpy as np
y = np.array([0.0, 2.0, 4.0])
held_predictions = np.array([
np.delete(y, i).mean() for i in range(len(y))
])
train_mse = np.mean((y - y.mean()) ** 2)
loo_mse = np.mean((y - held_predictions) ** 2)
A = np.diag([1.0, 2.0])
target = np.array([2.0, 2.0])
beta = np.linalg.solve(A.T @ A + np.eye(2), A.T @ target)
residual = target - A @ beta
objective = residual @ residual + beta @ beta
print(train_mse, loo_mse, beta, objective)
The outputs are approximately , , , and . Solving the positive definite system avoids explicitly computing its inverse.
Choosing a model with cross-validation
For , leave-one-out validation trains on all but one observation and averages the squared held-out errors. Leave--out, with , considers every validation subset of size , requiring fits per candidate. In -fold validation, with , partition observations into disjoint nonempty blocks; each block is withheld once. When , this is leave-one-out validation.
For unequal fold sizes, pool squared errors and divide by the total number of held-out observations to weight observations equally. Averaging fold MSEs equally instead weights folds equally. Repeated random holdout, or Monte Carlo cross-validation, samples several training-validation partitions. Within each split the sets are disjoint, while an observation may be validated repeatedly across splits or never be selected. Use the same splits for all candidate penalties to make their comparisons refer to the same prediction tasks.
The code below uses three fixed folds, one nonconstant feature, and an unpenalized intercept. Its penalty matrix gives objective . Every training subset contains varying feature values, so each computed standard deviation is positive.
import numpy as np
X = np.arange(6.0)[:, None]
y = np.array([1.0, 2.0, 2.0, 4.0, 4.0, 5.0])
folds = [np.array([0, 1]), np.array([2, 3]), np.array([4, 5])]
indices = np.arange(len(y))
penalty = np.diag([0.0, 1.0])
for lam in (0.0, 1.0, 4.0):
squared_error = 0.0
count = 0
for valid in folds:
train = np.setdiff1d(indices, valid)
mu = X[train].mean(axis=0)
scale = X[train].std(axis=0, ddof=0)
Z_train = (X[train] - mu) / scale
Z_valid = (X[valid] - mu) / scale
A = np.column_stack((np.ones(len(train)), Z_train))
B = np.column_stack((np.ones(len(valid)), Z_valid))
beta = np.linalg.solve(A.T @ A + lam * penalty, A.T @ y[train])
error = y[valid] - B @ beta
squared_error += error @ error
count += len(valid)
print(lam, squared_error / count)
For , the pooled MSEs are approximately , , and , respectively. Thus wins among these three candidates. Select the candidate with the smallest pooled validation MSE, then learn a fresh scale and fit using all development observations. The intercept is free to represent the response level. With positive , the only unpenalized direction here is the intercept, whose nonzero constant column ensures uniqueness. The earlier theorem penalizes every coefficient; changing the penalty matrix changes that stated problem.
If the candidate is instead defined by a mean-loss penalty strength , use inside each training split. Training subsets of different sizes then implement the same mean-loss convention. Keeping the numerical SSE parameter fixed implements a different comparison. Once candidates have been compared repeatedly against validation observations, those observations have helped select the procedure. Refitting the selected procedure on the full development set uses that information constructively; a final test set answers the subsequent evaluation question. A fixed split makes a numerical comparison reproducible, while several chosen splits reveal how strongly the comparison depends on which observations were withheld.
Feature scaling also changes the penalty. If and the standardized coefficient is , the raw slope is . Penalizing therefore penalizes in raw coordinates. Standardization gives a chosen, consistent unit of comparison; it is part of the model definition. Sensitivity can then be explored by perturbing a feature or penalty and recomputing predictions while keeping other choices fixed.
Sensitivity to input changes
Fixed-model sensitivity changes inputs while keeping fitted parameters fixed. Refitting after changing training observations also changes the model itself; its resulting predictions measure a different form of stability.
One-at-a-time (OAT) analysis changes one input while fixing the others. For the fixed interaction model at ,
Neither individual perturbation changes the output, but the joint perturbation does. Unchanged OAT outputs therefore do not establish joint insensitivity. Multivariable analysis examines interactions; scenario analysis specifies joint changes, while Monte Carlo sensitivity samples joint inputs from a specified distribution.
Common mistakes
Common mistake
Compare prediction error after the complete fitting procedure
Training SSE generally favors more flexible models and weaker penalties. Validation compares predictions after fitting and preprocessing on each training subset. The ridge objective includes a coefficient penalty, so its numerical value is not a validation MSE. Increasing guarantees the training tradeoff proved above, while the location of the best validation error depends on the data.
Summary
Define the evaluation metric, split observations, learn preprocessing on the training subset, and fit each candidate there. Pool held-out errors to compare candidates. For ridge, record the loss normalization and intercept convention with the penalty value; positive full-coefficient regularization gives a unique solution and shrinks spectral directions according to their eigenvalues.
Exercises
Checkpoint
Exercise 1: training feature values are and . Standardize a validation input using the population standard deviation. What are the three transformed values?
Compute the mean and standard deviation using the two training values.
Checkpoint
Exercise 2: evaluation responses are and , with predictions and . Find MSE, MAE, RMSE, and .
Use the evaluation-set mean in SST and retain the sign of .
Checkpoint
Exercise 3: let , , and . Penalize both coefficients. Find the unique ridge coefficient vector.
Form even though the two columns of coincide.
Checkpoint
Exercise 4: a training set has and objective . What is the equivalent in the unnormalized SSE convention?
Multiply the entire objective by .
Checkpoint
Exercise 5: For , , and budget , find the ball radius, constrained minimizer, and corresponding SSE ridge parameter.
Project the unconstrained coefficient onto the ball, then solve for the penalty.
Solutions
Solution · Exercise 1 solution
The training mean is and population standard deviation is . Thus , , and . The validation input does not change the scale parameters.
Solution · Exercise 2 solution
The residuals are and , so SSE is , MSE is , MAE is , and RMSE is . The response mean is and SST is , giving . The negative value expresses performance below the constant-mean baseline on these observations.
Solution · Exercise 3 solution
The system is
Subtracting the two equations gives , and either equation then gives . The matrix has eigenvalues and , both positive. The duplicate original columns do not prevent the ridge solution from being unique.
Solution · Exercise 4 solution
Multiplying by gives , so . Multiplication by a positive constant preserves minimizers; rescaling only the residual term would change their tradeoff.
Solution · Exercise 5 solution
The radius is , so . Solving gives . Stationarity is , and the positive multiplier matches the binding budget.
Related notes
Least squares and residuals develops the fitting equations used here. Lasso and matching pursuit studies penalties and algorithms that select sparse coefficients. SVD and principal components explains the spectral directions behind shrinkage. The course reading list collects further reading.