ابدأ

ضبط المعلمات الفائقة بكفاءة باستخدام Ray Tune وYOLO26

يبحث ضبط المعلمات الفائقة عن مجموعة المعلمات الفائقة التي تحقق أفضل أداء للنموذج. وينفذ تجارب بقيم مختلفة للمعلمات الفائقة، ثم يقيّم أداء كل تجربة.

تسريع الضبط باستخدام Ultralytics YOLO26 وRay Tune#

يتكامل Ultralytics YOLO26 مع Ray Tune لضبط المعلمات الفائقة. وباستخدام Ray Tune، يمكنك الاستفادة من استراتيجيات بحث متقدمة والتوازي والإيقاف المبكر لتسريع عملية الضبط.

Ray Tune#

Ray Tune hyperparameter optimization workflow

Ray Tune مكتبة لضبط المعلمات الفائقة مصممة لتحقيق الكفاءة والمرونة. وهي تدعم استراتيجيات بحث متنوعة والتوازي واستراتيجيات الإيقاف المبكر، وتتكامل مع أطر عمل تعلم الآلة الشائعة، بما فيها Ultralytics YOLO26.

التكامل مع Weights & Biases#

يدعم YOLO26 أيضًا تكاملًا اختياريًا مع Weights & Biases لمراقبة عملية الضبط.

التثبيت#

لتثبيت الحزم المطلوبة، شغّل:

التثبيت
# Install and update Ultralytics and Ray Tune packages
pip install -U ultralytics "ray[tune]" optuna

# Optionally install and enable W&B for per-trial logging
pip install wandb
yolo settings wandb=True

الاستخدام#

الاستخدام
from ultralytics import YOLO

# ⁨تحميل نموذج YOLO26n⁩
model = YOLO("yolo26n.pt")

# ⁨بدء ضبط المعلمات الفائقة لتدريب YOLO26n على مجموعة بيانات COCO8⁩
result_grid = model.tune(data="coco8.yaml", use_ray=True)

معلمات الطريقة tune()#

توفر طريقة tune() في YOLO26 واجهة سهلة الاستخدام لضبط المعلمات الفائقة باستخدام Ray Tune. وتقبل الطريقة عدة وسائط تتيح لك تخصيص عملية الضبط. فيما يلي شرح مفصل لكل معلمة:

المعلمةالنوعالوصفالقيمة الافتراضية
datastr or listملف YAML لمجموعة البيانات المراد تشغيل أداة الضبط عليها، ويحدد مسارات بيانات التدريب والتحقق والإعدادات الأخرى الخاصة بمجموعة البيانات. أما التصنيف، فيتطلب مجلد مجموعة بيانات أو اسم مجموعة بيانات مدمجة (مثل imagenet10). تدرب القائمة كل تجربة على كل مجموعة بيانات وتُبلغ عن متوسط مقياس المهمة.
spacedict, optionalقاموس يحدد مساحة البحث عن المعلمات الفائقة في Ray Tune. يتوافق كل مفتاح مع اسم معلمة فائقة، وتحدد القيمة نطاق القيم المطلوب استكشافه أثناء الضبط. وإذا لم تُقدَّم هذه المساحة، يستخدم YOLO26 مساحة بحث افتراضية تضم معلمات فائقة متنوعة.
grace_periodint, optionalفترة السماح بوحدة الحقب في مجدول ASHA ضمن Ray Tune. لن ينهي المجدول أي تجربة قبل انقضاء هذا العدد من الحقب (بحد أقصى epochs). لا يُستخدم مع search_alg="bohb".10
gpu_per_trialint, optionalعدد وحدات GPU التي يخصصها Ray لكل تجربة. حدّد هذه القيمة صراحةً لاستخدام التدريب على GPU؛ وإذا لم تُحدَّد، فلن تحصل التجارب على موارد GPU.None
iterationsint, optionalالحد الأقصى لعدد التجارب التي ستُجرى أثناء الضبط. تساعد هذه المعلمة على التحكم في إجمالي عدد تركيبات المعلمات الفائقة المختبرة، لضمان عدم استمرار عملية الضبط إلى أجل غير مسمى.300
search_algstr or Searcher, optionalاستراتيجية البحث في Ray Tune المطلوب استخدامها. يمكنك تمرير كائن باحث Ray مباشرةً، أو استخدام سلسلة مدعومة مثل optuna أو hyperopt أو bayesopt أو bohb أو hebo أو nevergrad أو zoopt أو ax أو random. تستخدم أدوات البحث المحددة بالسلاسل تلقائيًا مقياس المهمة الافتراضي وmode="max". يستخدم الإعداد الافتراضي TPE متعدد المتغيرات من Optuna مع اقتراحات تراعي التنفيذ المتوازي."optuna"
**train_argsdict, optionalوسائط إضافية تُمرَّر إلى طريقة train() أثناء الضبط. قد تتضمن هذه الوسائط إعدادات مثل عدد عصور التدريب وحجم الدفعة والتكوينات الأخرى الخاصة بالتدريب.{}

من خلال تخصيص هذه المعلمات، يمكنك ضبط عملية تحسين المعلمات الفائقة بدقة بما يلائم احتياجاتك المحددة وموارد الحوسبة المتاحة.

وصف مساحة البحث الافتراضية#

يسرد الجدول التالي معلمات مساحة البحث الافتراضية لضبط المعلمات الفائقة في YOLO26 باستخدام Ray Tune. لكل معلمة نطاق قيم محدد بواسطة tune.uniform()، باستثناء close_mosaic، الذي يستخدم tune.randint().

المعلمةالنطاقالوصف
lr0tune.uniform(1e-5, 1e-2)معدل التعلّم الأولي الذي يتحكم في حجم الخطوة أثناء التحسين. تسرّع القيم الأعلى التدريب، لكنها قد تسبب عدم الاستقرار.
lrftune.uniform(0.01, 1.0)عامل معدل التعلّم النهائي الذي يحدد مقدار انخفاض معدل التعلّم بحلول نهاية التدريب.
momentumtune.uniform(0.7, 0.98)عامل الزخم للمُحسِّن، ويساعد على تسريع التدريب وتجاوز نقاط الحد الأدنى المحلية.
weight_decaytune.uniform(0.0, 0.001)معلمة تنظيم تمنع فرط التكيّف من خلال فرض عقوبة على قيم الأوزان الكبيرة.
warmup_epochstune.uniform(0.0, 5.0)عدد العصور التدريبية التي يزداد خلالها معدل التعلّم تدريجيًا لتحقيق استقرار التدريب في مراحله الأولى.
warmup_momentumtune.uniform(0.0, 0.95)قيمة الزخم الأولية التي تزداد تدريجيًا خلال فترة الإحماء.
boxtune.uniform(1.0, 20.0)وزن مكوّن خسارة الصندوق المحيط، لموازنة دقة تحديد المواقع في النموذج.
clstune.uniform(0.1, 4.0)وزن مكوّن خسارة التصنيف، لموازنة دقة توقع الفئات في النموذج.
cls_pwtune.uniform(0.0, 1.0)قوة ترجيح الفئات، من التعطيل (0.0) إلى الترجيح الكامل العكسي للتكرار (1.0).
dfltune.uniform(0.4, 12.0)وزن مكوّن انحدار مسافة الصندوق، لإعطاء أولوية للدقة في تحديد موضع الصندوق المحيط.
hsv_htune.uniform(0.0, 0.1)نطاق زيادة تنويع درجة اللون، لإضافة تنوع لوني ومساعدة النموذج على التعميم.
hsv_stune.uniform(0.0, 0.9)نطاق زيادة التشبع، لتغيير شدة اللون وتحسين المتانة.
hsv_vtune.uniform(0.0, 0.9)نطاق زيادة القيمة (السطوع)، لمساعدة النموذج على العمل في ظروف إضاءة متنوعة.
degreestune.uniform(0.0, 45.0)نطاق زيادة التدوير بالدرجات، لتحسين التعرف على الأجسام المدورة.
translatetune.uniform(0.0, 0.9)نطاق زيادة الإزاحة، لتحريك الصور أفقيًا ورأسيًا.
scaletune.uniform(0.0, 0.95)نطاق زيادة تغيير المقياس، لمحاكاة ظهور الأجسام على مسافات مختلفة.
sheartune.uniform(0.0, 10.0)نطاق زيادة القص بالدرجات، لمحاكاة تغيرات المنظور.
perspectivetune.uniform(0.0, 0.001)نطاق زيادة المنظور، لمحاكاة تغيرات زاوية الرؤية ثلاثية الأبعاد.
flipudtune.uniform(0.0, 1.0)احتمالية زيادة القلب الرأسي، لتعزيز تنوع مجموعة البيانات.
fliplrtune.uniform(0.0, 1.0)احتمالية زيادة القلب الأفقي، وهي مفيدة للأجسام المتماثلة.
bgrtune.uniform(0.0, 1.0)احتمالية زيادة تبديل قنوات BGR، للمساعدة على ثبات الألوان.
mosaictune.uniform(0.0, 1.0)احتمالية زيادة الفسيفساء التي تجمع أربع صور في عينة تدريب واحدة.
mixuptune.uniform(0.0, 1.0)احتمالية زيادة Mixup التي تمزج صورتين وتسميتيهما معًا.
cutmixtune.uniform(0.0, 1.0)احتمالية زيادة Cutmix التي تجمع مناطق من الصور مع الحفاظ على السمات المحلية.
copy_pastetune.uniform(0.0, 1.0)في وضع flip، تحدد النسبة المئوية للأجسام المؤهلة التي تُنسخ إلى صورة؛ أما في وضع mixup، فتحدد أيضًا احتمال تنفيذها.
close_mosaictune.randint(0, 11)تعطيل الفسيفساء في آخر N من العصور التدريبية لتحقيق استقرار التدريب قبل اكتماله.

مثال على فضاء بحث مخصص#

يوضح هذا المثال كيفية استخدام فضاء بحث مخصص لضبط المعلمات الفائقة باستخدام Ray Tune وYOLO26. يتيح لك توفير فضاء بحث مخصص تركيز عملية الضبط على معلمات فائقة محددة تهمك.

الاستخدام
from ray import tune

from ultralytics import YOLO

# ⁨تعريف نموذج YOLO⁩
model = YOLO("yolo26n.pt")

# ⁨تشغيل Ray Tune على النموذج⁩
result_grid = model.tune(
    data="coco8.yaml",
    space={"lr0": tune.uniform(1e-5, 1e-2)},
    epochs=50,
    use_ray=True,
)

ينشئ مقتطف الشيفرة أعلاه نموذج YOLO باستخدام الأوزان المدرّبة مسبقًا لـYOLO26n، ثم يستدعي الطريقة tune() باستخدام إعداد مجموعة البيانات coco8.yaml. ويوفّر فضاء بحث مخصّصًا لـمعدل التعلّم الأولي lr0 على هيئة قاموس يتضمن المفتاح "lr0" والقيمة tune.uniform(1e-5, 1e-2). وأخيرًا، يمرّر وسيطات تدريب إضافية، مثل عدد الحقب، مباشرةً إلى طريقة tune بصيغة epochs=50.

مثال على خوارزمية البحث#

يمكنك تحديد استراتيجية بحث في Ray Tune بالاسم. بالنسبة إلى خوارزميات البحث المحددة بالسلاسل، سيستخدم Ultralytics تلقائيًا مقياس التحسين الافتراضي للمهمة الحالية وmode="max". وإذا لم تُقدَّم search_alg، يستخدم Ultralytics خوارزمية TPE متعددة المتغيرات من Optuna مع اقتراحات تراعي التنفيذ المتوازي.

استخدام السلسلة `search_alg` مع `model.tune()`
from ultralytics import YOLO

# ⁨تعريف نموذج YOLO⁩
model = YOLO("yolo26n.pt")

result_grid = model.tune(
    data="coco8.yaml",
    epochs=50,
    search_alg="optuna",
    use_ray=True,
)

إذا كنت بحاجة إلى تخصيص أداة أخذ العينات في الباحث أو تجاوز مقياسه ووضع التحسين، فمرّر كائن باحث Ray Tune مُنشأً بدلًا من سلسلة.

استخدام كائن `OptunaSearch` مع `model.tune()`
from ray.tune.search.optuna import OptunaSearch

from ultralytics import YOLO

# ⁨تعريف نموذج YOLO⁩
model = YOLO("yolo26n.pt")

# ⁨تعريف باحث⁩
searcher = OptunaSearch(
    metric="metrics/mAP50-95(B)",
    mode="max",
)

result_grid = model.tune(
    data="coco8.yaml",
    epochs=50,
    search_alg=searcher,
    use_ray=True,
)

استئناف جلسة ضبط المعلمات الفائقة المتوقفة باستخدام Ray Tune#

يمكنك استئناف جلسة Ray Tune متوقفة بتمرير resume=True. ويمكنك اختياريًا تمرير الدليل name الذي يستخدمه Ray Tune ضمن runs/{task} للاستئناف. وإلا فسيستأنف آخر جلسة متوقفة. لا تحتاج إلى توفير iterations وspace مجددًا، لكن عليك توفير بقية وسيطات التدريب مرة أخرى، بما في ذلك data وepochs.

استخدام `resume=True` مع `model.tune()`
from ultralytics import YOLO

# ⁨تعريف نموذج YOLO⁩
model = YOLO("yolo26n.pt")

# ⁨استئناف التشغيل السابق⁩
results = model.tune(use_ray=True, data="coco8.yaml", epochs=50, resume=True)

# ⁨استئناف تشغيل Ray Tune بالاسم 'tune_exp_2'⁩
results = model.tune(use_ray=True, data="coco8.yaml", epochs=50, name="tune_exp_2", resume=True)

معالجة نتائج Ray Tune#

بعد إجراء تجربة لضبط المعلمات الفائقة باستخدام Ray Tune، قد ترغب في إجراء تحليلات متنوعة للنتائج التي حصلت عليها. سيرشدك هذا الدليل إلى مسارات العمل الشائعة لمعالجة هذه النتائج وتحليلها.

تحميل نتائج تجربة الضبط من دليل#

تعيد model.tune(use_ray=True) كائن Ray من النوع ResultGrid، وتحفظ التجربة ضمن runs/{task}/tune أو ضمن name الذي مررته. لتحميل هذه النتائج بعد انتهاء تنفيذ النص البرمجي الأصلي، استأنف الجلسة؛ إذ يؤدي ذلك إلى استعادة التجارب المحفوظة وإرجاع ResultGrid نفسه:

from ultralytics import YOLO

model = YOLO("yolo26n.pt")
result_grid = model.tune(data="coco8.yaml", epochs=50, use_ray=True, resume=True)

تحليل أساسي على مستوى التجربة#

احصل على نظرة عامة حول أداء التجارب. يمكنك التحقق سريعًا مما إذا وقعت أخطاء أثناء التجارب.

if result_grid.errors:
    print("One or more trials failed!")
else:
    print("No errors!")

تحليل أساسي على مستوى التجربة الفردية#

يمكنك الوصول إلى تكوينات المعلمات الفائقة لكل تجربة فردية والمقاييس التي أُبلغ عنها أخيرًا.

for i, result in enumerate(result_grid):
    print(f"Trial #{i}: Configuration: {result.config}, Last Reported Metrics: {result.metrics}")

رسم السجل الكامل للمقاييس المُبلّغ عنها لتجربة#

يمكنك رسم سجل المقاييس المُبلّغ عنها لكل تجربة لمعرفة كيفية تطور المقاييس بمرور الوقت.

import matplotlib.pyplot as plt

for i, result in enumerate(result_grid):
    plt.plot(
        result.metrics_dataframe["training_iteration"],
        result.metrics_dataframe["metrics/mAP50-95(B)"],
        label=f"Trial {i}",
    )

plt.xlabel("Training Iterations")
plt.ylabel("mAP50-95")
plt.legend()
plt.show()

الملخص#

تناولنا في هذا الدليل مسارات العمل الشائعة لتحليل نتائج التجارب التي أُجريت باستخدام Ray Tune وUltralytics. وتشمل الخطوات الأساسية تحميل نتائج التجربة من دليل، وإجراء تحليل أساسي على مستوى التجربة والتجربة الفردية، ورسم المقاييس.

اطّلع على صفحة وثائق تحليل النتائج الخاصة بـRay Tune للاستفادة القصوى من تجارب ضبط المعلمات الفائقة.

الأسئلة الشائعة#

  • لضبط المعلمات الفائقة لنموذج Ultralytics YOLO26 باستخدام Ray Tune، اتبع الخطوات التالية:

    1. تثبيت الحزم المطلوبة:

      pip install -U ultralytics "ray[tune]" optuna
      pip install wandb # optional for logging
      yolo settings wandb=True
    2. تحميل نموذج YOLO26 وبدء الضبط:

      from ultralytics import YOLO
      
      # ⁨تحميل نموذج YOLO26⁩
      model = YOLO("yolo26n.pt")
      
      # ⁨بدء الضبط باستخدام مجموعة بيانات COCO8⁩
      result_grid = model.tune(data="coco8.yaml", use_ray=True)

    يستخدم ذلك استراتيجيات البحث والتوازي في Ray Tune لتحسين المعلمات الفائقة لنموذجك بكفاءة.

  • يستخدم Ultralytics YOLO26 المعلمات الفائقة الافتراضية التالية للضبط باستخدام Ray Tune:

    المعلمةنطاق القيمالوصف
    lr0tune.uniform(1e-5, 1e-2)معدل التعلّم الأولي
    lrftune.uniform(0.01, 1.0)عامل معدل التعلّم النهائي
    momentumtune.uniform(0.7, 0.98)الزخم
    weight_decaytune.uniform(0.0, 0.001)اضمحلال الأوزان
    warmup_epochstune.uniform(0.0, 5.0)عصور الإحماء
    boxtune.uniform(1.0, 20.0)وزن خسارة الصندوق
    clstune.uniform(0.1, 4.0)وزن خسارة الفئة
    cls_pwtune.uniform(0.0, 1.0)قوة ترجيح الفئات
    dfltune.uniform(0.4, 12.0)وزن خسارة مسافة الصندوق
    hsv_htune.uniform(0.0, 0.1)نطاق زيادة درجة اللون
    translatetune.uniform(0.0, 0.9)نطاق زيادة الإزاحة

    يمكن تخصيص هذه المعلمات الفائقة بما يلائم احتياجاتك المحددة. للاطلاع على القائمة الكاملة ومزيد من التفاصيل، راجع دليل ضبط المعلمات الفائقة.

  • لدمج Weights & Biases (W&B) مع عملية ضبط Ultralytics YOLO26:

    1. تثبيت W&B:

      pip install wandb
      wandb login
      yolo settings wandb=True
    2. تشغيل الضابط:

      from ultralytics import YOLO
      
      # ⁨تحميل نموذج YOLO⁩
      model = YOLO("yolo26n.pt")
      
      # ⁨تنشئ كل تجربة في Ray تشغيلًا خاصًا بها في W&B ضمن هذا المشروع⁩
      result_grid = model.tune(data="coco8.yaml", project="YOLO-Tuning", use_ray=True)

    يتيح لك هذا الإعداد مراقبة عملية الضبط، وتتبع تكوينات المعلمات الفائقة، وتصور النتائج في W&B.

  • يوفر Ray Tune مزايا عديدة لتحسين المعلمات الفائقة:

    • استراتيجيات بحث متقدمة: يستخدم خوارزميات مثل التحسين البايزي وHyperOpt لإجراء بحث فعّال عن المعلمات.
    • التوازي: يدعم التنفيذ المتوازي لعدة تجارب، ما يسرّع عملية الضبط بشكل ملحوظ.
    • الإيقاف المبكر: يستخدم استراتيجيات مثل ASHA لإنهاء التجارب ذات الأداء الضعيف مبكرًا، مما يوفر موارد الحوسبة.

    يتضمن Ultralytics YOLO26 دعم Ray Tune عبر model.tune(use_ray=True).

  • لتحديد مساحة بحث مخصصة لضبط المعلمات الفائقة في YOLO26 باستخدام Ray Tune:

    from ray import tune
    
    from ultralytics import YOLO
    
    model = YOLO("yolo26n.pt")
    search_space = {"lr0": tune.uniform(1e-5, 1e-2), "momentum": tune.uniform(0.7, 0.98)}
    result_grid = model.tune(data="coco8.yaml", space=search_space, use_ray=True)

    يتيح ذلك تخصيص نطاق المعلمات الفائقة، مثل معدل التعلم الأولي والزخم، التي سيجري استكشافها أثناء عملية الضبط. للاطلاع على إعدادات متقدمة، راجع قسم مثال مساحة البحث المخصصة.

التعليقات40

اطرح سؤالًا، وشارك نتائجك، أو ساعد شخصًا آخر.

  1. supriamirGitHub

    Hi, I finish the hyperparameter tune, how to use the best parameter in best_hyperparameters.ymal for training?

    Currently i manually use the manually copy the htperparameter.

    model.train( data=str(dataset_yaml), epochs=epochs, imgsz=imgsz, batch=batch, project=project, name=f"fold_{k}", workers=0, patience=100, exist_ok=True, cache=False, device=0,

        lr0= 0.00254,
        lrf= 0.02718,
        momentum= 0.83225,
        weight_decay= 0.001,
        warmup_epochs= 2.22741,
        warmup_momentum= 0.72834,
        box= 8.86345,
        cls= 0.52365,
        dfl= 0.45493,
        hsv_h= 0.01544,
        hsv_s= 0.44438,
        hsv_v= 0.37867,
        degrees= 0.01115,
        translate= 0.10045,
        scale= 0.33157,
        shear= 0.0075,
        perspective= 6.0e-05,
        flipud= 0.00882,
        fliplr= 0.34916,
        bgr= 9.0e-05,
        mosaic= 0.63841,
        mixup= 0.00099,
        cutmix= 0.00361,
        copy_paste= 0.00051,
        close_mosaic= 6,
    )
    1. Glenn JocherUltralytics

      Yes — you can load best_hyperparameters.yaml and unpack it directly into model.train() instead of copying values by hand; see the Ray Tune integration guide and feel free to keep follow-ups here in Discussions so the Ultralytics team can see them.

      from pathlib import Path
      import yaml
      from ultralytics import YOLO
      
      model = YOLO("yolo26n.pt")
      
      hyp_path = Path("runs/detect/tune/best_hyperparameters.yaml")
      with hyp_path.open() as f:
          hyp = yaml.safe_load(f)
      
      model.train(
          data=str(dataset_yaml),
          epochs=epochs,
          imgsz=imgsz,
          batch=batch,
          project=project,
          name=f"fold_{k}",
          workers=0,
          patience=100,
          exist_ok=True,
          cache=False,
          device=0,
          **hyp,
      )
      1
  2. Emeyer87GitHub

    Hello,

    I've noticed that every Iteration with use_ray = True is downloading yolo11n.pt. I'm attempting to use this on an existing instance segmentation model I built but wanted to ensure the tuning is running against the model I've assigned, and not a fresh Detection model.

    from ultralytics import YOLO from ray import tune

    model_path = r"C:/Users/Me/Downloads/NashvilleSegmentation.pt" data_path = r"C:/Users/Me/Downloads/dataset/data.yaml" model=YOLO(model_path)

    search_space = { "degrees": tune.uniform(0.0, 12.0) }

    results = model.tune( data=data_path, epochs=20, # keep it tiny iterations=20, # exactly one trial optimizer="AdamW", space=search_space, device=0, seed=0, workers=2, amp=True, batch=16, patience=12, plots=False, save=False, project="test_tune", name="degrees_tune_01", lr0=0.00114, use_ray=True, gpu_per_trial=1

    )

    1. Glenn JocherUltralytics

      Glad it’s sorted—quick tip: to tune your existing segmentation model, load your .pt first (model = YOLO("path/to/your.pt")) and then run model.tune(..., use_ray=True); Ray trials will reuse that same model/task—verify in the logs that task=segment.

  3. Fatima-khanjarGitHub

    Subject: Questions Regarding Using Ray Tune for YOLOv11 Hyperparameter Tuning

    Hello!

    I hope this message finds you well.

    #hyperparameter tuning using tune()
    from ray import tune
    from ray.tune import ResultGrid
    from ray.tune.examples.mnist_pytorch import train_mnist
    from ultralytics import YOLO
    import os
    import torch
    import matplotlib.pyplot as plt
    
    # Define a YOLO model
    model = YOLO("yolo11s.pt").to('cuda')
    
    tune_dir = 'ray_results'
    os.makedirs(tune_dir, exist_ok=True)
    
    
    # Tune hyperparameters using ray tune
    result_grid = model.tune(
        data= "data.yaml",  
        epochs=10,                 
        iterations=10,             
        batch = 16,            
        device = 0,
        workers=0,
        use_ray=True,
        gpu_per_trial =1,
        name = "tuning",
        project = tune_dir
    )
    
    Now, load the results after the tuning experiment is finished
    exp_name = "tuning"
    experiment_path = f"{tune_dir}/{exp_name}"  # Get the name of the experiment
    print(f"Loading results from {experiment_path}...")
    
    restored_tuner = tune.Tuner.restore(experiment_path, trainable=train_mnist)
    result_grid = restored_tuner.get_results()
    
    # Basic Experiment-Level Analysis: Check for errors
    if result_grid.errors:
        print("One or more trials failed!")
    else:
        print("No errors!")
    
    # Basic Trial-Level Analysis: Print configurations and last reported metrics for each trial
    for i, result in enumerate(result_grid):
        print(f"Trial #{i}: Configuration: {result.config}, Last Reported Metrics: {result.metrics}")
    
    # Plotting the Entire History of Reported Metrics for a Trial
    # Assuming "mean_accuracy" is part of the metrics
    for i, result in enumerate(result_grid):
        plt.plot(
            result.metrics_dataframe["training_iteration"],
            result.metrics_dataframe["mean_accuracy"],  # Modify this depending on your metrics
            label=f"Trial {i}",
        )
    
    plt.xlabel("Training Iterations")
    plt.ylabel("Mean Accuracy")
    plt.legend()
    plt.show()
    

    #hyperparameter tuning using tuner.fit()
    import os 
    from ray import tune
    from ray.tune import ResultGrid
    from ray.tune.examples.mnist_pytorch import train_mnist
    from ray.tune import Result
    from pathlib import Path
    
    tune_dir = Path("ray_results").resolve().as_uri()
    exp_name = "tune_analyzing_results"
    
    tuner = tune.Tuner(
        trainable=train_mnist,
        param_space={
            "lr": tune.uniform(0.001, 0.1),
            "momentum": tune.uniform(0.1, 0.9),
        },
        run_config=tune.RunConfig(
            name=exp_name,
            stop={"training_iteration": 100},
            checkpoint_config=tune.CheckpointConfig(
                checkpoint_score_attribute="mean_accuracy",
                num_to_keep = 5,
            ),
            storage_path=tune_dir,
        ),
        tune_config=tune.TuneConfig(mode="max", metric="mean_accuracy", num_samples=3),
    )
    result_grid: ResultGrid = tuner.fit()
    
    
    experiment_path = os.path.join(tune_dir, exp_name)
    print(f"Loading results from {experiment_path}...")
    
    restored_tuner = tune.Tuner.restore(experiment_path, trainable=train_mnist)
    result_grid = restored_tuner.get_results()
    
    # Check if there have been errors
    if result_grid.errors:
        print("One of the trials failed!")
    else:
        print("No errors!")
    
    num_results = len(result_grid)
    print("Number of results:", num_results)
    
    # Iterate over results
    for i, result in enumerate(result_grid):
        if result.error:
            print(f"Trial #{i} had an error:", result.error)
            continue
    
        print(
            f"Trial #{i} finished successfully with a mean accuracy metric of:",
            result.metrics["mean_accuracy"]
        )
    
    results_df = result_grid.get_dataframe()
    results_df[["training_iteration", "mean_accuracy"]]
    
    print("Shortest training time:", results_df["time_total_s"].min())
    print("Longest training time:", results_df["time_total_s"].max())
    
    best_result_df = result_grid.get_dataframe(
        filter_metric="mean_accuracy", filter_mode="max"
    )
    best_result_df[["training_iteration", "mean_accuracy"]]
    
    
    # Get the result with the maximum test set `mean_accuracy`
    best_result: Result = result_grid.get_best_result()
    
    # Get the result with the minimum `mean_accuracy`
    worst_performing_result: Result = result_grid.get_best_result(
        metric="mean_accuracy", mode="min"
    )
    
    best_result.config
    best_result.path
    # Get the last Checkpoint associated with the best-performing trial
    best_result.checkpoint
    # Get the last reported set of metrics
    best_result.metrics
    result_df = best_result.metrics_dataframe
    result_df[["training_iteration", "mean_accuracy", "time_total_s"]]
    best_result.metrics_dataframe.plot("training_iteration", "mean_accuracy")
    ax = None
    for result in result_grid:
        label = f"lr={result.config['lr']:.3f}, momentum={result.config['momentum']}"
        if ax is None:
            ax = result.metrics_dataframe.plot("training_iteration", "mean_accuracy", label=label)
        else:
            result.metrics_dataframe.plot("training_iteration", "mean_accuracy", ax=ax, label=label)
    ax.set_title("Mean Accuracy vs. Training Iteration for All Trials")
    ax.set_ylabel("Mean Test Accuracy")

    I have been following your guide on using Ray Tune for hyperparameter tuning with YOLOv11. I was able to run the experiment using the use_ray=True argument, and it worked successfully—thank you for the helpful explanation!

    However, I still have a few questions and points of confusion:

    1. Naming the Trials: How can I change or customize the names of the individual trials when using model.tune(..., use_ray=True)? Right now, the trials are auto-named, and I’d like more meaningful names to help keep track of different configurations. image

    2. Retrieving the Best Hyperparameters: After the tuning process is complete, I would like to extract the best hyperparameter configuration to reuse it for future training. I noticed in other examples (e.g., train_mnist) that you use tuner.fit() to retrieve and analyze results, including the best configuration. So my question is: when using model.tune() directly (as in the case of YOLOv11), is there a method to extract the best hyperparameters without using tuner.fit()? Or is it necessary to re-structure the experiment using tune.Tuner to get access to that kind of detailed analysis?

    3. Using tune.Tuner() with YOLOv11: In your other examples, the tuning process is managed using tune.Tuner(...), but I’m not sure how to apply this approach to YOLOv11, since there’s no explicit trainable function like train_mnist. Should we always use model.tune() for YOLO models, or is there a way to integrate YOLOv11 into a Tuner workflow for more advanced customization and analysis?

    Thank you so much for your time and support! I would really appreciate any clarification or guidance on these points.

    Best regards,

    1. Glenn JocherUltralytics

      @Fatima-khanjar Thank you for your detailed questions about Ray Tune integration with YOLO11!

      1. Naming Trials: Currently, the high-level model.tune() API doesn't provide direct control over individual trial naming. Ray Tune automatically generates these names. You can use the name parameter to name the overall experiment (as you've done with "tuning"), but individual trial names remain auto-generated.

      2. Retrieving Best Hyperparameters: When using model.tune() with Ray Tune, the best hyperparameters are automatically saved to runs/[task]/tune/best_hyperparameters.yaml. This file contains the optimal configuration and can be loaded for future use. You can also examine tune_results.csv for all trial results.

      3. Using tune.Tuner(): While possible, creating a custom trainable function for YOLO with the low-level Ray Tune API requires more work. You'd need to wrap the YOLO training process in a function that configures and trains the model while reporting metrics to Ray Tune. For most users, the high-level model.tune() API is recommended as it handles this integration automatically.

      For more advanced customization, you might consider extending the Ray Tune integration in Ultralytics by referring to the source code in the ultralytics/utils/tuner.py file.

    2. Fatima-khanjarGitHub

      Hello! Thank you for your clarification. I will continue using model.tune() and use the following line to retrieve the best hyperparameters, since the best_hyperparameters.yaml file wasn’t automatically saved in the output directory of the Ray tuning: best_config = analysis.get_best_config(metric="metrics/mAP50(B)", mode="max")`

      I have a question: I read that Optuna uses the TPE (Tree-structured Parzen Estimator) search algorithm, which is more powerful than the default search algorithms in Ray Tune. Since Ray Tune provides scalability and distributed tuning, is it possible to combine both—using Optuna’s TPE algorithm with Ray Tune while still calling model.tune()? If so, how can I integrate them?

      I also have another question that’s unrelated. I noticed that YOLOv11 comes in different versions, from n to xl. I understand that the choice depends on the dataset size and the task complexity. But what are the actual criteria used to determine the complexity of a task?

      best regrads,

    3. Glenn JocherUltralytics

      @Fatima-khanjar

      Regarding using TPE with Ray Tune - yes, it's possible! Ray Tune already supports TPE through the HyperOpt integration. You can use it by installing the HyperOpt package and specifying the search algorithm:

      pip install hyperopt
      
      from ray.tune.search.hyperopt import HyperOptSearch
      from ray.tune.search import ConcurrencyLimiter
      
      hyperopt_search = HyperOptSearch(metric="metrics/mAP50(B)", mode="max")
      limited_search = ConcurrencyLimiter(hyperopt_search, max_concurrent=4)
      
      # Then in your model.tune() call
      model.tune(
          data="data.yaml",
          search_alg=limited_search,
          use_ray=True,
          # other parameters
      )

      For your question about YOLO11 model size selection, the criteria typically include:

      • Computational resources: Larger models (l, x, xl) require more GPU memory and processing power
      • Dataset complexity: More complex datasets with small/numerous objects benefit from larger models
      • Inference speed requirements: Smaller models (n, s) offer faster inference for real-time applications
      • Accuracy needs: Larger models generally provide higher accuracy at the cost of speed

      You can check the performance trade-offs in the Ultralytics documentation to make an informed decision based on your specific constraints.

      1
    4. Fatima-khanjarGitHub(تم التعديل)

      Hello, I hope this message finds you well.

      I followed your instructions to integrate Ray Tune with the TPE algorithm using HyperOpt:

      hyperopt_search = HyperOptSearch(metric="metrics/mAP50(B)", mode="max")
      limited_search = ConcurrencyLimiter(hyperopt_search, max_concurrent=1)

      Then, I used the following code to tune hyperparameters with Ray Tune:

      tuning_results = model.tune(
          data="data.yaml",
          epochs=50,                # Number of epochs for each tuning iteration
          iterations=100,           # Total number of tuning iterations
          batch=16,
          device=0,
          workers=0,
          grace_period=30,
          search_alg=limited_search,
          use_ray=True,
          gpu_per_trial=1,
          project=tune_dir
      )

      However, I encountered a syntax error: SyntaxError: 'search_alg' is not a valid YOLO argument. Could you please advise me on how to fix this?

      I have another question regarding the output directory of Ray Tune. It shows that inside the runs folder, there are subfolders named train (equal to the number of iterations) and a tune folder that contains subdirectories also equal to the number of iterations.

      Screenshot 2025-04-17 104229

      My question is: should I focus on the train directories? Why are they generated, and what's their purpose?

      Also, if I want to monitor the overall progress of the fine-tuning process — for example, in genetic tuning, we usually look at a graph of the fitness score vs. iteration — where should I look for that kind of visualization or information?

      best regards,

    5. Glenn JocherUltralytics(تم التعديل)

      @Fatima-khanjar

      Regarding your issues with HyperOptSearch and Ray Tune integration:

      1. The search_alg argument is passed through model.tune(use_ray=True). It defaults to "optuna" (TPE) and accepts either a string (such as "optuna", "hyperopt", "bohb" or "random") or a Ray Tune searcher instance like your HyperOptSearch, so you do not need to modify ultralytics/utils/tuner.py.

      2. About the directory structure:

        • The train directories (train1, train2, etc.) contain individual training runs for each trial with different hyperparameter sets
        • The tune directory contains the aggregated results of all trials and should be your primary focus
      3. For monitoring progress:

        • Check tune/tune_results.csv for all trial results
        • Look for tune/best_fitness.png which shows fitness score progression over iterations
        • tune/best_hyperparameters.yaml contains the optimal configuration found

      The plots in the tune directory (especially tune_scatter_plots.png if available) provide valuable visualizations of the hyperparameter search space and how different parameters affected model performance.

  4. Fatima-khanjarGitHub

    Hello!
    I hope this message finds you well.

    I'm trying to use Ray Tune for hyperparameter optimization with the following code:

    results = model.tune(
        data="data.yaml",  
        epochs=30,                 
        iterations=150,           
        batch=16,            
        optimizer="AdamW",         
        plots=False,               
        save=False,                
        val=False,                 
        device=0,
        workers=8,
        use_ray=True,
        project="ray_results"
    )

    However, I'm getting a path-related error that I can't figure out:

    FileNotFoundError: [WinError 3] The system cannot find the path specified...

    It seems to be related to the length of the path Ray is trying to create. Do you know how I can fix this?

    Also, I have a question. I came across Ray Tune while working with Genetic Algorithms, and I was wondering: would you recommend using Ray Tune or Genetic Algorithms for hyperparameter optimization? Are they similar in how they work, or are there major differences between them? What advantages does Ray Tune offer over Genetic Algorithms?

    Thank you for your help!

    1. Fatima-khanjarGitHub

      Hello Community!!

      Just following up on my own post — I managed to solve the issue on Windows 11.

      Here’s what worked for me:

      1. Opened gpedit.msc as Administrator
      2. Navigated to: Computer Configuration > Administrative Templates > System > Filesystem
      3. Enabled the setting “Enable Win32 long paths"

      After doing this, the problem was resolved.

      Posting this in case it helps someone else!

    2. Glenn JocherUltralytics

      @Fatima-khanjar Thank you for sharing your solution to the Windows path length issue! This is helpful information that could benefit other users experiencing similar problems.

      Regarding your question about Ray Tune versus Genetic Algorithms: They're different approaches to hyperparameter optimization. Ray Tune offers several advantages including:

      1. Multiple search strategies beyond genetic algorithms (Bayesian optimization, grid search, random search)
      2. Built-in parallel execution that efficiently utilizes available resources
      3. Early stopping via ASHA scheduler to terminate underperforming trials
      4. Distributed computing capabilities for scaling across multiple machines

      Ultralytics actually supports both approaches - the internal tuner uses genetic algorithms focusing on mutation, while the Ray Tune integration provides more advanced search strategies and better parallelization. Ray Tune is generally recommended for more complex search spaces and when you have multiple GPUs available.

      1
    1. wisroviGitHub

      tambien necesito:

      model.add_callback("on_train_start", self.on_train_start) model.add_callback("on_train_end", self.on_train_end)

      pero dichas funciones no se disparan

    2. wisroviGitHub

      agradezco mucho sus valiosas aportaciones, de verdad que es una funcionalidad increible y magnifica

    3. Glenn JocherUltralytics

      @wisrovi to integrate MLFlow with Ultralytics YOLO hyperparameter tuning, you'll need to create a custom Ray Tune reporter that logs metrics to MLFlow. While we don't have native MLFlow integration like Weights & Biases, you can implement it by adding MLFlow logging callbacks to your tuning script. The Ray Tune documentation provides guidance on MLFlow integration that you can adapt for YOLO workflows.

  5. NegroAmigoGitHub

    Which versions of YOLO are supported by Ray Tune? I have project with YOLOv8, will it be suitable to use with Ray Tune?

    1. Glenn JocherUltralytics

      @NegroAmigo yes, YOLOv8 fully supports Ray Tune integration for hyperparameter tuning. You can use the same model.tune() method shown in our Ray Tune integration guide by simply loading your YOLOv8 model (YOLO('yolov8n.pt')). The tuning process works identically across supported YOLO versions. For implementation details, see the Ultralytics Ray Tune documentation.

    1. Glenn JocherUltralytics

      @alifazeli00 the documentation currently focuses on the default hyperparameters and their tuning ranges. If you're looking for specific details on beta2 for AdamW, it might not be explicitly covered. For more information on hyperparameter tuning, you can explore the Ray Tune documentation linked in the guide.

    2. Glenn JocherUltralytics

      Beta2 is not explicitly mentioned in the documentation as it typically defaults to 0.999 in AdamW, which is a common standard setting. For specific adjustments, you may need to modify the optimizer settings directly in your training script.

      1
  6. sirtrisGitHub

    Hi, you mention that the .tune() function integrates well with wandb. Are there any plans to make it work with mlflow as well? When I try to use it now no model metric, parameters or artifacts, etc. are logged. It would also be nice to have one hyperparameter sweep as a parent run and the individual runs as child runs of that parent run. Best,

    1. Glenn JocherUltralytics

      @sirtris currently, there are no plans to integrate the .tune() function with MLflow, but we appreciate your feedback and will consider it for future updates.

  7. sachmatkrisGitHub

    unfortunately that is not the issue because the results are exactly the same for different learning rates - impossible.

    On Fri, 27 Sept 2024 at 19:06, Glenn Jocher @.***> wrote:

    @sachmatkris https://github.com/sachmatkris it seems like the issue might be with the search space configuration. Ensure that the hyperparameters have enough variability and that the dataset path is correctly set. If the problem persists, consider adjusting the search space or reviewing the dataset configuration. For more details, you can refer to the Ray Tune documentation https://docs.ultralytics.com/integrations/ray-tune/.

    — Reply to this email directly, view it on GitHub https://github.com/orgs/ultralytics/discussions/16505#discussioncomment-10777716, or unsubscribe https://github.com/notifications/unsubscribe-auth/A3WH6HFTKYE2WLTJVGR6HWTZYV7A5AVCNFSM6AAAAABO5HD4QCVHI2DSMVQWIX3LMV43URDJONRXK43TNFXW4Q3PNVWWK3TUHMYTANZXG43TCNQ . You are receiving this because you were mentioned.Message ID: @.*** com>

    1. Glenn JocherUltralytics

      @sachmatkris if you're seeing identical results for different learning rates, it might be worth checking the hyperparameter search space and ensuring the dataset configuration is correct. Adjusting these settings could help resolve the issue. For further guidance, please refer to the Ray Tune documentation.

  8. sachmatkrisGitHub

    I found out the issue was setting device = 0 in the model.tune() and specifying absolute path for the .data.yaml, which is not the same what YOLO does when started from within an opened folder on VScode.

    1. sachmatkrisGitHub(تم التعديل)

      @sachmatkris it seems like you've identified the issue with the device setting and path specification. If you need further assistance, feel free to ask!

      Another issue I have is using the following call all of my experiments with ray_tune return the same metrics:

      search_space = { 'lr0': tune.loguniform(1e-5, 1e-1), 'momentum': tune.uniform(0.6, 0.95), }

      result_grid = model.tune(data = 'C:/Users/Kristijonas/Desktop/Mokslo šaknys karčios/AI/Projects/masinu_numeriai/formated_dataset_new/data.yaml', imgsz = 1280, space = search_space, batch = 16, epochs = 50, patience = 5, use_ray = True, iterations = 20, device='cuda' )

      e.g.

      image

    2. Glenn JocherUltralytics

      @sachmatkris it seems like the issue might be with the search space configuration. Ensure that the hyperparameters have enough variability and that the dataset path is correctly set. If the problem persists, consider adjusting the search space or reviewing the dataset configuration. For more details, you can refer to the Ray Tune documentation.