Find where early stopping halts

Why it matters Fine-tuning runs stop on validation loss with this rule to avoid overfitting small datasets.

Early stopping halts when validation loss has not improved for patience epochs.

Write early_stop(val_losses, patience, min_delta=0.0). Track the best loss. An epoch improves if loss < best - min_delta. Return (stop_epoch, best_epoch), both 0-based, where stop_epoch is the epoch at which the count of non-improving epochs reaches patience, or the last epoch if it never does.

Signaturedef early_stop(val_losses, patience, min_delta=0.0)

Example

early_stop([1.0, 0.8, 0.85, 0.9], 2) gives (3, 1).

Understand the idea

Early stopping watches validation loss and stops training once it has failed to improve for a set number of epochs (the patience). It also remembers which epoch was best, so you can restore those weights. An epoch only counts as an improvement if it beats the best loss by more than min_delta. Worked example: losses [1.0, 0.9, 0.95, 0.85, 0.9, 0.92], patience 2, min_delta 0. Epoch 0 sets best 1.0. Epoch 1 improves (best 0.9, wait 0). Epoch 2 does not (wait 1). Epoch 3 improves to 0.85 (wait resets to 0). Epochs 4 and 5 do not, so wait reaches 2 at epoch 5. Answer (5, 3). With min_delta 0.1, epoch 1 needs loss < 0.9, which fails, so wait hits 2 at epoch 2 and the answer is (2, 0). Rule: improvement if loss < best - min_delta, then set best and reset wait to 0; otherwise add 1 to wait; stop when wait equals patience; if it never does, stop_epoch is the last index. Used in: almost every training loop, including fine-tuning runs.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks all 4.

  • Sample 1: exampleearly_stop([1.0, 0.8, 0.85, 0.9], 2)
  • Sample 2: never stopsearly_stop([3, 2, 1, 0.5], 1)
  • Test 3: min deltaearly_stop([1.0, 0.95, 0.94, 0.93, 0.5], 3, 0.1)
  • Test 4: recoversearly_stop([1.0, 1.1, 0.9, 1.0, 0.8, 1.2, 1.3], 2)