Join Our 5-Week ML/AI Engineer Interview Bootcamp 🚀 led by ML Tech Leads at FAANGs

Back to Questions

203. Early stopping criterion

easy
GeneralGeneral
senior

Design an early stopping check that decides when to halt training based on validation loss over epochs. You’ll implement a small utility that returns the first epoch where training should stop and the epoch with the best validation loss.

An epoch (t) is considered an improvement if:

Lt<mini<t(Li)δL_t < \min_{i < t}(L_i) - \delta

Requirements

Implement the function:

python

Rules:

  • Track the best (lowest) validation loss seen so far and its epoch index.
  • An epoch is “improving” only if it beats the best loss by at least min_delta.
  • Early stopping triggers when you see patience consecutive epochs without improvement.
  • Return stop_epoch as the epoch where the patience counter first reaches patience.
  • Use NumPy for input type, but basic Python iteration is sufficient.

Example

python

Output:

python
Input Signature
ArgumentType
patienceint
min_deltafloat
val_lossesnp.ndarray
Output Signature
Return NameType
valuetuple

Constraints

  • Single pass over val_losses (O(n))

  • Use NumPy arrays for input

  • Return (-1, best_epoch) if never stops

Hint 1

Keep three variables while scanning epochs: best_loss, best_epoch, and no_improve (consecutive non-improvements).

Hint 2

An epoch counts as improvement only if loss < best_loss - min_delta; on improvement reset no_improve = 0, otherwise increment it.

Hint 3

Early stopping triggers the first epoch where no_improve reaches patience; set stop_epoch = current_epoch and break. Track best_epoch as the earliest minimum.

Roles
ML Engineer
AI Engineer
Companies
GeneralGeneral
Levels
senior
entry
Tags
early-stopping
patience-min-delta
time-series-scan
training-loop-utilities
39 people are solving this problem
Python LogoPython Editor
Ln 1, Col 1

Input Arguments

Edit values below to test with custom inputs

You need tolog in/sign upto run or submit