跳至内容

回调

回调

Ultralytics 框架支持将回调作为 train、val、export 和 predict 模式战略阶段的入口点。每个回调都接受一个 Trainer, ValidatorPredictor 对象,具体取决于操作类型。这些对象的所有属性都可以在文档的 "参考 "部分找到。



观看: 掌握Ultralytics YOLOv8 :回调

实例

通过预测返回更多信息

在本例中,我们希望在每个结果对象中返回原始帧。我们可以这样做

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("yolov8n.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

所有回调

以下是所有支持的回调。更多详情请查看回调源代码

培训师回电

回调 说明
on_pretrain_routine_start 在训练前程序开始时触发
on_pretrain_routine_end 在训练前的例行训练结束时触发
on_train_start 培训开始时触发
on_train_epoch_start 在每个训练期开始时触发
on_train_batch_start 在每批训练开始时触发
optimizer_step 在优化步骤中触发
on_before_zero_grad 梯度归零前触发
on_train_batch_end 在每批训练结束时触发
on_train_epoch_end 在每个训练周期结束时触发
on_fit_epoch_end 在每个拟合纪元结束时触发
on_model_save 保存模型时触发
on_train_end 训练过程结束时触发
on_params_update 模型参数更新时触发
teardown 在清理训练过程时触发

验证器回调

回调 说明
on_val_start 验证开始时触发
on_val_batch_start 在每个验证批次开始时触发
on_val_batch_end 在每个验证批次结束时触发
on_val_end 验证结束时触发

预测器回调

回调 说明
on_predict_start 预测过程开始时触发
on_predict_batch_start 在每批预测开始时触发
on_predict_postprocess_end 预测后处理结束时触发
on_predict_batch_end 在每批预测结束时触发
on_predict_end 预测过程结束时触发

出口回调

回调 说明
on_export_start 出口程序启动时触发
on_export_end 输出过程结束时触发

常见问题

什么是Ultralytics 回调,如何使用?

Ultralytics 回调 是在模型运行的关键阶段(如训练、验证、输出和预测)触发的专门入口点。这些回调允许在流程中的特定点实现自定义功能,从而增强和修改工作流程。每个回调都接受一个 Trainer, ValidatorPredictor 对象,具体取决于操作类型。有关这些对象的详细属性,请参阅 参考章节.

要使用回调,可以定义一个函数,然后用 add_callback 方法。下面是一个如何在预测过程中返回附加信息的示例:

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

如何使用回调自定义Ultralytics 训练程序?

Ultralytics Ultralytics YOLO 提供多种训练回调,例如 on_train_start, on_train_endon_train_batch_end.这些功能允许您添加自定义指标、处理或日志。

下面举例说明如何在每次训练结束时记录附加指标:

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("yolov8n.pt")
model.add_callback("on_train_epoch_end", on_train_epoch_end)
model.train(data="coco.yaml", epochs=10)

有关如何有效使用培训回调的详细信息,请参阅《培训指南》

为什么要在Ultralytics YOLO 验证过程中使用回调?

使用 验证期间的回调 Ultralytics YOLO 中的 "回调 "可以通过自定义处理、日志记录或指标计算来增强模型评估。回调,如 on_val_start, on_val_batch_endon_val_end 提供注入自定义逻辑的入口点,确保详细而全面的验证流程。

例如,您可能希望记录额外的验证指标或保存中间结果以作进一步分析。下面举例说明如何在验证结束时记录自定义指标:

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("yolov8n.pt")
model.add_callback("on_val_end", on_val_end)
model.val(data="coco.yaml")

查看《验证指南》,进一步了解如何将回调纳入验证流程。

如何在Ultralytics YOLO 中为预测模式附加自定义回调?

要为 预测模式 Ultralytics YOLO 中,定义一个回调函数并将其注册到预测流程中。常见的预测回调包括 on_predict_start, on_predict_batch_endon_predict_end.这些功能允许修改预测输出,并集成数据记录或结果转换等附加功能。

下面是一个使用自定义回调来记录预测结果的示例:

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("yolov8n.pt")
model.add_callback("on_predict_end", on_predict_end)
results = model.predict(source="image.jpg")

如需更全面的使用方法,请参阅《预测指南》,其中包括详细说明和其他自定义选项。

Ultralytics YOLO 中使用回调的实例有哪些?

Ultralytics YOLO 支持各种实用的回调实现,以增强和定制训练、验证和预测等不同阶段。一些实际例子包括

  1. 记录自定义指标:在不同阶段(如训练或验证历元结束时)记录附加指标。
  2. 数据增强:在预测或训练批次中实施自定义数据转换或增强。
  3. 中间结果:保存中间结果,如预测或框架,以便进一步分析或可视化。

举例说明:在预测过程中将帧与预测结果结合使用 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("yolov8n.pt")
model.add_callback("on_predict_batch_end", on_predict_batch_end)
for result, frame in model.predict():
    pass

查看《完整回调参考》,了解更多选项和示例。



创建于 2023-11-12,更新于 2024-07-04
作者:glenn-jocher(9),RizwanMunawar(1),Laughing-q(1)

评论