The one question model selection has to answer
Every modeling project eventually produces several plausible candidates, each with a score attached. The skill is not fitting them — optimizers do that — but deciding which score you are allowed to believe. It covers the four tools statisticians actually use: the bias–variance decomposition, k-fold cross-validation, the information criteria AIC and BIC, and penalized regression, each demonstrated on simulated data in Python.
- You will predict how training and validation error move as complexity grows.
- You will compute a cross-validation score and its fold-to-fold spread from scratch.
- You will know when AIC and BIC disagree, and which to trust for your goal.
Prerequisites
- !Least squares regression and likelihood
- !Training versus test error
- !Regularization vocabulary: Ridge and Lasso
What You'll Learn
- 1Decompose expected prediction error into bias, variance and noise
- 2Run k-fold and nested cross-validation without leaking the test set
- 3Compute and interpret AIC, BIC and adjusted R-squared
- 4Use L1 and L2 penalties as an implicit form of model selection
Where prediction error actually comes from
Assume the data follow with independent noise of variance . For a fitted model , the expected squared error at a point splits into three non-negative parts: squared bias, the variance of across training samples, and the noise variance. Only the last is irreducible; the other two follow entirely from the modeling choices you make.
Raising flexibility pushes bias down and variance up at similar rates, so total error traces a U-shaped curve. Three regimes are easy to recognize:
| Regime | Training error | Validation error | Diagnosis |
|---|---|---|---|
| Underfit | High, barely improves with more data | High, close to training | Model too simple, or features missing signal |
| Well fit | Low but not near zero | Minimum of the validation curve | Complexity matches the amount of signal |
| Overfit | Very low, near zero | Rising as complexity grows | Model memorizing noise; regularize or simplify |
The consequence: training error only falls as complexity grows, so any criterion built on it will always choose the most complex model available.
Why training error always flatters you
The experiment below fits polynomials of rising degree to noisy sine data and records both errors; watch how the two columns diverge.
import numpy as np
from sklearn.preprocessing import PolynomialFeatures
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error
rng = np.random.default_rng(7)
X = rng.uniform(-1, 1, size=(60, 1))
y = np.sin(1.5 * np.pi * X.ravel()) + rng.normal(0, 0.25, 60)
Xv = rng.uniform(-1, 1, size=(200, 1))
yv = np.sin(1.5 * np.pi * Xv.ravel()) + rng.normal(0, 0.25, 200)
for deg in range(1, 16):
poly = PolynomialFeatures(degree=deg, include_bias=False)
Xt, Xvt = poly.fit_transform(X), poly.transform(Xv)
model = LinearRegression().fit(Xt, y)
train = mean_squared_error(y, model.predict(Xt))
valid = mean_squared_error(yv, model.predict(Xvt))
print(f"degree {deg:2d} train {train:7.3f} valid {valid:7.3f}")
Training error falls monotonically across the whole range, from 0.57 at degree 1 to 0.035 at degree 15: a high-degree polynomial interpolates sixty noisy points almost exactly. Validation error drops sharply until about degree 5, then creeps back up as the fit starts tracking individual noise draws. Selecting on training error picks the most complex model available; the validation curve points somewhere much simpler. One catch remains: a validation set used repeatedly for selection becomes part of training, so the final reported number must come from data the search never touched.
K-fold cross-validation, step by step
Cross-validation estimates out-of-sample error by rotating the holdout: partition the data into folds, fit on the folds not held out, score the remaining fold, average the results. The mean is nearly unbiased, and the spread shows how fragile it is.
Here is a minimal implementation that reports both the mean and the fold spread:
import numpy as np
from sklearn.linear_model import Ridge
def kfold_mse(X, y, factory, k=5, seed=0):
idx = np.arange(len(y))
np.random.default_rng(seed).shuffle(idx)
folds = np.array_split(idx, k)
scores = []
for i in range(k):
test = folds[i]
train = np.concatenate([f for j, f in enumerate(folds) if j != i])
model = factory()
model.fit(X[train], y[train])
err = (y[test] - model.predict(X[test])) ** 2
scores.append(float(err.mean()))
return float(np.mean(scores)), float(np.std(scores))
mean, spread = kfold_mse(X, y, lambda: Ridge(alpha=1.0))
print(f"CV MSE = {mean:.3f} across folds, sd = {spread:.3f}")
Picking is itself a bias–variance tradeoff: small inflates bias, large inflates the variance of the estimate while multiplying compute.
| Scheme | Folds | Bias | Variance of estimate | Typical use |
|---|---|---|---|---|
| 5-fold | 5 | Slightly higher | Lower, stable | Default for large datasets and deep models |
| 10-fold | 10 | Lower | Moderate | Classic tabular default |
| Leave-one-out | Lowest | Highest, folds nearly identical | Very small samples, linear models | |
| Repeated -fold | Same as -fold | Reduced by averaging repeats | Noisy metrics, small datasets |
Penalizing complexity: AIC, BIC, adjusted R-squared
Cross-validation is expensive; information criteria are cheap. Both compare models by combining fit with a penalty that grows in the number of estimated parameters , using the maximized log-likelihood and the sample size .
AIC targets expected out-of-sample KL divergence, so it keeps adding variables as long as they improve prediction slightly. BIC approximates posterior model probability, and its penalty exceeds 2 once — any sample larger than about 7. Adjusted is the least-squares special case: it improves only when a new predictor beats the noise it introduces.
| Criterion | Penalty per parameter, , | Optimizes | Consistent for the true model? |
|---|---|---|---|
| AIC | Prediction accuracy, KL risk | No, tends to overfit in large samples | |
| BIC | Posterior model probability | Yes, given the true model is in the set | |
| Adjusted | Implicit, via | Explained variance net of noise | Only inside the linear Gaussian family |
| Cross-validation | Data-dependent | Empirical future error | Asymptotically, with caveats |
Match the criterion to the goal: rank by cross-validation or AIC when the model will be used for prediction, and by BIC when you want a parsimonious explanation of which predictors matter.
A worked comparison of three candidates
As a calibration: a gap under 2 is negligible, 2 to 6 is positive, 6 to 10 is strong, and above 10 is very strong — report the gap, not just the winner.
Regularization: letting the fit choose the complexity
An alternative to ranking discrete candidates is to shrink the parameter space continuously. Ridge shrinks every coefficient toward zero but rarely reaches it; Lasso sets many coefficients exactly to zero, performing feature selection inside the optimization; Elastic Net blends both penalties and behaves better when predictors are strongly correlated.
| Method | Penalty | Coefficients | Feature selection? | Best for |
|---|---|---|---|---|
| Ridge (L2) | All shrunk, none zeroed | No | Many small correlated signals | |
| Lasso (L1) | Some exactly zero | Yes | Sparse true model | |
| Elastic Net | L1 + L2 | Partially zeroed | Partially | Correlated groups of predictors |
The tuning parameter is itself a hyperparameter, so it is chosen by cross-validation — model selection folded into the fit.
import numpy as np
from sklearn.linear_model import LassoCV, RidgeCV
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
rng = np.random.default_rng(0)
Xs = rng.normal(size=(200, 40))
signal = [3, 11, 22, 37]
ys = (2.0 * Xs[:, signal[0]] - 1.5 * Xs[:, signal[1]]
+ Xs[:, signal[2]] + rng.normal(size=200))
lasso = make_pipeline(StandardScaler(), LassoCV(cv=5, random_state=0)).fit(Xs, ys)
ridge = make_pipeline(StandardScaler(), RidgeCV(alphas=np.logspace(-3, 3, 50))).fit(Xs, ys)
kept = np.flatnonzero(lasso[-1].coef_)
print("Lasso kept columns:", kept, " (true:", signal, ")")
print("Lasso alpha:", round(lasso[-1].alpha_, 4))
print("Ridge non-zero coefficients:", int(np.sum(ridge[-1].coef_ != 0)), "of 40")
Lasso kept three of the four informative columns, plus a few extras, while Ridge kept all forty. Neither is wrong: Ridge is safer when every feature carries a little signal, Lasso when you need a deployable subset. Stability still matters — if Lasso picks a different subset on each bootstrap sample, the selection is not trustworthy.
A workflow that survives the test set
- Lock away a held-out test set before any exploration, and never look at it again until the end.
- Choose the primary metric first; a model cannot be selected by a metric invented after the results are visible.
- Build the candidate set: model families, degrees, feature subsets, penalty strengths.
- Tune inside the training data with -fold cross-validation, recording mean and standard deviation across folds.
- Refit the winner on the full training sample, evaluate exactly once on the test set, and report that number beside the cross-validation estimate. If the test result is far worse, treat it as evidence that the search overfit — never go back and tune against the test set.
💡Reading the fold spread
If cross-validation reports 0.82 with a fold standard deviation of 0.14, two candidates separated by 0.03 are indistinguishable. A difference smaller than the fold noise is not a difference: prefer the simpler model.
Common Mistakes
Selecting the final model by training or in-sample R-squared
Fix: Use held-out or cross-validated error; training fit only ever rewards complexity.
Tuning hyperparameters on the test set because it was convenient
Fix: Split once up front, tune only inside cross-validation, and evaluate the test set a single time.
Quoting a cross-validation mean without its spread
Fix: Report mean plus standard deviation across folds, and compare candidates only when the gap exceeds that noise.
Assuming BIC always dominates AIC because it is more conservative
Fix: Match the criterion to the goal: prediction favors AIC or cross-validation, explanation and sparse truth favor BIC.
Running Lasso once and treating the selected features as discovered facts
Fix: Check selection stability across resamples, and use Elastic Net when predictors are correlated.
Best Practices
- Reserve the test set before any modeling work begins, and document the decision
- Report cross-validation results as a mean with a fold-level standard deviation
- Include both a parsimonious baseline and the strongest candidate in every comparison
- Treat differences smaller than the fold noise as ties and choose the simpler model
Interview Questions
Q1: Why can training error never be used to select a model?
Adding parameters can only reduce the training residual sum of squares, so training error is monotone in complexity and always favors the largest model, no matter how much noise it fits.
Q2: AIC and BIC disagree on the winning model. Which do you trust?
It depends on the objective. For prediction accuracy I trust cross-validation and, as a cheap proxy, AIC. For identifying the true parsimonious mechanism I trust BIC, whose penalty grows with log of sample size and is consistent.
Q3: What problem does nested cross-validation solve?
It separates hyperparameter tuning from performance estimation. An inner loop selects the configuration, an outer loop estimates its error, so the reported score is not inflated by the search itself.