Callback
了解回调(callbacks)如何优化 Ultralytics YOLO26 的训练。学习实现提前停止、检查点和自定义日志记录,以增强你的 AI 工作流。
在软件工程和 人工智能 (AI) 领域,回调 (callback) 是一段可执行代码,作为参数传递给其他代码,然后预期在给定时间执行(回调)该参数。在 深度学习 (DL) 框架的具体上下文中,回调是必不可少的工具,允许开发者自定义 模型训练 循环的行为,而无需修改核心训练代码本身。它们充当自动触发器,在训练过程的各个阶段(例如 轮次 (epoch) 的开始或结束、训练批次或整个训练会话)执行特定操作。
回调在机器学习中的作用#
训练一个复杂的 神经网络 可能需要数小时甚至数天。如果没有回调,训练过程本质上是一个运行到完成的“黑盒”,通常需要人工监督。回调引入了可观察性和控制力,允许系统根据实时性能指标进行自我调节。
When using high-level libraries like PyTorch or TensorFlow, callbacks provide a way to inject logic into the optimization algorithm. For instance, if a model is learning well, a callback might save the current state; if it stops learning, a callback might halt the process to save resources. This makes the machine learning (ML) workflow more efficient and robust.
常见应用与实际案例#
回调具有多功能性,可用于 模型监控 和优化过程中的各种任务。
- **早停 (Early Stopping):**最常见的用途之一是 早停。该回调监控特定指标,例如 验证数据 损失。如果损失在设定的轮次内停止下降,回调就会中止训练。这可以防止 过拟合,确保模型能够很好地泛化到新数据,而不是简单地记住 训练数据。
- **模型检查点 (Model Checkpointing):**在长时间的训练运行中,硬件故障可能是灾难性的。检查点回调会定期(例如每轮)或仅当模型在诸如 准确率 或 平均精度均值 (mAP) 等指标上取得新的“最佳”得分时,保存 模型权重。这确保你始终拥有表现最好的模型的保存版本。
- 学习率调度 (Learning Rate Scheduling):每次更新模型权重时,学习率 控制模型根据估计误差变化的程度。回调可以动态调整此速率,在学习陷入停滞时降低它,以帮助模型收敛到最佳解,这种技术通常被称为 学习率衰减。
- Logging and Visualization: Callbacks are frequently used to integrate with experiment tracking tools. They stream metrics to dashboards like TensorBoard or MLflow, allowing data scientists to visualize loss functions and performance graphs in real-time.
使用 Ultralytics YOLO 实现回调#
The Ultralytics library supports a robust callback system, allowing users to hook into events during the training of models like YOLO26. This is particularly useful for users managing workflows on the Ultralytics Platform who need custom logging or control logic.
Below is a concise example of how to define and register a custom callback that prints a message at the end of every training epoch using the Python API:
from ultralytics import YOLO
# Define a custom callback function
def on_train_epoch_end(trainer):
"""Callback function to execute at the end of each training epoch."""
print(f"Epoch {trainer.epoch + 1} complete. Current Fitness: {trainer.fitness}")
# Load the YOLO26 model (latest generation)
model = YOLO("yolo26n.pt")
# Register the custom callback to the model
model.add_callback("on_train_epoch_end", on_train_epoch_end)
# Train the model with the callback active
model.train(data="coco8.yaml", epochs=3)回调 vs. 钩子 (Hooks)#
虽然相关,但区分回调与 钩子 (hooks) 会很有帮助。在诸如 PyTorch 等框架中,钩子通常是附加到特定 张量 操作或神经网络层的底层函数,用于在正向或反向传播期间检查或修改梯度和输出。相比之下,回调通常是绑定到 训练循环 事件(开始、结束、批次处理)的高级抽象,而不是数学计算图本身。
延伸阅读与资源#
For those looking to deepen their understanding of how to optimize training workflows, exploring hyperparameter tuning is a logical next step. Additionally, understanding the underlying computer vision (CV) tasks such as object detection and instance segmentation will provide context on why precise training control via callbacks is necessary. For enterprise-grade management of these processes, the Ultralytics Platform offers integrated solutions that automate many of these callback-driven behaviors.






