🚀 LEVEL UP TO SENIOR:Unlock 500+ Advanced Practical Challenges & Exercises.
🎓 COURSERA PARTNER:Earn professional Google, Meta, and IBM certificates to supercharge your resume.
REFERENCEtensorflow

tensorflow Documentation

LOADING ENGINE...

callbacks.EarlyStopping()

AI & DATA SCIENCE // callbacks-earlystopping

tf.keras.callbacks.EarlyStopping() stops training automatically once a monitored metric, like validation loss, stops improving for a set number of epochs.

Syntax

tf.keras.callbacks.EarlyStopping(monitor='val_loss', patience=0)

Deep Dive Course

EarlyStopping watches a chosen metric, most commonly val_loss, after every epoch, and halts training once that metric fails to improve for patience consecutive epochs, preventing wasted computation and helping avoid the overfitting that tends to happen if training continues well past the point where validation performance peaks. Passing restore_best_weights=True additionally rolls the model's weights back to whichever epoch achieved the best monitored value, rather than leaving it at whatever weights existed when training actually stopped, several epochs after the true best point.

1Understanding callbacks.EarlyStopping()

EarlyStopping watches a chosen metric, most commonly val_loss, after every epoch, and halts training once that metric fails to improve for patience consecutive epochs, preventing wasted computation and helping avoid the overfitting that tends to happen if training continues well past the point where validation performance peaks. Passing restore_best_weights=True additionally rolls the model's weights back to whichever epoch achieved the best monitored value, rather than leaving it at whatever weights existed when training actually stopped, several epochs after the true best point.

💡

Always pass restore_best_weights=True alongside EarlyStopping — without it, training stops patience epochs after the best result, but the model is left with those later, already-degrading weights rather than the genuinely best ones seen during training.

editor.html
import tensorflow as tf

callback = tf.keras.callbacks.EarlyStopping(monitor='val_loss', patience=3, restore_best_weights=True)
print(callback.patience)
localhost:3000

2Practical Example

Here is a real-world application of callbacks.EarlyStopping() showing how it is used in production TensorFlow code.

editor.html
import tensorflow as tf
from tensorflow.keras import layers, Sequential
import numpy as np

model = Sequential([layers.Dense(1, input_shape=(1,))])
model.compile(optimizer='sgd', loss='mse')
callback = tf.keras.callbacks.EarlyStopping(monitor='loss', patience=2)
x, y = np.array([1, 2, 3, 4]), np.array([2, 4, 6, 8])
history = model.fit(x, y, epochs=100, callbacks=[callback], verbose=0)
print(len(history.history['loss']) <= 100)
localhost:3000

3Best Practices

Follow these guidelines when working with callbacks.EarlyStopping():

1. Pass restore_best_weights=True so the final model uses the weights from its best epoch, not whatever epoch training happened to stop on

2. Monitor val_loss, or a validation metric, rather than a training metric, since the goal is to detect when the model stops generalizing better, not just fitting the training data better

3. Set patience high enough to tolerate normal epoch-to-epoch noise in validation performance, rather than stopping prematurely on a single bad epoch

⚠️

Tip: Always pass restore_best_weights=True alongside EarlyStopping — without it, training stops patience epochs after the best result, but the model is left with those later, already-degrading weights rather than the genuinely best ones seen during training.

editor.html
import tensorflow as tf

callback = tf.keras.callbacks.EarlyStopping(monitor='val_loss', patience=3, restore_best_weights=True)
print(callback.patience)
localhost:3000

Examples

Example 01Basic Usage
import tensorflow as tf

callback = tf.keras.callbacks.EarlyStopping(monitor='val_loss', patience=3, restore_best_weights=True)
print(callback.patience)
Example 02Advanced Example
import tensorflow as tf
from tensorflow.keras import layers, Sequential
import numpy as np

model = Sequential([layers.Dense(1, input_shape=(1,))])
model.compile(optimizer='sgd', loss='mse')
callback = tf.keras.callbacks.EarlyStopping(monitor='loss', patience=2)
x, y = np.array([1, 2, 3, 4]), np.array([2, 4, 6, 8])
history = model.fit(x, y, epochs=100, callbacks=[callback], verbose=0)
print(len(history.history['loss']) <= 100)

Best Practices

  • Pass restore_best_weights=True so the final model uses the weights from its best epoch, not whatever epoch training happened to stop on
  • Monitor val_loss, or a validation metric, rather than a training metric, since the goal is to detect when the model stops generalizing better, not just fitting the training data better
  • Set patience high enough to tolerate normal epoch-to-epoch noise in validation performance, rather than stopping prematurely on a single bad epoch

Interview Question

Why is restore_best_weights=True considered essential when using EarlyStopping, rather than an optional nice-to-have?

Hint: Think about which epoch's weights the model is actually left holding once EarlyStopping decides to halt training.

EarlyStopping only detects that the monitored metric has stopped improving after it's already failed to improve for patience full epochs in a row, which means by the time training actually halts, the model has already trained patience epochs past its genuinely best point, and its current weights reflect that later, already-degrading state, not the best one observed. Without restore_best_weights=True, you end up keeping precisely the wrong epoch's weights, the ones from right when training stopped, rather than the ones that actually achieved the best validation performance somewhere earlier in that patience window. Setting restore_best_weights=True fixes this by having EarlyStopping keep track of the weights from the actual best epoch throughout training, and rolling the model back to exactly those weights once it decides to stop, ensuring you genuinely end up with the best model observed rather than a slightly-overfit later version of it.

Exercises

MediumPractice using callbacks.EarlyStopping() in a real scenario.
View Solution
import tensorflow as tf

callback = tf.keras.callbacks.EarlyStopping(monitor='val_loss', patience=3, restore_best_weights=True)
print(callback.patience)

Frequently Asked Questions

Why is restore_best_weights=True considered essential when using EarlyStopping, rather than an optional nice-to-have?

EarlyStopping only detects that the monitored metric has stopped improving after it's already failed to improve for patience full epochs in a row, which means by the time training actually halts, the model has already trained patience epochs past its genuinely best point, and its current weights reflect that later, already-degrading state, not the best one observed. Without restore_best_weights=True, you end up keeping precisely the wrong epoch's weights, the ones from right when training stopped, rather than the ones that actually achieved the best validation performance somewhere earlier in that patience window. Setting restore_best_weights=True fixes this by having EarlyStopping keep track of the weights from the actual best epoch throughout training, and rolling the model back to exactly those weights once it decides to stop, ensuring you genuinely end up with the best model observed rather than a slightly-overfit later version of it.

Related Functions

callbacks-modelcheckpointmodel-fitmodel-evaluate