Introduction
Custom callbacks let you add your own actions during model training, like stopping early or saving progress.
class MyCallback(tf.keras.callbacks.Callback): def on_epoch_end(self, epoch, logs=None): # Your code here pass model.fit(x_train, y_train, epochs=5, callbacks=[MyCallback()])
class PrintEpochCallback(tf.keras.callbacks.Callback): def on_epoch_end(self, epoch, logs=None): print(f"Finished epoch {epoch + 1}")
class StopIfLossLow(tf.keras.callbacks.Callback): def on_epoch_end(self, epoch, logs=None): if logs.get('loss') < 0.1: print('Loss is low, stopping training') self.model.stop_training = True
import tensorflow as tf import numpy as np # Create simple data x_train = np.array([[1], [2], [3], [4]], dtype=float) y_train = np.array([[2], [4], [6], [8]], dtype=float) # Define a simple model model = tf.keras.Sequential([ tf.keras.layers.Dense(1, input_shape=(1,)) ]) model.compile(optimizer='sgd', loss='mean_squared_error') # Custom callback to stop if loss < 0.01 class StopIfLossLow(tf.keras.callbacks.Callback): def on_epoch_end(self, epoch, logs=None): loss = logs.get('loss') print(f"Epoch {epoch + 1}, loss: {loss:.4f}") if loss is not None and loss < 0.01: print('Loss is low, stopping training') self.model.stop_training = True # Train model with callback model.fit(x_train, y_train, epochs=20, callbacks=[StopIfLossLow()])
import tensorflow as tf
class MyCallback(tf.keras.callbacks.Callback):
def on_epoch_end(self, epoch, logs=None):
print(f"Epoch {epoch+1} ended with loss {logs['loss']:.2f}")
model = tf.keras.Sequential([tf.keras.layers.Dense(1)])
model.compile(optimizer='sgd', loss='mse')
model.fit([[1.0]], [[2.0]], epochs=2, callbacks=[MyCallback()])class StopCallback(tf.keras.callbacks.Callback):
def on_epoch_end(self, epoch, logs=None):
if logs['loss'] < 0.1:
self.model.stop_training = True
model.fit(x_train, y_train, epochs=10, callbacks=[StopCallback()])Pass the test and this pattern moves unknown