Sub topic 19
A practical workflow for diagnosing and fixing a model
This chapter ties the earlier ideas into one repeatable procedure. It assumes you know the following:
- Train, validation and test splits.
- k-fold cross-validation.
- The bias-variance trade-off.
- Ridge, lasso, early stopping and dropout.
- Scikit-learn pipelines.
The goal is to answer one question in order: what is wrong with this model, and which change is most likely to fix it?
Start with a baseline and a target
Before diagnosing anything, fix two reference points.
- A trivial baseline, such as predicting the training mean or the majority class. A model that cannot beat it has a more basic problem than overfitting.
- An estimate of the best error you could reasonably reach. This might be human performance, the label noise you know about, or a published result. In the examples below the noise standard deviation is 0.2, so the best possible mean squared error is about 0.04.
Without a target, "training error is low" and "training error is high" mean nothing. Error is only high or low relative to something.
Step 1: measure training and validation error together
Always look at both numbers, from the same procedure. Cross-validation with return_train_score=True gives both, and it keeps scaling inside each fold.
import numpy as np
from sklearn.model_selection import cross_validate
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import PolynomialFeatures, StandardScaler
from sklearn.linear_model import LinearRegression, Ridge
rng = np.random.default_rng(0)
X = rng.uniform(-3, 3, size=(200, 1))
y = np.sin(X).ravel() + rng.normal(0, 0.2, size=200)
def report(name, model):
res = cross_validate(
model, X, y, cv=5,
scoring="neg_mean_squared_error",
return_train_score=True,
)
train = -res["train_score"].mean()
val = -res["test_score"].mean()
print(f"{name:26s} train={train:.3f} val={val:.3f} gap={val - train:.3f}")
report("degree 1", make_pipeline(
PolynomialFeatures(1), StandardScaler(), LinearRegression()))
report("degree 15", make_pipeline(
PolynomialFeatures(15), StandardScaler(), LinearRegression()))
report("degree 15 + ridge", make_pipeline(
PolynomialFeatures(15), StandardScaler(), Ridge(alpha=1.0)))Read the output as two quantities:
- The training error compared with your target. A large distance means the model cannot even fit the data it has seen.
- The gap between validation and training error. A large gap means the model's fit does not carry over to new data.
Step 2: classify the problem
The two quantities give three common situations.
| Training error | Validation error | Gap | Diagnosis |
|---|---|---|---|
| High | High | Small | High bias (underfitting) |
| Low | High | Large | High variance (overfitting) |
| Low | Low | Small | Acceptable, check the test set once |
Both problems can appear together. A model with high training error and a large gap is rare but possible, for example when the data is badly mismatched to the model and the model is also unstable. Fix the bias first. A model that cannot fit the training data gives you nothing to regularise.
A learning curve confirms the classification. Plot both errors against training set size:
- If the curves converge at a high error, more data will not help. You need a more flexible model or better features.
- If a wide gap persists and narrows as data grows, the model is overfitting and more data is a real option.
Step 3: apply the remedy that matches the diagnosis
Pick a remedy from the right column. Applying a variance remedy to a bias problem makes things worse.
| Diagnosis | Try, roughly in this order |
|---|---|
| High bias | Add informative features or interactions. Use a more flexible model. Lower the regularisation strength. Train longer. |
| High variance | Collect more data or augment it. Raise the regularisation strength. Use lasso to drop features. Add dropout and early stopping for neural networks. Reduce model size. |
Change one thing at a time and re-run Step 1. If you change three settings at once, you cannot tell which one helped.
For regularised models, the strength is the knob that moves you along the bias-variance curve. Tune it with cross-validation:
from sklearn.model_selection import GridSearchCV
pipe = make_pipeline(PolynomialFeatures(15), StandardScaler(), Ridge())
grid = GridSearchCV(
pipe,
param_grid={"ridge__alpha": [1e-4, 1e-2, 1, 100]},
cv=5,
scoring="neg_mean_squared_error",
)
grid.fit(X, y)
print(grid.best_params_, round(-grid.best_score_, 3))Use a wide, roughly logarithmic grid. If the best value sits at an edge of the grid, extend the grid in that direction.
Step 4: guard against leakage at every stage
Leakage makes a diagnosis look better than reality, so check it before trusting any number.
- Fit scalers, imputers and feature selectors inside the pipeline, so each fold learns them from its own training portion only.
- Split before any step that uses the labels or the whole dataset's statistics.
- For grouped data (several rows per patient, user or device), split by group so one entity never appears on both sides.
- For time series, validate on later data than you train on.
- Do not use the test set to choose between models, features or strengths.
A suspicious sign is validation error that is far better than your target or your baseline suggests is possible. Treat it as a bug first and a success second.
Step 5: final check and stopping
When validation error is near your target and the gap is small, do the following.
- Fix the chosen settings.
- Refit on the combined training and validation data.
- Score once on the test set.
The test score should be close to the cross-validation score. A much worse test score means that the tuning overfit the validation folds, the test data differs from the training data, or there is leakage you missed. Do not go back and tune against the test result. If you must, collect a new held-out set.
Stop iterating when further changes improve validation error by less than its fold-to-fold variation. Look at the standard deviation of the fold scores. A difference of 0.002 in mean error, with folds varying by 0.02, is noise.
Common mistakes
- Judging a model from validation error alone. Without training error, you cannot tell bias from variance.
- Reaching for more data when the learning curves have already converged at a high error.
- Regularising an underfit model harder.
- Comparing scores computed on different splits or with different scaling.
- Forgetting the baseline, and celebrating a model that barely beats the mean.
Exercise
A model has training MSE 0.04, validation MSE 0.31, and a target MSE of about 0.04. Learning curves show the gap narrowing slowly as you add data. Name the diagnosis and give two remedies, in the order you would try them. Then say what you would conclude if the training MSE were 0.30 and the validation MSE 0.32.
Show answer
Training error is at the target and the gap is large, so this is high variance (overfitting). Try stronger regularisation, such as a larger ridge alpha, tuned by cross-validation, and collecting or augmenting data, since the narrowing gap shows more data helps. Reducing model size is another option. With training MSE 0.30 and validation MSE 0.32, both errors are far above the 0.04 target and the gap is small. That is high bias (underfitting), so you would add capacity or features or lower the regularisation, not add data.
Exercise
Your cross-validated MSE is 0.05, but the final test MSE is 0.19. List two likely causes and one thing you must not do in response.
Show answer
Likely causes are leakage during preprocessing or tuning (for example scaling on the full dataset, or choosing settings against the same folds many times), and a test set that differs in distribution from the training data. You must not tune the model further against the test score, because that uses up the test set as an unbiased estimate.