The goal of machine learning is not to fit the training data perfectly but to make good predictions on new data, which is called generalisation. A model that is too simple misses real patterns (underfitting); a model that is too flexible learns the noise as well (overfitting). This lesson shows both problems in numbers and introduces cross-validation and grid search, the standard tools for finding the right balance.
In this lesson you will learn
- How to recognise underfitting and overfitting
- The bias-variance trade-off
- K-fold cross-validation with
cross_val_score - Tuning settings with
GridSearchCV - Practical ways to reduce overfitting
Too Simple, Just Right, Too Complex
This example fits polynomial curves of increasing degree to 15 noisy points from a sine wave, then tests them on 200 fresh points.
import numpy as np
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import PolynomialFeatures
rng = np.random.default_rng(0)
def make_data(n):
X = np.sort(rng.uniform(0, 1, n)).reshape(-1, 1)
y = np.sin(2 * np.pi * X).ravel() + rng.normal(0, 0.2, n)
return X, y
X_train, y_train = make_data(15) # small training set
X_test, y_test = make_data(200) # fresh data the model never saw
for degree in [1, 4, 12]:
model = make_pipeline(PolynomialFeatures(degree), LinearRegression())
model.fit(X_train, y_train)
train_err = mean_squared_error(y_train, model.predict(X_train))
test_err = mean_squared_error(y_test, model.predict(X_test))
print(f"degree {degree:2d}: train error {train_err:.3f} test error {test_err:.3f}")
Output
degree 1: train error 0.176 test error 0.350
degree 4: train error 0.011 test error 0.062
degree 12: train error 0.008 test error 0.109
- Degree 1 (a straight line) cannot follow a wave. Both errors are high: this is underfitting, also called high bias.
- Degree 4 follows the wave’s shape. Training and test errors are both low and close together, which is the sweet spot.
- Degree 12 bends to pass near every training point, so its training error is the lowest, but its test error almost doubles. It has learned the noise: this is overfitting, also called high variance.
| Symptom | Diagnosis | Try |
|---|---|---|
| Training and test scores both poor | Underfitting | A more flexible model, better features, less regularisation |
| Training score much better than test score | Overfitting | More data, a simpler model, regularisation, fewer features |
| Both good and close | Good fit | Confirm on the test set and stop |
Cross-Validation and Grid Search
A single train-test split can be lucky or unlucky. K-fold cross-validation splits the data into k parts (folds), trains on k − 1 of them, tests on the remaining one, and repeats until every fold has been the test set once. The average score is far more reliable.
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import cross_val_score, GridSearchCV
from sklearn.tree import DecisionTreeClassifier
X, y = load_breast_cancer(return_X_y=True)
scores = cross_val_score(DecisionTreeClassifier(random_state=0), X, y, cv=5)
print("5 fold scores:", scores.round(3))
print(f"Mean {scores.mean():.3f} (+/- {scores.std():.3f})")
search = GridSearchCV(
DecisionTreeClassifier(random_state=0),
param_grid={"max_depth": [2, 3, 4, 6, None], "min_samples_leaf": [1, 5, 10]},
cv=5,
)
search.fit(X, y)
print("Best settings:", search.best_params_)
print(f"Best cross-validated accuracy: {search.best_score_:.3f}")
Output
5 fold scores: [0.904 0.921 0.912 0.947 0.903]
Mean 0.917 (+/- 0.016)
Best settings: {'max_depth': 4, 'min_samples_leaf': 10}
Best cross-validated accuracy: 0.931
- The five fold scores range from 0.903 to 0.947. A single split could have reported either number; the mean and standard deviation give an honest picture.
GridSearchCVtries every combination inparam_grid(5 × 3 = 15 here), runs 5-fold cross-validation for each, and keeps the best. Limiting the tree (max_depth=4,min_samples_leaf=10) improves accuracy from 0.917 to 0.931, a direct fix for overfitting.- After the search,
search.best_estimator_is a model retrained on all the data passed tofitwith the best settings. - In a real project, run the grid search on the training set only and keep a separate test set for the final check, as in the end-to-end project.
Ways to Reduce Overfitting
- Get more training data, often the most effective fix.
- Simplify the model: lower degree, shallower trees, fewer features.
- Regularise:
Ridge/Lassofor linear models, smallerCfor logistic regression. - Use ensembles such as random forests.
- Stop early when training iterative models such as neural networks and boosting.
Common Mistakes
- Celebrating a high training score.
- Tuning against the test set, which overfits the test set itself.
- Fitting preprocessing outside cross-validation. Put scalers in a pipeline so each fold is clean.
- Huge grids that take hours. Start coarse, then refine around the best values, or use
RandomizedSearchCV.
Practice Exercises
Exercise 1. A model scores 0.99 on training data and 0.71 on test data. What is the likely problem and one fix?
Show answer
Overfitting. Fixes include a simpler model, regularisation, limiting tree depth, or collecting more data.
Exercise 2. Use GridSearchCV to find the best n_neighbors from 1 to 15 for KNN on the wine data.
Show answer
pipe = make_pipeline(StandardScaler(), KNeighborsClassifier())
search = GridSearchCV(pipe, {"kneighborsclassifier__n_neighbors": range(1, 16)}, cv=5)
search.fit(X, y)
print(search.best_params_, round(search.best_score_, 3))
Inside a pipeline, parameter names are the step name, two underscores and the parameter.
Frequently Asked Questions
How many folds should I use?
5 or 10 folds are standard. More folds use more data for training each time but take longer. For classification, scikit-learn automatically keeps class proportions in each fold (stratified k-fold).
What is the bias-variance trade-off?
Bias is error from a model being too simple; variance is error from being too sensitive to the particular training data. Making a model more flexible lowers bias but raises variance, so the best model sits in between.
Summary
- Underfitting: poor everywhere. Overfitting: great on training data, poor on new data.
- K-fold cross-validation gives a stable estimate by averaging several splits.
GridSearchCVpicks settings with cross-validation.- More data, simpler models, regularisation and ensembles all fight overfitting.
