回调函数
Ultralytics 框架支持回调函数,这些回调函数在训练过程的关键阶段作为入口点。 train
, val
, export
和 predict
模式。每个回调都接受一个 Trainer
, Validator
或 Predictor
对象,具体取决于操作类型。这些对象的所有属性都在 参考章节 文档的。
观看: 如何使用 Ultralytics Callbacks | 预测、训练、验证和导出 Callbacks | 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_model_save
回调函数
此示例展示了如何在保存检查点后检索训练详细信息,例如 best_fitness 分数、total_loss 和其他指标,使用 on_model_save
回调函数。
from ultralytics import YOLO
# Load a YOLO model
model = YOLO("yolo11n.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)
所有回调
以下是所有支持的回调。有关更多详细信息,请参阅回调源代码。
培训师回电
回调函数 | 描述 |
---|---|
on_pretrain_routine_start |
在预训练程序开始时触发。 |
on_pretrain_routine_end |
在预训练程序结束时触发。 |
on_train_start |
在训练开始时触发。 |
on_train_epoch_start |
在每个训练 epoch 开始时触发。 |
on_train_batch_start |
在每个训练批次开始时触发。 |
optimizer_step |
在优化器步骤中触发。 |
on_before_zero_grad |
在梯度归零之前触发。 |
on_train_batch_end |
在每个训练批次结束时触发。 |
on_train_epoch_end |
在每个训练 epoch 结束时触发。 |
on_fit_epoch_end |
在每个拟合 epoch 结束时触发。 |
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
, Validator
或 Predictor
对象,具体取决于操作类型。有关这些对象的详细属性,请参阅 参考章节.
要使用回调,请定义一个函数并使用以下代码将其添加到模型中 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_end
和 on_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_end
和 on_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_end
和 on_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
浏览回调源代码,了解更多选项和示例。