YOLO Vision 2026:

Geri Çağırmalar (Callbacks)#

Ultralytics framework supports callbacks, which serve as entry points at strategic stages during the 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 are detailed in the Reference section of the documentation.



Watch: How to use Ultralytics Callbacks | Predict, Train, Validate and Export Callbacks | Ultralytics YOLO🚀

Örnekler#

Tahmin ile Ek Bilgi Döndürme#

Bu örnekte, her bir sonuç nesnesiyle birlikte orijinal kareyi (frame) nasıl döndüreceğimizi gösteriyoruz:

from ultralytics import YOLO

def on_predict_batch_end(predictor):
    """Combine prediction results with corresponding frames."""
    _, 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("yolo26n.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

Access Model metrics using the on_model_save callback#

This example shows how to retrieve training details, such as the best_fitness score, total_loss, and other metrics after a checkpoint is saved using the on_model_save callback.

from ultralytics import YOLO

# Load a YOLO model
model = YOLO("yolo26n.pt")

def print_checkpoint_metrics(trainer):
    """Print trainer metrics and loss details after each checkpoint is saved."""
    print(
        f"Model details\n"
        f"Best fitness: {trainer.best_fitness}, "
        f"Loss names: {trainer.loss_names}, "  # List of loss names
        f"Metrics: {trainer.metrics}, "
        f"Total loss: {trainer.tloss}"  # Total loss value
    )

if __name__ == "__main__":
    # Add on_model_save callback.
    model.add_callback("on_model_save", print_checkpoint_metrics)

    # Run model training on custom dataset.
    results = model.train(data="coco8.yaml", epochs=3)

Tüm Geri Çağırmalar#

Below are all the supported callbacks. For more details, refer to the callbacks source code.

Eğitmen (Trainer) Geri Çağırmaları#

Geri ÇağırmaAçıklama
on_pretrain_routine_startÖn eğitim rutininden önce, veri yükleme ve model kurulumundan önce tetiklenir.
on_pretrain_routine_endÖn eğitim rutininden sonra, veri yükleme ve model kurulumu tamamlandıktan sonra tetiklenir.
on_train_startTriggered when the training starts, before the first epoch begins.
on_train_epoch_startTriggered at the start of each training epoch, before batch iteration begins.
on_train_batch_startHer eğitim yığınının başlangıcında, ileri geçişten (forward pass) önce tetiklenir.
optimizer_stepİyileştirici (optimizer) adımı sırasında tetiklenir. Özel entegrasyonlar için ayrılmıştır; varsayılan eğitim döngüsü tarafından çağrılmaz.
on_before_zero_gradGradyanlar sıfırlanmadan önce tetiklenir. Özel entegrasyonlar için ayrılmıştır; varsayılan eğitim döngüsü tarafından çağrılmaz.
on_train_batch_endHer eğitim yığınının sonunda, geri geçişten (backward pass) sonra tetiklenir. İyileştirici adımı, gradyan birikimi nedeniyle ertelenebilir.
on_train_epoch_endHer eğitim epochunun sonunda, tüm yığınlar işlendikten sonra ancak doğrulama (validation) öncesinde tetiklenir. Doğrulama metrikleri ve uygunluk (fitness) henüz mevcut olmayabilir.
on_model_saveModel kontrol noktası kaydedildiğinde, doğrulamadan sonra tetiklenir.
on_fit_epoch_endHer uyum (fit) epochunun (eğitim + doğrulama) sonunda, doğrulamadan ve herhangi bir kontrol noktası kaydından sonra tetiklenir. Doğrulama metrikleri ve uygunluk, epoch bazlı eğitim çağrısı için mevcuttur. Bu geri çağırma aynı zamanda, hiçbir kontrol noktası kaydının gerçekleşmediği ve uygunluğun mevcut olmayabileceği nihai en iyi model değerlendirmesi sırasında da çağrılır.
on_train_endEğitim süreci sona erdiğinde, en iyi modelin nihai değerlendirmesinden sonra tetiklenir.
on_params_updateModel parametreleri güncellendiğinde tetiklenir. Özel entegrasyonlar için ayrılmıştır; varsayılan eğitim döngüsü tarafından çağrılmaz.
teardownEğitim süreci temizlenirken tetiklenir.

Doğrulayıcı (Validator) Geri Çağırmaları#

Geri ÇağırmaAçıklama
on_val_startDoğrulama başladığında tetiklenir.
on_val_batch_startHer doğrulama yığınının başlangıcında tetiklenir.
on_val_batch_endHer doğrulama yığınının sonunda tetiklenir.
on_val_endDoğrulama sona erdiğinde tetiklenir.

Tahminci (Predictor) Geri Çağırmaları#

Geri ÇağırmaAçıklama
on_predict_startTahmin süreci başladığında tetiklenir.
on_predict_batch_startHer tahmin yığınının başlangıcında tetiklenir.
on_predict_postprocess_endTahmin sonrası işlemlerin (post-processing) sonunda tetiklenir.
on_predict_batch_endHer tahmin yığınının sonunda tetiklenir.
on_predict_endTahmin süreci sona erdiğinde tetiklenir.

Dışa Aktarıcı (Exporter) Geri Çağırmaları#

Geri ÇağırmaAçıklama
on_export_startDışa aktarma süreci başladığında tetiklenir.
on_export_endDışa aktarma süreci sona erdiğinde tetiklenir.

SSS#

  • Ultralytics callbacks are specialized entry points that are triggered during key stages of model operations such as training, validation, exporting, and prediction. These callbacks enable custom functionality at specific points in the process, allowing for 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, define a function and add it to the model using the model.add_callback() method. Here is an example of returning 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("yolo26n.pt")
    model.add_callback("on_predict_batch_end", on_predict_batch_end)
    for result, frame in model.predict():
        pass
  • Customize your Ultralytics training routine by injecting 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, which allow you to add custom metrics, processing, or logging.

    Geri çağırmalarla katmanları dondururken BatchNorm istatistiklerini dondurmanın yolu budur:

    from ultralytics import YOLO
    
    # Add a callback to put the frozen layers in eval mode to prevent BN values from changing
    def put_in_eval_mode(trainer):
        n_layers = trainer.args.freeze
        if not isinstance(n_layers, int):
            return
    
        for i, (name, module) in enumerate(trainer.model.named_modules()):
            if name.endswith("bn") and int(name.split(".")[1]) < n_layers:
                module.eval()
                module.track_running_stats = False
    
    model = YOLO("yolo26n.pt")
    model.add_callback("on_train_epoch_start", put_in_eval_mode)
    model.train(data="coco.yaml", epochs=10)

    For more details on effectively using training callbacks, see the Training Guide.

  • Using callbacks during validation in Ultralytics YOLO enhances model evaluation by enabling custom processing, logging, or metrics calculation. Callbacks like on_val_start, on_val_batch_end, and on_val_end provide entry points to inject custom logic, ensuring detailed and comprehensive validation processes.

    Örneğin, sadece ilk üç yığın yerine tüm doğrulama yığınlarını çizdirmek için:

    import inspect
    
    from ultralytics import YOLO
    
    def plot_samples(validator):
        frame = inspect.currentframe().f_back.f_back
        v = frame.f_locals
        validator.plot_val_samples(v["batch"], v["batch_i"])
        validator.plot_predictions(v["batch"], v["preds"], v["batch_i"])
    
    model = YOLO("yolo26n.pt")
    model.add_callback("on_val_batch_end", plot_samples)
    model.val(data="coco.yaml")

    For more insights on incorporating callbacks into your validation process, see the Validation Guide.

  • To attach a custom callback for prediction mode in Ultralytics YOLO, 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 the modification of prediction outputs and the integration of additional functionalities, like data logging or result transformation.

    İşte belirli bir sınıfa ait bir nesnenin bulunup bulunmadığına bağlı olarak tahminleri kaydeden özel bir geri çağırma örneği:

    from ultralytics import YOLO
    
    model = YOLO("yolo26n.pt")
    
    class_id = 2
    
    def save_on_object(predictor):
        r = predictor.results[0]
        if class_id in r.boxes.cls:
            predictor.args.save = True
        else:
            predictor.args.save = False
    
    model.add_callback("on_predict_postprocess_end", save_on_object)
    results_stream = model("pedestrians.mp4", stream=True, save=True)
    
    for result in results_stream:
        pass

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

  • Ultralytics YOLO, eğitim, doğrulama ve tahmin gibi farklı aşamaları geliştirmek ve özelleştirmek için çeşitli pratik geri çağırma uygulamalarını destekler. Bazı pratik örnekler şunlardır:

    • Logging Custom Metrics: Log additional metrics at different stages, such as at the end of training or validation epochs.
    • Data Augmentation: Implement custom data transformations or augmentations during prediction or training batches.
    • Ara Sonuçlar: Daha fazla analiz veya görselleştirme için tahminler veya kareler gibi ara sonuçları kaydet.

    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("yolo26n.pt")
    model.add_callback("on_predict_batch_end", on_predict_batch_end)
    for result, frame in model.predict():
        pass

    Explore the callback source code for more options and examples.

Yorumlar