Sub topic 14
Iteration and Epoch Curves for Iterative Learners
This chapter assumes you can already compute and read a learning curve and a validation curve with scikit-learn. You should also know what underfitting and overfitting look like on those plots. You should be comfortable with fit, predict, and score, and with the idea that a hyperparameter is a setting you choose before training.
Training time as a third axis
A learning curve varies the amount of data. A validation curve varies a hyperparameter. Many models have a third quantity you can vary: how long you train.
Iterative learners fit their parameters in repeated steps. Examples include stochastic gradient descent (SGD) models, neural networks, and gradient boosting. For these models, one pass over the training data is an epoch. In boosting, one added tree is an iteration or stage. An epoch curve (or iteration curve) plots the training score and the validation score after each epoch or stage.
| Curve | x-axis | What you refit | Main question |
|---|---|---|---|
| Learning curve | Training set size | One model per size and fold | Would more data help? |
| Validation curve | One hyperparameter | One model per value and fold | How complex should the model be? |
| Epoch curve | Epochs or stages | Usually one model, scored as it trains | When should training stop? |
The epoch curve differs from the other two in cost. Models after epoch 10 and epoch 11 are nested: the second continues from the first. You can score a single training run at every step instead of refitting from scratch for each x value.
The shapes are familiar. Early in training the model is underfit, so both scores are poor. As training continues, the training score keeps improving. The validation score improves and then often flattens or declines once the model starts fitting noise. The number of epochs therefore acts like a complexity knob, in the same way gamma does for the SVM in the validation curve chapter.
Computing an epoch curve by hand
learning_curve and validation_curve refit the estimator for every point, so they do not fit this job. Instead, write the loop yourself with partial_fit. This method runs one pass over the data it receives and keeps the model's current state.
The next example trains a logistic regression with SGD on the digits data. It scores the training and validation sets after every epoch.
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, stratify=y, random_state=0
)
scaler = StandardScaler().fit(X_train)
X_train = scaler.transform(X_train)
X_val = scaler.transform(X_val)
clf = SGDClassifier(loss="log_loss", alpha=1e-4, random_state=0)
classes = np.unique(y)
rng = np.random.default_rng(0)
history = []
for epoch in range(1, 41):
order = rng.permutation(len(X_train))
clf.partial_fit(X_train[order], y_train[order], classes=classes)
history.append((epoch, clf.score(X_train, y_train), clf.score(X_val, y_val)))
for epoch, train_acc, val_acc in history[::5]:
print(f"epoch={epoch:2d} train={train_acc:.3f} validation={val_acc:.3f}")Three details matter here:
partial_fitdoes not shuffle. The loop shuffles the rows each epoch withrng.permutation, which avoids the same ordering effects every pass.- The first call must receive
classes, because the model cannot see all labels in one call in general. - The scaler is fit on the training split only, then applied to both splits. This is the same leakage rule from the pitfalls chapter.
To draw the curve, put history into three arrays and plot with ax.plot, exactly as you did for the learning curve.
Staged scores for boosting
Gradient boosting builds its model one tree at a time, so every prefix of the ensemble is itself a model. scikit-learn exposes this through staged_predict, which yields predictions after stage 1, stage 2, and so on. You get a full epoch curve from a single fit.
This block continues from the previous one and reuses X_train, X_val, y_train, and y_val.
import numpy as np
from sklearn.ensemble import GradientBoostingClassifier
from sklearn.metrics import accuracy_score
gb = GradientBoostingClassifier(
n_estimators=100, learning_rate=0.1, max_depth=3, random_state=0
)
gb.fit(X_train, y_train)
train_curve = [accuracy_score(y_train, p) for p in gb.staged_predict(X_train)]
val_curve = [accuracy_score(y_val, p) for p in gb.staged_predict(X_val)]
best_stage = int(np.argmax(val_curve)) + 1
print(f"best stage: {best_stage}, validation accuracy: {max(val_curve):.3f}")
print(f"final stage: train={train_curve[-1]:.3f}, validation={val_curve[-1]:.3f}")The + 1 converts a zero-based index into a stage count. If argmax ties, it returns the earliest stage, which is the simpler model. That is usually the choice you want.
Reading an epoch curve
Apply the same diagnostic logic as before, with training time standing in for complexity.
- Both curves low and still rising. The model is undertrained. Train longer, raise the learning rate, or check that features are scaled. Stopping here is a mistake.
- Both curves flat and low. More training will not help. The model class is too simple, or the features lack signal. This is high bias.
- Training keeps rising, validation peaks and falls. The model overfits. The epoch of the validation peak is the stopping point.
- Training and validation both flat and close. Training has converged. Extra epochs cost time and change nothing.
- A noisy, jagged validation curve. Common with SGD, small validation sets, and high learning rates. Do not pick the single best epoch from a noisy curve without smoothing or a patience window.
Training scores can also fall or jump in the early epochs when the learning rate is too high. That is an optimization problem, not a bias or variance problem. If the curve looks unstable, lower the learning rate before drawing conclusions about fit.
Early stopping
Early stopping automates the reading. The model holds out part of the training data, scores it after each epoch, and stops once the score has not improved for a set number of epochs. That number is the patience.
Several estimators have this built in. SGDClassifier uses early_stopping=True, validation_fraction, and n_iter_no_change. Gradient boosting uses n_iter_no_change and validation_fraction. Here is the boosting version:
from sklearn.datasets import load_digits
from sklearn.ensemble import GradientBoostingClassifier
X, y = load_digits(return_X_y=True)
gb = GradientBoostingClassifier(
n_estimators=500,
learning_rate=0.1,
validation_fraction=0.2,
n_iter_no_change=10,
random_state=0,
)
gb.fit(X, y)
print("stages actually fitted:", gb.n_estimators_)If the model stops long before 500 stages, n_estimators_ tells you how many were kept. With patience 10, training stops when ten consecutive stages fail to improve the held-out score, and the final model still includes those ten extra stages.
Choose the patience to match the noise. A patience of 1 or 2 stops at the first dip, which is often just noise. A patience of 10 or more tolerates short dips but costs extra epochs.
Pitfalls specific to epoch curves
The stopping epoch is tuned on the validation data. Picking the best epoch from the validation curve is a form of model selection. The validation score at that epoch is then optimistically biased, for the same reason as the best value in a validation curve. Report final performance on a separate test set that played no part in the choice.
One split is one sample. An epoch curve from a single train and validation split has no error band. If the dataset is small, the best epoch can shift by tens of epochs on a different split. Repeat the run over several splits, or with GroupKFold when samples are dependent. Then plot the mean and spread, and choose a stopping point from the averaged curve.
Early stopping inside cross-validation. When an estimator holds out its own validation data, it uses part of each training fold. That data is lost to fitting. This is correct and leak-free, but the results differ slightly from training on the whole fold.
Epochs interact with other hyperparameters. A smaller learning rate needs more epochs. More regularization changes where the validation peak falls. If you tune alpha or learning_rate, the best number of epochs changes with it. Treat the epoch as a parameter to find by early stopping, then tune the others around that.
Incremental learning curves. learning_curve accepts exploit_incremental_learning=True for estimators that implement partial_fit. It then trains on growing slices of each fold incrementally rather than refitting. This speeds up the learning curve, but it is a different quantity from an epoch curve. It varies data size, not passes over the data.
Exercise
You plot an epoch curve for an SGD classifier. Training accuracy rises steadily from 0.80 to 0.99 over 100 epochs. Validation accuracy rises to 0.93 at epoch 25, then declines slowly to 0.89. What does this show, what should you do, and why should you not report 0.93 as the final performance?
Show answer
The model overfits after epoch 25: the training score keeps rising while the validation score falls. Stop at about epoch 25, for example with early stopping and a patience window, or add regularization. The 0.93 figure is the maximum over many epochs on the validation data, so choosing it used that data and biases it upward. Report performance on a separate test set, or use repeated splits.