core28 min studyLesson 16 in Engineering

Generalization, regularization, and honest selection

Understand how fitting a finite sample differs from predicting new data, and how to investigate that gap.

On this page

What you’ll understand

  • Separate optimization error from generalization error.
  • Derive the shrinkage effect of a simple L2 penalty.
  • Design validation that survives repeated experimentation.

Imagine two models with identical training error: one captures a stable relationship, while the other memorizes accidental details. Training loss alone cannot distinguish them. Generalization concerns what happens on new examples from the intended population. Regularization expresses preferences about fitted solutions, but its value is empirical and contextual; no penalty can make an evaluation contaminated by leakage become trustworthy.

A finite sample is not the population

Empirical risk averages observed losses. Population risk averages over the unknown distribution that matters after deployment. Their difference is a generalization gap, not an optimization failure. A model can minimize training loss exactly and still fail on new users. Conversely, poor training and validation performance together often indicate insufficient features, limited capacity, bad labels, or a training problem rather than classic overfitting. Compare curves with the same loss definition before interpreting their gap.

An independent test set can estimate population risk only to the extent that it represents the relevant future population. Time drift, changed measurement, and interventions can break that connection. More data help when they contribute relevant information; many near-duplicate records do not act like as many independent observations. Slice performance by meaningful conditions and inspect errors. A small average gap can conceal a severe failure on a rare but important operating regime.

R^S(θ)=1n∑i=1nℓ(fθ(xi),yi),Δ(θ)=R(θ)−R^S(θ)\widehat R_S(\theta)=\frac{1}{n}\sum_{i=1}^n\ell(f_\theta(x_i),y_i),\qquad \Delta(\theta)=R(\theta)-\widehat R_S(\theta)
The gap compares risk under a specified population with risk on training sample S. Its true value is generally unknown and cannot be inferred from training loss alone.↔ Scroll wide equations horizontally.

Regularization changes which solution is preferred

An L2 penalty adds a cost for large coefficients. In a linear problem it can reduce sensitivity to noisy or nearly collinear directions, trading some training fit for stability. Coefficient scale matters: rescaling one feature changes how much its coefficient is penalized. Decide how to standardize and whether to penalize the intercept. A penalty is not an abstract measure of all possible model complexity, and its strength must be selected using a validation procedure consistent with deployment.

Other choices impose different preferences. Data augmentation asserts that certain transformations should preserve labels; applying a transformation that changes the label injects incorrect supervision. Dropout trains with random masking and has a different evaluation-time behavior. Early stopping selects a point along the optimization path based on held-out behavior. Each method has assumptions, and combining them is not automatically better. Keep an unregularized or simpler baseline to determine whether a proposed constraint actually helps.

J(w)=12(w−a)2+λ2w2,w∗=a1+λ(λ≥0)J(w)=\frac{1}{2}(w-a)^2+\frac{\lambda}{2}w^2,\qquad w^*=\frac{a}{1+\lambda}\quad(\lambda\ge0)
This scalar example shows shrinkage explicitly. It assumes the unregularized data term has unit curvature; it is not the general coefficient formula for an arbitrary dataset.↔ Scroll wide equations horizontally.

Selection itself can overfit

Every architecture trial, feature change, and threshold choice uses information from validation results. Trying enough variants can select one that benefits from validation noise. Track the number of experiments and reserve a final untouched evaluation. For small datasets, cross-validation can reuse data efficiently for development, but folds must preserve grouping and time constraints. When estimating the performance of a whole hyperparameter-selection procedure, nested validation separates outer evaluation from inner selection.

A useful investigation asks what evidence would change the next decision. If training error is high, first test whether a tiny subset can be fitted. If training error is low and validation error grows, try stronger relevant regularization, better data coverage, or a simpler model. If both are excellent but production fails, investigate population mismatch and leakage. Confidence intervals quantify sampling uncertainty under assumptions; they do not account automatically for every adaptive choice made during model development.

Calculate the cost of shrinkage

For J(w)=(w−6)²/2+lambda w²/2, compare lambda=0 with lambda=2.

  1. Differentiate to get J'(w)=(w−6)+lambda w. Setting this to zero gives (1+lambda)w=6.

  2. With lambda=0, the solution is w=6 and the data-fit term is zero. With lambda=2, the solution is w=2 and the data-fit term is (2−6)²/2=8.

  3. The regularized solution intentionally accepts worse fit to this data term. Whether that preference improves predictions on new data requires independent validation; the algebra alone cannot answer it.

The result

Regularization changes the objective and the chosen solution. A larger training error can be an intentional tradeoff, but it is not proof of better generalization.

Explore the model

Interactive lab

Interactive lab · function

Inspect quadratic penalty strength

The lab plots y=ax², its slope, and area. Set a=lambda/2 to interpret the curve as the scalar L2 penalty and inspect how its gradient changes with x. It does not include the data-fit term, choose lambda, or estimate generalization.

Inspect quadratic penalty strengthThis lab uses only y = ax². Playback traces the curve within the fixed integration interval from 0 to x; it does not estimate numerical error or change the chosen point. Current readings: y at chosen x: 0.608; Tangent slope · 2ax: 1.35; Signed area · ax³/3: 0.182. All parameters are adjustable with the labeled controls below.−2.4−1.201.22.4−9−4.504.59xy(x, ax²)
y = ax²TangentSigned integral
y at chosen x
0.608
Tangent slope · 2ax
1.35
Signed area · ax³/3
0.182
t = 0 s

This lab uses only y = ax². Playback traces the curve within the fixed integration interval from 0 to x; it does not estimate numerical error or change the chosen point. Parameter changes pause playback and recompute the model at the current elapsed time. Reset restores both parameters and returns time to zero. Playback starts paused. Adjust either parameter, then choose Play or Step.

Look forIncreasing a penalty coefficient changes optimization pressure; held-out evidence is still needed to judge predictive benefit.

Check your understanding

Training loss is tiny, validation loss worsens, and you have tried 300 variants on the same validation set. What is the strongest next concern?

Try it yourself

Training and validation losses are both large and nearly equal. Is stronger regularization the obvious first fix? Give a useful diagnostic experiment.

Take a moment to make a prediction or work it out on paper. Open a hint when you need one.

Give me a hint

Ask whether the model can learn even a small clean subset.

Compare with the solution

No. This pattern may reflect underfitting, missing information, bad labels, or an optimization bug. Try fitting a tiny clean subset with weak regularization and inspect updates. Failure there points toward optimization or implementation; successful tiny fitting but poor full-data fit motivates inspecting capacity, features, and conflicting labels before adding constraints.

Take it with you

  • Fitting the sample and predicting the population are distinct goals.
  • A regularizer expresses a preference that must be validated.
  • The model-selection procedure can itself overfit data.

Read further

Original sources and deeper explanations to follow at your own pace.

Optional progress, saved in this browser when available. Revisit any lesson at any time.

Lesson not marked complete.