Simulate reduce-learning-rate-on-plateau

Why it matters ReduceLROnPlateau is one of the most used schedulers in Keras and PyTorch for fine-tuning.

When validation loss stops improving, many trainers cut the learning rate instead of stopping.

Write plateau_lrs(val_losses, lr, factor, patience, min_lr=0.0). Keep best = infinity and bad = 0. After each epoch's loss: if loss < best, set best = loss and bad = 0; otherwise bad += 1. If bad > patience, set lr = max(lr * factor, min_lr) and bad = 0. Return the list of learning rates in effect after each epoch.

Signaturedef plateau_lrs(val_losses, lr, factor, patience, min_lr=0.0)

Example

plateau_lrs([1.0, 0.9, 0.95, 0.96, 0.97], 0.1, 0.5, 1) is [0.1, 0.1, 0.1, 0.05, 0.05].

Understand the idea

If the loss has not improved for a while, the steps are probably too big to settle into the valley, so we halve them and try again. It is like slowing down when you keep overshooting a turn.

Tiny example: patience 1, factor 0.5, lr 0.1. Losses 1.0 (best), 0.9 (best), 0.95 (bad = 1, not more than 1), 0.96 (bad = 2, more than patience, so lr becomes 0.05 and bad resets), 0.97 (bad = 1). Result [0.1, 0.1, 0.1, 0.05, 0.05].

Rule: if loss < best then best = loss, bad = 0 else bad += 1; if bad > patience then lr = max(lr * factor, min_lr), bad = 0.

Fine-tuning scripts for image classifiers and many tabular deep models use this when no fixed schedule is known in advance.

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

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

  • Sample 1: exampleplateau_lrs([1.0, 0.9, 0.95, 0.96, 0.97], 0.1, 0.5, 1)
  • Sample 2: min lr floorplateau_lrs([1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0], 1.0, 0.1, 0, 0.005)
  • Test 3: improves againplateau_lrs([3.0, 2.0, 2.5, 2.4, 1.0, 1.5, 1.6, 1.7], 0.2, 0.5, 2)