Generalization and validation
Generalization is performance on new examples
A useful model must perform acceptably on examples not used to fit or tune it. Training error describes the fitted sample; validation error estimates performance on an unseen partition under a stated split design. A model with training accuracy 0.99 and validation accuracy 0.63 has a large gap, a warning sign for overfitting. It does not prove the cause: a shift in customer mix, leakage or noisy labels may also produce the gap. A model with both scores low may be underfitting or facing an unlearnable target, poor features or measurement error. Compare to a simple baseline and examine the data before increasing model complexity. Bias here refers to systematic approximation error, not social bias; variance refers to sensitivity to the training sample.
Cross-validation by hand and in Python
K-fold cross-validation divides development data into k disjoint validation subsets. Each fold trains a fresh model on the other subsets. The code below uses round-robin indices i modulo k and fits a mean-only regression baseline on each complement. With values [2,4,6,8,10,12] and three folds, fold 0 validates [2,8] using a training mean of 8; fold 1 validates [4,10] using mean 7; fold 2 validates [6,12] using mean 6. All three mean absolute errors are 3. The equal-weight fold mean is 3. With unequal fold sizes, an equal-weight fold average differs from a per-record pooled MAE; report the chosen aggregation. Round-robin is a fixed illustrative split for independent records, not recommended for time series or repeated entities. Choose chronological, grouped or stratified splits as appropriate. Do not use the final test set as a fold.
def mean_baseline_cv(values, folds): n = len(values) if not 2 <= folds <= n: raise ValueError("Need between 2 and n folds") errors = [] for f in range(folds): train = [v for i, v in enumerate(values) if i % folds != f] valid = [v for i, v in enumerate(values) if i % folds == f] prediction = sum(train) / len(train) errors.append(sum(abs(v - prediction) for v in valid) / len(valid)) return errors
scores = mean_baseline_cv([2, 4, 6, 8, 10, 12], 3)print(scores)print(sum(scores) / len(scores))Regularization limits model flexibility
Regularization adds a preference or constraint that discourages overly complex solutions. In a one-feature centered linear regression with no intercept needed, minimize sum((y−wx)²) + lambdaw². Differentiating with respect to w gives w = sum(x*y)/(sum(x²)+lambda), for a positive denominator. For x=[−1,1], y=[−4,4], the numerator is 8 and sum(x²)=2. With lambda 0 the slope is 4, with lambda 2 it is 2, and with lambda 6 it is 1. The penalty shrinks the coefficient toward zero without choosing a better model automatically. This is an exact scalar ridge objective with an unnormalized squared-error sum, not a claim about every library’s alpha convention. The toy function accepts centered integer sequences and a nonnegative penalty. If all x are zero and the penalty is zero, every slope minimizes the objective; it rejects the nonunique case. With positive penalty, zero is uniquely optimal. L1 penalties can favor exact zero coefficients; their general solution differs. Scaling can change the practical effect of coefficient penalties.
def ridge_centered_slope(xs, ys, penalty): if len(xs) != len(ys) or not xs or penalty < 0: raise ValueError("Need paired data and nonnegative penalty") if sum(xs) != 0 or sum(ys) != 0: raise ValueError("This example requires centered integer data") denominator = sum(x*x for x in xs) + penalty if denominator == 0: raise ValueError("Slope is not uniquely determined") return sum(x*y for x, y in zip(xs, ys)) / denominator
for penalty in (0, 2, 6): print(ridge_centered_slope([-1, 1], [-4, 4], penalty))Diagnose fit and choose a model
Consider fictional higher-is-better accuracy scores: simple baseline train 0.70 / validation 0.69; shallow model 0.83 / 0.80; deep model 0.99 / 0.63. The shallow model has the best validation accuracy in this comparison, so select it provisionally, inspect error types and variability, then evaluate the locked workflow on untouched test data. These numbers are hypothetical, not measured results. Stronger regularization, fewer features, more representative training examples or early stopping can reduce overfit; too much restriction can cause underfit. A validation curve varies a hyperparameter while holding the split design fixed. A learning curve varies training set size and records training and validation scores. Both help diagnose possible causes, but neither guarantees performance under distribution shift. When tuning repeatedly, selection can overfit validation scores; nested cross-validation and separate final testing are advanced follow-ups.
Practice and recap
For [0,2,4,6] with two round-robin folds, training means are 4 and 2. Each fold MAE is 2. For centered x=[−2,2], y=[−6,6], the unpenalized slope is 3; with penalty 8 it is 1.5. Explain why tuning the penalty using the final test score invalidates that test as an independent estimate. Record model choice, fold assignments, metric definition and any remaining uncertainty. Next: neural networks from first principles.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Generalization and validation quiz
Apply feature preparation and generalization concepts.
Training accuracy is 0.99 and validation accuracy is 0.63. What is the most defensible interpretation?
In k-fold cross-validation, on which rows should each fresh scaler estimate its parameters?
For the centered ridge objective sum((y−w*x)²) + λw², with x=[−1,1], y=[−4,4] and λ=2, what is the optimal slope?
If validation accuracy is the sole selection criterion and three models score 0.69, 0.80 and 0.63 respectively, which is the provisional choice?
For a learning curve that plots training and validation scores against sample size, which quantity changes across points?