Concepts and worked examples

Validation and generalization

Test models fairly, avoid data leakage, and check how they handle new data.

Generalization is the goal

A model learns from historical examples but earns its value on new cases. Generalization means useful performance on the population and prediction horizon that actually matter. Overfitting means adapting to accidental training patterns rather than transferable structure. A tree can memorize records through tiny leaves; a linear model can overfit with many predictors, interactions, or repeated feature searches. Neither a straight decision boundary nor impressive training accuracy guarantees generalization.

Under squared-error regression, the expected prediction error at a fixed input decomposes as bias² + variance + irreducible noise. Bias measures systematic deviation of the average fitted predictor from the true conditional mean. Variance measures sensitivity to the sampled training set. Noise is the conditional variability of the outcome even with the available predictors known. This decomposition averages over hypothetical training sets and new outcomes; it is not an exact identity for accuracy or log loss. Greater complexity often reduces bias and increases variance, but this is a tendency, not a universal law.

Read the right curve

A fitting or validation curve plots training and validation performance against model complexity, such as tree depth or inverse regularization strength. A learning curve plots performance against training-set size while holding the learning procedure fixed. A large training–validation gap can suggest variance; poor performance on both can suggest excessive bias, weak features, or difficult labels. More data may close a variance gap but cannot automatically repair missing signal, distribution shift, or an unsuitable objective.

Limit tree depth, require minimum leaf sizes, or stop splitting when improvements are too small. Post-pruning replaces a subtree with a leaf, trading fit against complexity; cost-complexity pruning selects a penalty using validation rather than demanding unchanged training accuracy. Early stopping in iterative models selects an iteration using held-out performance and patience. The selected iteration is a tuned parameter, so its validation score is not an untouched final estimate.

Penalized objectives

Regularization balances empirical fit and constrained complexity. A common objective is J(w, b) = (1/n) Σᵢ ℓ(yᵢ, f(xᵢ)) + λΩ(w), with λ ≥ 0. The intercept is usually unpenalized. Ridge regression uses squared loss and Ω(w) = Σⱼ wⱼ²; lasso uses Ω(w) = Σⱼ |wⱼ|. Ridge generally shrinks coefficients without making them exactly zero. Lasso can select features by setting coefficients to zero, but selection can be unstable among correlated predictors.

For binary labels y ∈ {−1, +1}, hinge loss is max(0, 1 − yf(x)); a linear support-vector classifier commonly combines it with L2 regularization. For labels y ∈ {0, 1}, logistic log loss is −[y ln p + (1 − y) ln(1 − p)], where p = 1/(1 + exp(−f(x))). Regularized logistic regression minimizes negative log likelihood plus a penalty, not raw likelihood plus a penalty. Hinge scores are not automatically probabilities.

Worked comparison: two models have mean losses 0.20 and 0.24, and squared coefficient norms 9 and 1. At λ = 0.01 their objectives are 0.29 and 0.25, so the second wins despite worse training fit. At λ = 0.001 the objectives become 0.209 and 0.241. In many SVM and logistic APIs, C controls inverse regularization: larger C weakens the penalty. Exact λ–C conversion depends on loss averaging and implementation; do not assume C literally equals 1/λ everywhere. Standardize predictors using training statistics because penalties depend on feature scale.

Split according to deployment

Use training data to fit parameters, validation data to select features and hyperparameters, and a test set to estimate the frozen procedure. Standard shuffled k-fold cross-validation fits on k − 1 folds and validates on the remaining fold, rotating through folds. Each record is held out once in ordinary k-fold, not necessarily in every CV design. Stratification can stabilize class proportions but does not prevent dependence leakage.

Use grouped folds when multiple rows belong to a patient, customer, household, or site that must be unseen at deployment. Use forward temporal validation when predicting the future; training must precede validation, with gaps or purging when feature or label windows overlap. Preserve both constraints when groups and time interact. Random splitting cannot simulate a future regime merely by increasing the number of folds.

Nested CV evaluates selection itself: tune candidates inside each outer training fold, refit the chosen pipeline on that outer training fold, and score once on its outer holdout. Five outer folds and four inner folds with six candidates require 5 × 4 × 6 = 120 inner fits, plus five outer refits. Fold scores share training observations; their standard deviation describes variation across folds, not automatically an independent-sample confidence interval.

Keep all learning inside the boundary

Sequential forward selection starts with no predictors, evaluates each possible first feature, keeps the best, and repeatedly adds the best remaining feature. Its search and stopping rule belong inside the training portion of each validation split. Choosing a feature subset on all data and then cross-validating only the estimator leaks selection information. A pipeline should similarly fit imputers, scalers, vocabularies, encoders, PCA, and resampling only on each training fold.

Leakage includes target information unavailable at prediction time, preprocessing learned from held-out records, and the same entity appearing across inappropriate splits. A future cancellation code is target leakage; scaling before splitting is preprocessing leakage; repeated patient visits crossing folds can be group leakage. Audit timestamps, join logic, duplicates, label construction, and the precise decision moment. After tuning, refit on allowed development data and evaluate the locked test once. If test feedback changes the model, that set has become development data; obtain new independent evidence.

Question: Does nested CV mean tuning on the outer holdout?

No. Inner folds select the procedure using only outer training data. The outer holdout estimates how that selection procedure generalizes. Final deployment tuning can use all development data, but cannot reuse the final test as feedback.

Question: What would you investigate before adding complexity?

Compare training and validation curves, inspect labels and leakage, check split realism and subgroup errors, and compare a simple baseline. A performance gap may come from distribution shift rather than insufficient model capacity.

Continue with distance-based models and decision-focused evaluation.

Definition

View in glossary →