Skip to content

Callbacks

Callbacks

Ultralytics framework supports callbacks as entry points in strategic stages of train, val, export, and predict modes. Each callback accepts a Trainer, Validator, or Predictor object depending on the operation type. All properties of these objects can be found in Reference section of the docs.



Watch: Mastering Ultralytics YOLO: Callbacks

Examples

Returning additional information with Prediction

In this example, we want to return the original frame with each result object. Here's how we can do that

from ultralytics import YOLO


def on_predict_batch_end(predictor):
    """Handle prediction batch end by combining results with corresponding frames; modifies predictor results."""
    _, image, _, _ = predictor.batch

    # Ensure that image is a list
    image = image if isinstance(image, list) else [image]

    # Combine the prediction results with the corresponding frames
    predictor.results = zip(predictor.results, image)


# Create a YOLO model instance
model = YOLO("yolo11n.pt")

# Add the custom callback to the model
model.add_callback("on_predict_batch_end", on_predict_batch_end)

# Iterate through the results and frames
for result, frame in model.predict():  # or model.track()
    pass

All callbacks

Here are all supported callbacks. See callbacks source code for additional details.

Trainer Callbacks

CallbackDescription
on_pretrain_routine_startTriggered at the beginning of pre-training routine
on_pretrain_routine_endTriggered at the end of pre-training routine
on_train_startTriggered when the training starts
on_train_epoch_startTriggered at the start of each training epoch
on_train_batch_startTriggered at the start of each training batch
optimizer_stepTriggered during the optimizer step
on_before_zero_gradTriggered before gradients are zeroed
on_train_batch_endTriggered at the end of each training batch
on_train_epoch_endTriggered at the end of each training epoch
on_fit_epoch_endTriggered at the end of each fit epoch
on_model_saveTriggered when the model is saved
on_train_endTriggered when the training process ends
on_params_updateTriggered when model parameters are updated
teardownTriggered when the training process is being cleaned up

Validator Callbacks

CallbackDescription
on_val_startTriggered when the validation starts
on_val_batch_startTriggered at the start of each validation batch
on_val_batch_endTriggered at the end of each validation batch
on_val_endTriggered when the validation ends

Predictor Callbacks

CallbackDescription
on_predict_startTriggered when the prediction process starts
on_predict_batch_startTriggered at the start of each prediction batch
on_predict_postprocess_endTriggered at the end of prediction postprocessing
on_predict_batch_endTriggered at the end of each prediction batch
on_predict_endTriggered when the prediction process ends

Exporter Callbacks

CallbackDescription
on_export_startTriggered when the export process starts
on_export_endTriggered when the export process ends

FAQ

What are Ultralytics callbacks and how can I use them?

Ultralytics callbacks are specialized entry points triggered during key stages of model operations like training, validation, exporting, and prediction. These callbacks allow for custom functionality at specific points in the process, enabling enhancements and modifications to the workflow. Each callback accepts a Trainer, Validator, or Predictor object, depending on the operation type. For detailed properties of these objects, refer to the Reference section.

To use a callback, you can define a function and then add it to the model with the add_callback method. Here's an example of how to return additional information during prediction:

from ultralytics import YOLO


def on_predict_batch_end(predictor):
    """Handle prediction batch end by combining results with corresponding frames; modifies predictor results."""
    _, image, _, _ = predictor.batch
    image = image if isinstance(image, list) else [image]
    predictor.results = zip(predictor.results, image)


model = YOLO("yolo11n.pt")
model.add_callback("on_predict_batch_end", on_predict_batch_end)
for result, frame in model.predict():
    pass

How can I customize Ultralytics training routine using callbacks?

To customize your Ultralytics training routine using callbacks, you can inject your logic at specific stages of the training process. Ultralytics YOLO provides a variety of training callbacks such as on_train_start, on_train_end, and on_train_batch_end. These allow you to add custom metrics, processing, or logging.

Here's an example of how to log additional metrics at the end of each training epoch:

from ultralytics import YOLO


def on_train_epoch_end(trainer):
    """Custom logic for additional metrics logging at the end of each training epoch."""
    additional_metric = compute_additional_metric(trainer)
    trainer.log({"additional_metric": additional_metric})


model = YOLO("yolo11n.pt")
model.add_callback("on_train_epoch_end", on_train_epoch_end)
model.train(data="coco.yaml", epochs=10)

Refer to the Training Guide for more details on how to effectively use training callbacks.

Why should I use callbacks during validation in Ultralytics YOLO?

Using callbacks during validation in Ultralytics YOLO can enhance model evaluation by allowing custom processing, logging, or metrics calculation. Callbacks such as on_val_start, on_val_batch_end, and on_val_end provide entry points to inject custom logic, ensuring detailed and comprehensive validation processes.

For instance, you might want to log additional validation metrics or save intermediate results for further analysis. Here's an example of how to log custom metrics at the end of validation:

from ultralytics import YOLO


def on_val_end(validator):
    """Log custom metrics at end of validation."""
    custom_metric = compute_custom_metric(validator)
    validator.log({"custom_metric": custom_metric})


model = YOLO("yolo11n.pt")
model.add_callback("on_val_end", on_val_end)
model.val(data="coco.yaml")

Check out the Validation Guide for further insights on incorporating callbacks into your validation process.

How do I attach a custom callback for the prediction mode in Ultralytics YOLO?

To attach a custom callback for the prediction mode in Ultralytics YOLO, you define a callback function and register it with the prediction process. Common prediction callbacks include on_predict_start, on_predict_batch_end, and on_predict_end. These allow for modification of prediction outputs and integration of additional functionalities like data logging or result transformation.

Here is an example where a custom callback is used to log predictions:

from ultralytics import YOLO


def on_predict_end(predictor):
    """Log predictions at the end of prediction."""
    for result in predictor.results:
        log_prediction(result)


model = YOLO("yolo11n.pt")
model.add_callback("on_predict_end", on_predict_end)
results = model.predict(source="image.jpg")

For more comprehensive usage, refer to the Prediction Guide which includes detailed instructions and additional customization options.

What are some practical examples of using callbacks in Ultralytics YOLO?

Ultralytics YOLO supports various practical implementations of callbacks to enhance and customize different phases like training, validation, and prediction. Some practical examples include:

  1. Logging Custom Metrics: Log additional metrics at different stages, such as the end of training or validation epochs.
  2. Data Augmentation: Implement custom data transformations or augmentations during prediction or training batches.
  3. Intermediate Results: Save intermediate results such as predictions or frames for further analysis or visualization.

Example: Combining frames with prediction results during prediction using on_predict_batch_end:

from ultralytics import YOLO


def on_predict_batch_end(predictor):
    """Combine prediction results with frames."""
    _, image, _, _ = predictor.batch
    image = image if isinstance(image, list) else [image]
    predictor.results = zip(predictor.results, image)


model = YOLO("yolo11n.pt")
model.add_callback("on_predict_batch_end", on_predict_batch_end)
for result, frame in model.predict():
    pass

Explore the Complete Callback Reference to find more options and examples.

📅 Created 1 year ago ✏️ Updated 1 month ago

Comments