التخصيص المتقدم
تُعد كل من واجهة Ultralytics YOLO لسطر الأوامر وواجهة Python تجريدات عالية المستوى مبنية على منفّذات المحرك الأساسية. يركّز هذا الدليل على المحرك Trainer، ويشرح كيفية تخصيصه ليناسب احتياجاتك.
شاهد: إتقان Ultralytics YOLO: التخصيص المتقدم
للاطلاع على أمثلة عملية لتخصيصات المدرب الشائعة — مثل المقاييس المخصصة، والخسارة الموزونة حسب الفئة، وحفظ النموذج، وتجميد العمود الفقري، ومعدلات التعلّم لكل طبقة — راجع دليل تخصيص المدرب.
BaseTrainer#
توفر الفئة BaseTrainer إجراءً عامًا للتدريب يمكن تكييفه مع مهام مختلفة. خصّصه بتجاوز دوال أو عمليات معينة مع الالتزام بالتنسيقات المطلوبة. على سبيل المثال، ادمج نموذجك ومحمّل البيانات المخصصين عبر تجاوز هذه الدوال:
get_model(cfg, weights): ينشئ النموذج المراد تدريبه.get_dataloader(dataset_path, batch_size, rank, mode): ينشئ محمّل البيانات.
لمزيد من التفاصيل والاطلاع على الشيفرة المصدرية، راجع مرجع BaseTrainer.
DetectionTrainer#
إليك كيفية استخدام DetectionTrainer في Ultralytics YOLO وتخصيصه:
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 غلافًا عالي المستوى لفئات Trainer. يمكنك الاستفادة من هذه البنية لمزيد من المرونة في سير عمل تعلّم الآلة:
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. إليك كيفية إضافة استدعاء راجع لتسجيل أوزان النموذج بعد كل حقبة تدريب: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 المهام المعقدة.
- الأداء: محسّن لـكشف الكائنات في الوقت الفعلي وتطبيقات الذكاء الاصطناعي للرؤية المختلفة.
- التخصيص: قابل للتوسيع بنماذج ودوال خسارة ومحملات بيانات مخصصة.
- النمطية: يمكن تعديل المكونات بصورة مستقلة دون التأثير في خط المعالجة بأكمله.
- التكامل: يعمل مع أطر العمل والأدوات الشائعة في منظومة ML.
تعرّف على المزيد عن إمكانات YOLO باستكشاف صفحة Ultralytics 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!