高级自定义
Ultralytics YOLO 的命令行和 Python接口都是基于底层引擎执行器构建的高级抽象。本指南聚焦于 Trainer 引擎,介绍如何根据你的具体需求进行自定义。
观看: 精通 Ultralytics YOLO:高级自定义
有关常见训练器自定义的实用示例——自定义指标、类别加权损失、模型保存、冻结骨干网络以及逐层学习率——请参阅自定义训练器指南。
BaseTrainer#
BaseTrainer 类提供通用训练流程,可适配各种任务。你可以在遵循所需格式的前提下,重写特定函数或操作来自定义它。例如,重写以下函数即可集成自己的自定义模型和数据加载器:
get_model(cfg, weights):构建待训练的模型。get_dataloader(dataset_path, batch_size, rank, mode):构建数据加载器。
如需了解更多详情和源代码,请参阅 BaseTrainer 参考文档。
DetectionTrainer#
以下介绍如何使用和自定义 Ultralytics YOLO DetectionTrainer:
from ultralytics.models.yolo.detect import DetectionTrainer
trainer = DetectionTrainer(overrides={...})
trainer.train()
trained_model = trainer.best # 获取最佳模型自定义 DetectionTrainer#
要训练尚未直接支持的自定义检测模型,请重载现有的 get_model 功能:
from ultralytics.models.yolo.detect import DetectionTrainer
class CustomTrainer(DetectionTrainer):
def get_model(self, cfg=None, weights=None, verbose=True):
"""Loads a custom detection model given configuration and weight files."""
trainer = CustomTrainer(overrides={...})
trainer.train()你还可以进一步自定义训练器,例如修改损失函数,或添加一个在每个轮次结束时运行的回调,以记录或上传最新权重。示例如下:
from ultralytics.models.yolo.detect import DetectionTrainer
from ultralytics.nn.tasks import DetectionModel
class MyCustomModel(DetectionModel):
def init_criterion(self):
"""Initializes a custom loss function for the model."""
class CustomTrainer(DetectionTrainer):
def get_model(self, cfg=None, weights=None, verbose=True):
"""Returns a customized detection model instance configured with specified config and weights."""
return MyCustomModel(...)
# 用于记录模型权重的回调
def log_model(trainer):
"""Logs the path of the last model weight used by the trainer."""
last_weight_path = trainer.last
print(last_weight_path)
trainer = CustomTrainer(overrides={...})
trainer.add_callback("on_train_epoch_end", log_model) # 添加到现有回调中
trainer.train()如需了解更多有关回调触发事件和入口点的信息,请参阅回调指南。
其他引擎组件#
你可以用类似的方法自定义其他组件,例如 Validators 和 Predictors。如需了解更多信息,请参阅验证器和预测器文档。
将 YOLO 与自定义训练器配合使用#
YOLO 模型类为训练器类提供了高级封装。你可以利用这一架构,让机器学习工作流更加灵活:
from ultralytics import YOLO
from ultralytics.models.yolo.detect import DetectionTrainer
# 创建自定义训练器
class MyCustomTrainer(DetectionTrainer):
def get_model(self, cfg=None, weights=None, verbose=True):
"""Custom code implementation."""
# 初始化 YOLO 模型
model = YOLO("yolo26n.pt")
# 使用自定义训练器进行训练
results = model.train(trainer=MyCustomTrainer, data="coco8.yaml", epochs=3)这种方法让你既能保留 YOLO 接口的简洁性,又能自定义底层训练过程,以满足具体需求。
常见问题#
要针对特定任务自定义
DetectionTrainer,可以重写它的方法,使其适配你的自定义模型和数据加载器。首先继承DetectionTrainer,然后重新定义get_model等方法,以实现自定义功能。示例如下:from ultralytics.models.yolo.detect import DetectionTrainer class CustomTrainer(DetectionTrainer): def get_model(self, cfg=None, weights=None, verbose=True): """Loads a custom detection model given configuration and weight files.""" trainer = CustomTrainer(overrides={...}) trainer.train() trained_model = trainer.best # 获取最佳模型BaseTrainer是训练流程的基础,可通过重写其通用方法来适配各种任务。关键组件包括:get_model(cfg, weights):构建待训练的模型。get_dataloader(dataset_path, batch_size, rank, mode):构建数据加载器。preprocess_batch():在模型前向传播之前处理批次预处理。set_model_attributes():根据数据集信息设置模型属性。get_validator():返回用于模型评估的验证器。
如需了解更多有关自定义和源代码的信息,请参阅
BaseTrainer参考文档。在
DetectionTrainer中添加回调,以监控和修改训练过程。下面介绍如何添加一个回调,在每个训练 epoch 结束后记录模型权重:from ultralytics.models.yolo.detect import DetectionTrainer # 用于记录模型权重的回调 def log_model(trainer): """Logs the path of the last model weight used by the trainer.""" last_weight_path = trainer.last print(last_weight_path) trainer = DetectionTrainer(overrides={...}) trainer.add_callback("on_train_epoch_end", log_model) # 添加到现有回调中 trainer.train()如需详细了解回调事件和入口点,请参阅回调指南。
Ultralytics YOLO 在其引擎执行器之上提供了高级抽象,非常适合快速开发和自定义。主要优势包括:
- 易于使用:命令行和 Python 接口都能简化复杂任务。
- 性能:针对实时目标检测和各种视觉 AI 应用进行了优化。
- 自定义:可扩展以支持自定义模型、损失函数和数据加载器。
- 模块化:可以独立修改各个组件,而不会影响整个流程。
- 集成:可与 ML 生态系统中常用的框架和工具协同使用。
探索主要的 Ultralytics YOLO 页面,进一步了解 YOLO 的功能。
可以,
DetectionTrainer支持针对非标准模型进行自定义。继承DetectionTrainer并重写方法,即可满足特定模型的需求。下面是一个简单示例:from ultralytics.models.yolo.detect import DetectionTrainer class CustomDetectionTrainer(DetectionTrainer): def get_model(self, cfg=None, weights=None, verbose=True): """Loads a custom detection model.""" trainer = CustomDetectionTrainer(overrides={...}) trainer.train()如需完整的操作说明和示例,请参阅
DetectionTrainer参考文档。
评论10
提出问题、分享结果,或帮助其他人。
UltralyticsAssistantUltralytics
👋 Hello, thank you for your interest in Ultralytics 🚀! We recommend visiting the Docs for new users, where you can explore numerous Python and CLI usage examples. Many common questions may already be answered there, including step-by-step guides tailored for different tasks.
If this is a 🐛 Bug Report, please provide a minimum reproducible example to help us debug the issue.
If you have a custom training ❓ Question, please include as much information as possible, such as dataset image samples and training logs, and make sure you are following our Tips for Best Training Results.
Join the Ultralytics community where it suits you best! For real-time chat, head to Discord 🎧. Prefer in-depth discussions? Check out Discourse. Or explore threads on our Subreddit and connect with other users.
Upgrade
Upgrade to the latest
ultralyticspackage, including all requirements, in a Python>=3.8 environment with PyTorch>=1.8 to ensure your issue is not already resolved:pip install -U ultralyticsEnvironments
YOLO can be run in any of the following up-to-date verified environments (with all dependencies, including CUDA/CUDNN, Python, and PyTorch preinstalled):
- Notebooks with free GPU:
- Google Cloud Deep Learning VM. See GCP Quickstart Guide
- Amazon Deep Learning AMI. See AWS Quickstart Guide
- Docker Image. See Docker Quickstart Guide
Status
If this badge is green, all Ultralytics CI tests are currently passing. CI tests verify correct operation of all YOLO Modes and Tasks on macOS, Windows, and Ubuntu every 24 hours and on every commit.
This is an automated response 🤖. An Ultralytics engineer will also assist you soon!
- Notebooks with free GPU:
ablyzniuk
How to set a custom loss function?
ablyzniuk
Sorry, I missed it above. I saw it))) Delete this comment.
Glenn JocherUltralytics@ablyzniuk to set a custom loss function, you can override the
init_criterionmethod in your custom model class, as shown in the Advanced Customization documentation. This method allows you to define and initialize your loss function according to your requirements. Let me know if you need an example!ablyzniuk
@glen-jocher thank you) I will be glad and thankfull if you will give a detailed example of training default Ultralytics Yolo(5-11 versions) with custom trainer e.t.c. I think there must be much easier and convinient way opposite what I did (I edited source code and overrides DetectionTrainer methods after)
Glenn JocherUltralytics(已编辑)For custom training without modifying source code, subclass
DetectionTrainerand override methods like this:from ultralytics.models.yolo.detect import DetectionTrainer from ultralytics.nn.tasks import DetectionModel class CustomModel(DetectionModel): def init_criterion(self): # Your custom loss initialization here pass class CustomTrainer(DetectionTrainer): def get_model(self, cfg=None, weights=None, verbose=True): return CustomModel(cfg, nc=self.data["nc"], verbose=verbose) # Replace with your model config trainer = CustomTrainer(overrides={'model': 'yolo26n.yaml', 'data': 'coco128.yaml', 'epochs': 100}) trainer.train()This maintains upgrade compatibility while allowing customization. The Advanced Customization Guide shows additional methods you can override.
ternaus
Is it possible to define custom DataLoader or Augmentation pipeline in DetectionTrainer?
Paula DerrengerUltralyticsYes, it's definitely possible to define custom DataLoader and Augmentation pipelines in DetectionTrainer! 🚀 To do so, you'd primarily override the
get_dataloader()method in a subclass ofDetectionTrainer. Here's a brief example on how you might go about customizing your DataLoader:from ultralytics.models.yolo.detect import DetectionTrainer class CustomTrainer(DetectionTrainer): def get_dataloader(self, ...): # Your custom DataLoader logic here ...For augmentations, you can integrate them within your custom DataLoader or modify datasets accordingly. If you need further customization or to include a custom Augmentation pipeline directly tied with the models' training loop, you could adjust or extend methods in the model itself or within the
get_dataloadermethod to apply augmentations.Don't forget to explore our Advanced Customization section and BaseTrainer Reference for more details on customizing training routines, models, and DataLoaders. 😄 Happy coding!
1
UttamToni
As mentioned in the advanced customization of ultralytics:
from ultralytics.models.yolo.detect import DetectionTrainer trainer = DetectionTrainer(overrides={...})
i am confuced that which file should i place in the curly brackets of
overrides={...}. Is theargs.yamlfile is allowed , which is created after the training step? I have used the args.yaml file which is created after training step but got this error:/usr/local/lib/python3.10/dist-packages/ultralytics/engine/trainer.py in __init__(self, cfg, overrides, _callbacks) 96 overrides (dict, optional): Configuration overrides. Defaults to None. 97 """ ---> 98 self.args = get_cfg(cfg, overrides) 99 self.check_resume(overrides) 100 self.device = select_device(self.args.device, self.args.batch) /usr/local/lib/python3.10/dist-packages/ultralytics/cfg/__init__.py in get_cfg(cfg, overrides) 207 overrides = cfg2dict(overrides) 208 if "save_dir" not in cfg: --> 209 overrides.pop("save_dir", None) # special override keys to ignore 210 check_dict_alignment(cfg, overrides) 211 cfg = {**cfg, **overrides} # merge cfg and overrides dicts (prefer overrides) TypeError: set.pop() takes no arguments (2 given)
Glenn JocherUltralytics(已编辑)Hello! It seems like there’s been a little confusion regarding the
overrides={...}usage, and I appreciate you reaching out for clarification. 🙌To directly answer your question, the
overrides={...}parameter is designed to accept a dictionary of configuration overrides, not a file. It's intended to programmatically override specific configuration entries. For example:from ultralytics.models.yolo.detect import DetectionTrainer # Example override dictionary overrides = { "batch": 16, "imgsz": 640, } trainer = DetectionTrainer(overrides=overrides)If you're looking to use the configurations from an
args.yamlfile created after training, you'd first need to read this YAML file into a Python dictionary, which you could then pass tooverrides. Here's a quick way to do it:import yaml # Load your args.yaml content into a dictionary with open('path/to/your/args.yaml', 'r') as file: yaml_content = yaml.safe_load(file) # Now, pass the loaded dictionary to overrides trainer = DetectionTrainer(overrides=yaml_content)Regarding the error you're encountering, it appears there's a misunderstanding in how the
overridesdictionary is being used or possibly an issue with the implementation. If following the above pattern doesn't resolve your issue, could you please share more details about what you're trying to achieve with theoverrides? This way, I or someone from the community can offer more targeted advice. 😊Thank you for your patience, and looking forward to helping you get this sorted!