跳至内容

回调

Ultralytics 框架支持回调,回调可作为运行过程中战略阶段的切入点。 train, val, exportpredict 模式。每个回调都接受一个 Trainer, ValidatorPredictor 对象,具体取决于操作类型。这些对象的所有属性在 参考章节 的文件。



观看: 掌握Ultralytics YOLO :回调

实例

返回预测的附加信息

在本例中,我们将演示如何在返回每个结果对象的同时返回原始帧:

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

所有回调

以下是所有支持的回调。有关详细信息,请参阅回调源代码

培训师回电

回调 说明
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 对象,具体取决于操作类型。有关这些对象的详细属性,请参阅 参考章节.

要使用回调,请定义一个函数并使用 model.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("yolo11n.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可以添加自定义指标、处理或日志。

下面介绍在使用回调冻结图层时如何冻结 BatchNorm 统计:

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

有关有效使用培训回调的更多详情,请参阅《培训指南》

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

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

例如,绘制所有验证批次而不只是前三个批次:

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

有关将回调纳入验证流程的更多信息,请参阅《验证指南》

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

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

下面是一个例子,自定义回调根据是否存在特定类的对象来保存预测结果:

from ultralytics import YOLO

model = YOLO("yolo11n.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 = model("pedestrians.mp4", stream=True, save=True)

for results in results:
    pass

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

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

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

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

举例说明:在预测过程中将帧与预测结果结合使用 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

查看回调源代码,了解更多选项和示例。

📅创建于 1 年前 ✏️已更新 9 天前

评论