Knowledge / Artificial Intelligence and Data Science / Overfitting, bias-variance and regularisation

Overfitting, bias-variance and regularisation

Artificial Intelligence and Data Science (B.E./B.Tech) · Machine learning · free study notes for exams, placements and interviews

In short

Overfitting is when a model learns the noise and quirks of the training sample instead of the underlying pattern, so it scores well in training and badly on unseen data; underfitting is the opposite failure, a model too simple to capture the signal. The bias-variance decomposition explains both: expected test error splits into squared bias (systematic error of the model family), variance (sensitivity to which particular training sample was drawn) and irreducible noise. Regularisation — ridge, lasso, elastic net, weight decay, dropout, early stopping, pruning, data augmentation — deliberately adds bias to cut variance, and the amount is tuned by cross-validation, not guessed. This is the most reliably asked machine-learning theory topic in GATE DA (the Data Science and Artificial Intelligence paper, introduced in 2024), in university CBCS/AICTE ML papers, and in technical rounds at TCS, Infosys, Wipro, Accenture, Mu Sigma, Fractal, ZS, Flipkart, Swiggy, Razorpay and bank/NBFC analytics teams, where "your model gave 99% on train and 71% on test — what do you do?" is a standard question.

Explained

Overfitting and underfitting

Bias-variance decomposition

Regularisation: ridge, lasso, elastic net

Other regularisers and practical controls

Choosing the right complexity: validation protocol

  1. Split first, then look. Train / validation / test, typically 60:20:20, or k-fold CV on train with a locked-away test set used once.
  2. k-fold CV: split into k folds (k = 5 or 10), train on k−1, score on the held-out fold, average. Stratified k-fold for classification keeps class proportions.
  3. LOOCV (k = n): nearly unbiased but high variance and expensive; for linear models it is cheap via the hat-matrix shortcut.
  4. Grid search / random search / Bayesian optimisation over λ (usually on a log grid such as 10⁻⁴ … 10³), scored by CV mean, with the standard error reported.
  5. One-standard-error rule: among models within one SE of the best CV score, pick the simplest (largest λ) — a classic exam point and good practice.
  6. Nested CV when you both tune and estimate performance; otherwise the reported score is optimistically biased by the tuning.
  7. Respect structure: time series needs forward-chaining splits (TimeSeriesSplit), never random shuffling; grouped data (multiple rows per customer) needs GroupKFold to prevent leakage.
  8. Fit preprocessing inside the fold — scalers, imputers, PCA, SMOTE, target encoding must be fitted on the training part only. Use a Pipeline.

Leakage, drift and the Indian compliance angle

Key points

Formulas and examples

E[(y − f̂(x₀))²] = (Bias[f̂(x₀)])² + Var[f̂(x₀)] + σ² — expected test MSE at x₀; units = (units of y)²
Bias[f̂(x₀)] = E_D[f̂(x₀)] − f(x₀); Var[f̂(x₀)] = E_D[(f̂(x₀) − E_D[f̂(x₀)])²]
Ridge: minimise ‖y − Xw‖² + λ‖w‖² → ŵ_ridge = (XᵗX + λI)⁻¹ Xᵗy (λ in the same units as XᵗX; dimensionless if X standardised)
Lasso: minimise ‖y − Xw‖² + λ‖w‖₁ ; single-feature solution ŵ = sign(Σxy)·max(0, |Σxy| − λ/2)/Σx² (soft thresholding)
Elastic net: minimise ‖y − Xw‖² + λ[α‖w‖₁ + (1 − α)‖w‖²/2], 0 ≤ α ≤ 1
Weight decay update: w ← w(1 − ηλ) − η ∂L/∂w (η = learning rate, dimensionless)
Ridge effective df: df(λ) = Σⱼ dⱼ²/(dⱼ² + λ); shrinkage factor on component j = dⱼ²/(dⱼ² + λ)
Cost-complexity pruning: R_α(T) = R(T) + α|T| (|T| = number of leaves)
k-fold CV error: CV = (1/k) Σᵢ Lᵢ , with SE = s/√k over the k fold losses

Example 1 — bias-variance decomposition from resampled models. Five models trained on five bootstrap samples predict at x₀: 8, 9, 11, 12, 15. True f(x₀) = 10, σ² = 1.

A simpler (more regularised) model on the same five samples predicts 7, 7.5, 8, 8, 8.5.

Modelbias²varianceσ²Total MSE
Flexible1.006.001.008.00
Regularised4.840.261.006.10

The biased, stabler model wins by 1.90 — that is the whole argument for regularisation.

Example 2 — ridge and lasso by hand (one feature, no intercept). Data (x, y): (1, 2), (2, 3), (3, 7). Σx² = 1 + 4 + 9 = 14; Σxy = 2 + 6 + 21 = 29.

Example 3 — choosing polynomial degree from a validation curve.

DegreeTrain RMSEValidation RMSEVerdict
18.28.5Underfit (both high, small gap)
33.13.4Improving
61.93.0Best validation — choose this
90.65.8Overfitting (gap 5.2)
120.111.2Severe overfitting

Degree 6 minimises validation RMSE at 3.0; degree 12's train RMSE of 0.1 is memorisation, and its validation error is 3.7× worse.

Example 4 — selecting λ by 5-fold CV with the one-SE rule. Fold MSEs:

λFold MSEsMean
0.010.42, 0.46, 0.40, 0.44, 0.482.20/5 = 0.440
0.10.36, 0.38, 0.34, 0.40, 0.371.85/5 = 0.370
10.33, 0.35, 0.31, 0.36, 0.301.65/5 = 0.330
100.40, 0.43, 0.41, 0.45, 0.462.15/5 = 0.430

Best mean is λ = 1 at 0.330. For λ = 1 the deviations from 0.330 are 0.00, 0.02, −0.02, 0.03, −0.03 → sum of squares 0.0026, sample variance 0.0026/4 = 0.00065, s = 0.0255, SE = 0.0255/√5 ≈ 0.0114. One-SE band = 0.330 + 0.011 = 0.341; λ = 0.1 (0.370) lies outside it, so λ = 1 stands.

Example 5 — ridge shrinkage and effective df. Standardised design with singular values d = (√10, 2, 1), i.e. d² = 10, 4, 1, and λ = 2.

Example 6 — one weight-decay step. w = 0.80, η = 0.1, λ = 0.5, ∂L/∂w = 0.2: w ← 0.80 × (1 − 0.1×0.5) − 0.1 × 0.2 = 0.80 × 0.95 − 0.02 = 0.76 − 0.02 = 0.74.

from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import RidgeCV, LassoCV, ElasticNetCV
import numpy as np

alphas = np.logspace(-4, 3, 50)          # lambda grid
ridge = make_pipeline(StandardScaler(), RidgeCV(alphas=alphas, cv=5))
lasso = make_pipeline(StandardScaler(), LassoCV(alphas=alphas, cv=5, max_iter=10000))
enet  = make_pipeline(StandardScaler(),
                      ElasticNetCV(l1_ratio=[.1,.5,.7,.9,.95,1], alphas=alphas, cv=5))
# scaler is fitted inside each CV fold because it is in the pipeline - no leakage
ridge.fit(X_train, y_train)
print(ridge[-1].alpha_, ridge.score(X_test, y_test))

Where it is used

Interview questions

Common mistakes

Related topics

Machine learning workflow · Model evaluation metrics · Linear and logistic regression · Ensemble methods and gradient boosting · Feature selection and model interpretability · Dimensionality reduction and PCA

Open in the Knowledge reader →Find jobs →