Generalization Gaps and Weight Penalties: A Short ML Primer
Machine LearningModel answerLast updated
Describe how to recognize a model that memorizes its training data, list ways to curb it, and contrast absolute-value and squared-weight penalties on a model's coefficients.
Imagine a short fundamentals round on model generalization. Answer the three parts below as you would out loud, with clear definitions, concrete examples and trade-offs.
-
Memorizing instead of learning. Describe what it means for a trained model to fit its training set too closely. Explain it using the relationship between training performance, validation performance and performance on future data. How would you diagnose it in practice?
-
Countermeasures. Which techniques would you use to prevent or reduce this problem? For each, say what it changes about the training setup and in which situations you would reach for it first.
-
Two penalty terms. A penalty on the sum of absolute weight values and a penalty on the sum of squared weight values are both commonly added to a loss function. Compare them in terms of:
- the effect on the learned weights,
- whether they perform feature selection,
- optimization behavior,
- typical use cases.
Aim for an answer that moves from intuition to mechanism to practice, and mention pitfalls that people commonly run into.
Hints
Hint 1
Start from the quantity that matters: error on data the model has not seen. Then ask what you would observe in training curves versus validation curves if the model were memorizing noise.
Hint 2
Organize countermeasures by the lever they pull: more or better data, less model capacity, explicit penalties, training-procedure tricks (early stopping, dropout), ensembling, and sound evaluation. Decide which you would try first and why.
Hint 3
For the penalty comparison, look at the gradient of each penalty term as a weight approaches zero. One pulls with strength proportional to the weight, the other with constant strength. Then connect that to the shape of each constraint region.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. Overfitting
Definition. A model overfits when it captures quirks of its training sample (noise, accidental correlations, leaked information) that do not hold in the true data distribution. It scores very well on data it has seen and noticeably worse on new data. The real goal is low error on unseen data, not low training error.
How to diagnose it
- Training loss keeps decreasing while validation loss flattens and then rises.
- There is a large generalization gap, for example 0.99 AUC on training versus 0.78 on validation.
- Learning curves show the training curve far above the validation curve. If adding data narrows the gap, variance is the problem.
Bias-variance view. Expected squared error splits into bias squared, variance and irreducible noise. Overfitting is the high-variance regime: small changes in the training set yield very different fitted functions. Underfitting is the opposite, with high bias and poor scores on both training and validation.
Typical causes
- Capacity too large for the amount of data (deep trees, many parameters).
- Too many features, especially high-cardinality identifiers that are easy to memorize.
- Training for too many epochs.
- Noisy labels.
- Repeatedly tuning against the same validation or test set, which overfits the evaluation itself.
- Data leakage, such as random splits on time-ordered data.
2. Preventing and mitigating it
| Lever | Techniques | When to use |
|---|---|---|
| More or better data | Collect more, fix noisy labels, augment (flips, crops, back-translation) | First choice if feasible. It reduces variance without adding bias. |
| Lower capacity | Fewer layers or units, shallower trees, lower polynomial degree | Large gap persists even with a reasonable amount of data. |
| Explicit regularization | L1, L2, elastic net, weight decay | Default for linear models and neural nets. |
| Training-procedure regularization | Early stopping, dropout, label smoothing, batch norm | Deep learning. Early stopping is almost free. |
| Ensembling | Bagging, random forests, boosting with shrinkage and subsampling | Tabular data. Bagging directly attacks variance. |
| Feature control | Feature selection, frequency cutoffs for rare categories, PCA | High-dimensional or sparse inputs. |
| Tree-specific limits | Max depth, min samples per leaf, pruning, row and column subsampling | Random forests and gradient-boosted trees. |
| Sound evaluation | Held-out validation, k-fold CV, time-based splits, untouched test set | Always. You cannot manage what you cannot measure. |
Practical order of attack. (1) Make sure the evaluation is honest, with no leakage and a split that matches deployment. (2) Look at learning curves to confirm a variance problem. (3) Add data or augmentation if cheap. (4) Add regularization and early stopping. (5) Reduce capacity or ensemble.
Large-scale example. In recommendation or ads models with huge sparse ID features, rare IDs are trivially memorized. Common fixes are frequency thresholds, embedding regularization, L1 on sparse linear models and time-based validation. A model that wins offline but loses in an online experiment may have overfit to logging artifacts or to the offline set.
3. Absolute-value penalty (L1) versus squared penalty (L2)
Loss with penalty:
- L1:
loss(w) + λ · Σ|w_j| - L2:
loss(w) + λ · Σ w_j²
Effect on weights (gradient argument)
- L2: the penalty gradient is
2λw_j, proportional to the weight. Each step multiplies the weight by roughly(1 − 2ηλ). Weights shrink toward zero but almost never become exactly zero. - L1: the subgradient is
λ·sign(w_j), a constant pull regardless of magnitude. If a feature's loss gradient is weaker thanλ, its weight is pinned at exactly zero. The one-dimensional solution is soft-thresholding:sign(z)·max(|z| − λ, 0).
Geometric argument. Minimizing the loss under a norm-ball constraint, the L1 ball is a diamond with corners on the axes. Loss contours tend to touch a corner first, which sets some coordinates to zero. The L2 ball is round, so the contact point is typically off-axis, giving small but nonzero weights.
Bayesian view. L2 is MAP estimation with a Gaussian prior. L1 corresponds to a Laplace prior, which is sharply peaked at zero.
| L1 | L2 | |
|---|---|---|
| Weights | Sparse, many exactly zero | Small and dense |
| Feature selection | Built in | None |
| Correlated features | Tends to pick one arbitrarily, can be unstable | Spreads weight across the group |
| Optimization | Not differentiable at 0. Use coordinate descent, proximal methods or subgradients | Smooth and strongly convex. Ridge regression has a closed form (XᵀX + λI)⁻¹Xᵀy |
| Uniqueness | Not guaranteed with correlated features or p > n | Unique for λ > 0 |
| Typical use | High-dimensional sparse models, interpretability, smaller models to serve | Default choice, multicollinearity, weight decay in neural nets |
Elastic net mixes both penalties. It gives sparsity while handling groups of correlated features more gracefully, which answers the natural follow-up "what if I want both?"
Practical notes
- Standardize features first, otherwise the penalty depends on feature scale.
- Do not penalize the bias/intercept term.
- Tune λ with cross-validation on a log scale.
- With adaptive optimizers such as Adam, use decoupled weight decay (AdamW). An L2 term added to the loss is not equivalent to weight decay there.
Common mistakes
- Defining overfitting as "the model is too complex" without mentioning generalization or the train/validation gap.
- Claiming L2 produces exactly zero weights. It shrinks them but rarely zeroes them.
- Tuning hyperparameters on the test set, then reporting that score as unbiased.
- Using random splits on time-dependent data, which hides overfitting until deployment.
- Forgetting to standardize features before regularizing.
- Reaching for a complex fix (new architecture) before checking learning curves and data quality.
What a strong answer shows
- A definition tied to generalization, with concrete diagnostics.
- Techniques grouped by mechanism, with a sensible order of priority.
- A real explanation of why L1 yields sparsity (gradient or geometry), not just the assertion.