How Long to Wait

Training Deep NetworksMedium+20 XP+20

How Long to Wait

A training run records its validation loss at the end of every epoch. Early stopping watches that number, saves a checkpoint whenever it improves, and halts once it has gone patience epochs in a row without improving. Then comes the step people forget: it restores the checkpoint from the best epoch.

val_losses is the validation loss the run would record at the end of each epoch if nothing stopped it. val_losses[0] belongs to epoch 1, val_losses[1] to epoch 2, and so on. Your function replays that history one epoch at a time, seeing it exactly as the early-stopping monitor would, with no knowledge of any epoch it has not reached yet.

The rules:

  • An epoch is an improvement only if its loss is strictly lower than every earlier epoch's. Epoch 1 is always an improvement, because nothing came before it.
  • An improvement saves a checkpoint and resets the count of epochs without improvement to zero.
  • Any other epoch adds one to that count. The moment the count reaches patience, training halts after that epoch.
  • If the list runs out first, training simply ends after the last epoch in it.

Task: write early_stopping(val_losses, patience), returning [best_epoch, stop_epoch, best_loss]:

  • best_epoch: the epoch whose checkpoint is restored,
  • stop_epoch: the last epoch that was actually trained,
  • best_loss: the validation loss of the restored checkpoint, rounded to 4 decimal places.

Epochs are numbered from 1. patience is a whole number of at least 1, and val_losses holds at least one value.

Worked through, early_stopping([0.9, 0.8, 0.86, 0.83, 0.78, 0.8, 0.84, 0.81, 0.77], 3):

epochlossbest so farepochs without improvement
10.90.9 (checkpoint)0
20.80.8 (checkpoint)0
30.860.81
40.830.82
50.780.78 (checkpoint)0
60.80.781
70.840.782
80.810.783, which is patience, so training halts

Epoch 4 is lower than epoch 3, but it does not beat the best, so it still counts as an epoch without improvement. Epoch 9 is never trained. The answer is [5, 8, 0.78].

patience is a trade. Set it too low and one noisy epoch ends a run that was still improving. Set it too high and you pay for epochs you will throw away. Either way, what you ship is the checkpoint. The epochs trained after it cost compute and change nothing about the model you keep.

Examples

val_losses = [0.92, 0.71, 0.6034, 0.6121, 0.6507, 0.7, 0.81]
patience = 2
returns [3, 5, 0.6034]
val_losses = [1.2, 0.95, 0.8, 0.83, 0.81, 0.74, 0.76, 0.77, 0.79, 0.73]
patience = 3
returns [6, 9, 0.74]

Hints

Solve it to unlock the solution

Once your code passes every test, a reference solution shows up here so you can compare it with yours.

solution.py
CtrlEnterto run