Score ridge penalties with the leave-one-out shortcut
Why it matters The leave-one-out shortcut is how ridge models with built-in cross-validation tune the penalty in one pass instead of n refits.
Leave-one-out cross-validation normally needs n refits, but for ridge regression there is an exact shortcut using the hat matrix.
Write ridge_loocv(X, y, lambdas). No intercept. For each lam, let H = X (X^T X + lam I)^-1 X^T and yhat = H y. The exact leave-one-out residual of point i is (y_i - yhat_i) / (1 - H_ii). Score lam by the mean of the squared LOO residuals. Return (scores, best_lam) where scores is a float list in the order of lambdas and best_lam is the lambda with the smallest score (first one on ties), as a float.
def ridge_loocv(X, y, lambdas)Example
X [[1, 0], [0, 1], [1, 1], [2, 1]], y [1, 2, 2, 4], lambdas [0.1, 1, 10] gives scores [0.768634, 1.083780, 3.625635] (rounded) and best_lam 0.1.
Understand the idea
Leave-one-out cross-validation trains on all points but one, predicts the held-out point, and repeats for every point. For n = 10,000 that is 10,000 model fits. Ridge regression has a neat shortcut: one fit is enough.
The hat matrix H turns y into predictions: yhat = H y. Its diagonal H_ii, the leverage, says how much point i pulls its own prediction toward itself. If we remove point i, its prediction loses that pull, and the exact held-out error is the ordinary error scaled up by 1 / (1 - H_ii).
Worked example: if a point has residual 0.3 and leverage 0.4, its leave-one-out residual is 0.3 / 0.6 = 0.5. A low leverage point with the same residual and H_ii = 0.1 gets 0.3 / 0.9 = 0.33.
Rule: e_loo_i = (y_i - yhat_i) / (1 - H_ii), score = mean(e_loo^2).
Plain training error always prefers the smallest penalty. The LOO score instead finds the penalty that predicts unseen points best, which is how built-in ridge cross-validation works.
Shapes and data flow
X (n, d) -> H (n, n) -> diag(H) (n,) -> LOO residuals (n,)