Sub topic 14
Iteration and Epoch Curves for Iterative Learners
This chapter assumes you can read learning curves and validation curves, and that you know fit and partial_fit in scikit-learn. Here the x-axis changes. Instead of training set size or a hyperparameter, it is the amount of training the model has done.
Training time as a curve axis
Many models learn in steps. Stochastic gradient descent, neural networks and gradient boosting all improve the model a little on each pass. One pass over the training data is an epoch. Boosting adds one tree per iteration.
For these models, the number of epochs or iterations acts like a complexity setting. Early on the model is too simple and underfits. After many epochs it can start to memorize the training data and overfit. Plotting training and validation scores against the epoch count shows where that shift happens. It uses the same reading rules as a validation curve.
Computing an epoch curve
learning_curve and validation_curve refit the model from scratch for every point. For an iterative learner it is cheaper to train once and score after each epoch. The loop below uses partial_fit, which runs exactly one pass each time you call it.
import numpy as np
from sklearn.datasets import load_digits
from sklearn.linear_model import SGDClassifier
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
X, y = load_digits(return_X_y=True)
X_train, X_val, y_train, y_val = train_test_split(
X, y, test_size=0.25, random_state=0, stratify=y
)
scaler = StandardScaler().fit(X_train)
X_train = scaler.transform(X_train)
X_val = scaler.transform(X_val)
model = SGDClassifier(loss="log_loss", alpha=1e-5, random_state=0)
classes = np.unique(y)
rng = np.random.default_rng(0)
train_hist, val_hist = [], []
for epoch in range(1, 31):
order = rng.permutation(len(X_train))
model.partial_fit(X_train[order], y_train[order], classes=classes)
train_hist.append(model.score(X_train, y_train))
val_hist.append(model.score(X_val, y_val))
if epoch == 1 or epoch % 5 == 0:
print(f"epoch={epoch:2d} train={train_hist[-1]:.3f} validation={val_hist[-1]:.3f}")
best_epoch = int(np.argmax(val_hist)) + 1
print("Best validation epoch:", best_epoch)The scaler is fitted on the training split only, so no validation information leaks in. The code shuffles the rows each epoch because partial_fit does not shuffle for you.
Reading the curve
- Both rising: the model is still underfitting. More epochs help.
- Validation flat, training rising: extra epochs only fit noise. Stop.
- Validation falls after a peak: the model is overfitting. Choose the epoch at the peak.
Smooth training curves are common. Validation curves are noisier, especially with small validation sets. Do not pick an epoch from a single-epoch spike. Look for the broad plateau.
Early stopping
Picking the best epoch by hand is called early stopping. Several scikit-learn estimators automate it:
SGDClassifier(early_stopping=True, n_iter_no_change=5)holds out part of the training data and stops when its score stops improving.MLPClassifier(early_stopping=True)does the same and recordsvalidation_scores_. It also exposesloss_curve_for the training loss.GradientBoostingClassifieroffersstaged_predict, which gives predictions after each tree.
Limits of the method
The epoch you choose was selected using the validation data. Its score is therefore slightly optimistic. Keep a separate test set for the final number.
A single split has no error bands. Repeat the run with different seeds or folds if you need to know whether a 0.5 point difference is real. Also, an epoch curve changes with the learning rate and the regularization strength. Re-check it after you tune either one.
Exercise
Your validation accuracy peaks at epoch 12 and then slowly drops while training accuracy keeps climbing. What does this show, and what are two ways to respond?
Show answer
The model is overfitting after epoch 12. You can stop training at about epoch 12 (early stopping), or increase regularization, for example a larger alpha in SGDClassifier, and then re-check the curve.