YOLOv8 Class Weights and Loss Weights: How They Affect Training

YOLOv8 class weights and loss weights both influence model optimization, but they solve different problems. Class weights change how strongly individual object classes contribute to the classification objective, which can help with imbalanced datasets. Loss weights such as box, cls, and dfl change the relative importance of localization, classification, and distribution-based bounding-box regression during training.

Current Ultralytics configuration exposes default detection loss gains of box=7.5, cls=0.5, and dfl=1.5. It also includes cls_pw, which applies inverse-frequency class weighting and is disabled by default with cls_pw=0.0.

Introduction to YOLOv8 Class Weights and Loss Weights

YOLOv8 training does not optimize a single simple error value. Object detection requires the model to learn several related objectives at the same time. It must classify objects correctly, place bounding boxes accurately, and learn a suitable distribution for box coordinates.

These objectives are combined into an overall training loss. Ultralytics provides separate gains that determine how strongly each component contributes to that total optimization objective. Current detection configuration includes:

box = 7.5
cls = 0.5
dfl = 1.5

These are relative loss gains rather than class-specific weights.

Class weighting operates at a different level. If one class appears 20,000 times while another appears only 500 times, the rare class may contribute relatively little training signal. Current Ultralytics detection training can compensate for this through cls_pw, which derives weights from inverse class frequencies.

Understanding this distinction is important because increasing cls does not specifically help a minority class. It strengthens classification loss for all classes. Class-specific imbalance requires class weighting, better data balance, or other targeted techniques.

What Are Class Weights in YOLOv8?

Class weights control how strongly examples from different classes contribute to the classification loss.

Suppose a dataset contains:

car:        20,000 instances
truck:       5,000 instances
ambulance:     300 instances

Without class weighting, the optimizer encounters cars much more frequently than ambulances. As a result, the model receives far more classification updates related to the majority class.

Current Ultralytics detection training includes automatic class-weight generation based on inverse class frequency. These weights can be controlled with the cls_pw parameter.

Purpose of Class Weighting

The purpose of class weighting is to make underrepresented classes contribute more strongly to classification optimization.

Conceptually:

Frequent class
↓
Lower relative weight

Rare class
↓
Higher relative weight

Current Ultralytics computes inverse-frequency class weights, raises them to the power specified by cls_pw, and normalizes the final weights so their mean is 1.0.

This means cls_pw does not require you to manually type one weight for every class in a standard detection training command.

Class Weights and Imbalanced Datasets

Class weighting is mainly useful when class frequencies are significantly different.

For example:

Class 0: 10,000
Class 1: 8,000
Class 2:   300

The third class may benefit from increased classification emphasis.

Current Ultralytics uses:

cls_pw=0.0

to disable inverse-frequency weighting.

A value such as:

cls_pw=0.5

applies partial weighting, while:

cls_pw=1.0

applies full inverse-frequency weighting. The parameter is constrained to the range from 0 to 1 in the current detection trainer.

Class weighting can help, but it does not create additional examples. A minority class represented by only a few nearly identical images can still perform poorly even with stronger loss weighting.

What Are Loss Weights in YOLOv8?

Loss weights determine how strongly different training objectives contribute to the total loss.

For standard YOLOv8 detection, the important configurable loss gains are:

box
cls
dfl

Current Ultralytics defaults are:

box=7.5
cls=0.5
dfl=1.5

These values are not probabilities and do not need to add up to 1. They are scaling factors used to balance the relative contribution of different loss components.

Role of Loss Weights During Training

Suppose the model calculates three raw loss components:

Box Loss
Classification Loss
DFL Loss

YOLO applies the configured gains before combining them into the total optimization objective.

Conceptually:

Total Loss
=
Box Loss × box
+
Classification Loss × cls
+
DFL Loss × dfl

The actual internal implementation contains additional normalization and task-specific calculations, but this representation explains the purpose of the weights.

Changing one gain changes how strongly the optimizer responds to that objective relative to the others.

Balancing Different Training Objectives

Object detection requires several goals at once.

If classification is excellent but bounding boxes are poorly localized, increasing the relative box objective may be worth testing.

If localization is good but class confusion remains high, classification loss deserves investigation.

However, the individual numerical loss values should not be compared directly without considering their gains and internal scales. A numerically larger box_loss does not automatically mean box regression is the biggest problem.

Loss-weight tuning should therefore be based primarily on validation performance.

YOLOv8 Loss Components

YOLOv8 detection training reports three familiar loss components:

box_loss
cls_loss
dfl_loss

The current Ultralytics loss implementation contains bounding-box regression, classification, and Distribution Focal Loss-related calculations for detection training.

Each component addresses a different part of object detection.

Box Loss

Box loss measures how accurately predicted bounding boxes align with ground-truth boxes.

Conceptually:

Ground Truth Box
       ↓
Compare
       ↑
Predicted Box

The detector uses IoU-based localization behavior to evaluate bounding-box agreement.

Current Ultralytics configuration controls the relative contribution of this component with:

box

and currently uses:

box=7.5

as the default gain.

Increasing box gives localization errors more influence on the overall training objective.

Classification Loss

Classification loss measures whether the detector assigns the correct object category to matched predictions.

For example:

Ground truth:
car

Prediction:
truck

produces a classification penalty.

The relative classification loss gain is controlled with:

cls

Current Ultralytics uses:

cls=0.5

as the default detection configuration.

This global cls gain is different from cls_pw. cls scales the overall classification objective, while cls_pw changes relative weighting between classes.

Distribution Focal Loss

YOLOv8 uses Distribution Focal Loss, commonly abbreviated as DFL, as part of bounding-box regression.

Instead of predicting each box coordinate only as a direct scalar, the detector learns a discrete distribution over possible coordinate values and uses that representation during localization.

The current Ultralytics loss implementation contains a DFLoss component based on cross-entropy over adjacent distribution bins.

The overall contribution is controlled with:

dfl

and the current default is:

dfl=1.5

How Loss Weights Affect YOLOv8 Training

Loss gains influence which types of errors receive more optimization emphasis.

Changing them can alter convergence behavior, localization quality, classification performance, and overall mAP. Ultralytics includes these loss gains in its supported hyperparameter-tuning search space.

Because the objectives interact, a large increase in one component can also reduce optimization emphasis available to another objective.

Box Loss Weight

The box parameter controls the gain applied to bounding-box localization loss.

Example:

yolo detect train model=yolov8n.pt data=data.yaml box=8.5

Increasing the value may be worth testing if:

  • detections frequently have poor localization,
  • predicted boxes are consistently loose,
  • IoU-sensitive metrics are weak.

However, increasing it does not guarantee improved localization because the overall optimization balance may become worse.

The default is:

box=7.5

in the current Ultralytics configuration.

Classification Loss Weight

The cls parameter controls the global classification loss gain.

Example:

yolo detect train model=yolov8n.pt data=data.yaml cls=0.7

This increases the importance of classification errors for all classes.

That can be useful if class confusion is a major problem, but it is not a direct solution for one rare class.

For minority classes, cls_pw or dataset balancing is more targeted.

DFL Loss Weight

The dfl gain controls the contribution of Distribution Focal Loss to box-regression optimization.

Example:

yolo detect train model=yolov8n.pt data=data.yaml dfl=2.0

The current default is:

dfl=1.5

Because DFL works together with other localization losses, aggressive changes should be tested carefully. Large values can shift optimization away from classification or other localization objectives.

Class Weights vs Loss Weights in YOLOv8

Class weights and loss weights are sometimes confused because both multiply part of the training objective.

They operate at different levels.

Class weights answer:

Which classes should receive more classification emphasis?

Loss weights answer:

Which training objectives should receive more overall emphasis?

Main Differences

A simple comparison is:

SettingPurpose
cls_pwReweights classes according to class frequency
boxScales bounding-box localization loss
clsScales overall classification loss
dflScales Distribution Focal Loss

Current Ultralytics detection configuration exposes all four of these parameters.

For example:

cls=1.0

does not tell YOLO to care more about only a rare class.

It tells YOLO to increase classification-loss importance globally.

By contrast:

cls_pw=0.5

uses class-frequency information to increase relative importance for less frequent classes.

When Each Type of Weight Is Useful

Use class weighting when the main issue is:

severe class imbalance
minority-class recall
rare-class AP
majority-class dominance

Use loss-weight tuning when the main issue is related to broader objective balance:

poor localization
class confusion across many classes
weak box quality
training-objective imbalance

These techniques can be combined, but doing so simultaneously makes experiments harder to interpret.

How to Adjust YOLOv8 Loss Weights

Ultralytics allows loss gains to be passed directly through Train mode.

It is usually best to establish a baseline using defaults before changing them. The current defaults are already designed as a general-purpose starting configuration.

Configure Loss Weights During Training

Using CLI:

yolo detect train \
model=yolov8n.pt \
data=data.yaml \
box=7.5 \
cls=0.5 \
dfl=1.5

You can then create an experiment such as:

yolo detect train \
model=yolov8n.pt \
data=data.yaml \
box=8.0 \
cls=0.7 \
dfl=1.5

Using Python:

from ultralytics import YOLO

model = YOLO("yolov8n.pt")

model.train(
    data="data.yaml",
    epochs=100,
    box=7.5,
    cls=0.5,
    dfl=1.5
)

These settings are part of the current Ultralytics training configuration.

Tune Weights for a Custom Dataset

Do not change all loss gains at once during manual tuning.

For example:

Baseline:
box=7.5
cls=0.5
dfl=1.5

Then test:

Experiment A:
box=8.5
cls=0.5
dfl=1.5

Next:

Experiment B:
box=7.5
cls=0.7
dfl=1.5

This makes it easier to identify which change affected performance.

Ultralytics’ automated hyperparameter tuner also includes loss gains among the settings it can explore.

Monitor Changes in Training Metrics

Track more than raw losses.

Compare:

mAP50-95
mAP50
precision
recall
per-class AP
box_loss
cls_loss
dfl_loss

If increasing cls lowers classification loss but decreases mAP50-95, it may not be a useful change.

The final decision should be based on validation performance, not whether one loss number looks smaller.

Using Weights for Class Imbalance

Class imbalance is one of the clearest cases where weighting can be useful.

Current Ultralytics detection training automatically derives inverse-frequency class weights when cls_pw is greater than zero.

However, class weighting should usually complement dataset improvements rather than replace them.

Improving Minority-Class Performance

Suppose:

Class 0: 15,000
Class 1: 10,000
Class 2:    500

You might test:

yolo detect train model=yolov8n.pt data=data.yaml cls_pw=0.25

A stronger experiment might use:

yolo detect train model=yolov8n.pt data=data.yaml cls_pw=0.5

Ultralytics’ current fine-tuning guidance suggests starting with moderate values such as 0.25 for moderate imbalance and increasing toward 1.0 only for more severe imbalance.

Track whether the minority class actually gains recall and AP instead of judging the change from overall mAP alone.

Data Balancing vs Weight Adjustment

Class weights alter optimization.

Data balancing alters what the model actually sees.

For example:

Weight Adjustment
→ same minority images
→ stronger minority loss contribution

while:

Better Data
→ more minority examples
→ more viewpoints
→ more backgrounds
→ more real variation

Collecting additional diverse examples is usually a stronger long-term solution because class weights cannot create new information.

A useful strategy is:

Improve data first
      ↓
Measure remaining imbalance
      ↓
Test cls_pw if needed

Avoiding Excessive Weighting

Too much minority-class weighting can create new problems.

The model may begin producing excessive minority-class detections or sacrifice majority-class precision.

For example:

Before weighting:
Minority recall = 0.35
Minority precision = 0.80

After aggressive weighting:

Minority recall = 0.70
Minority precision = 0.42

Whether this is better depends on the application.

For this reason, cls_pw should be tuned while monitoring both precision and recall.

How to Choose Suitable Loss Weights

Loss gains should be treated as advanced hyperparameters rather than mandatory custom settings.

The defaults provide a sensible baseline for most datasets. Current Ultralytics configuration uses box=7.5, cls=0.5, and dfl=1.5.

Only change them when validation behavior provides a reason.

Start with Default Values

Begin with:

box=7.5
cls=0.5
dfl=1.5
cls_pw=0.0

These are the current default detection settings.

Train a complete baseline and record:

mAP50-95
precision
recall
per-class AP
training losses

Without this baseline, you cannot know whether custom weighting helped.

Compare Per-Class Performance

Overall mAP can hide problems.

For example:

car AP:        0.85
truck AP:      0.79
ambulance AP:  0.24

If the problem is concentrated in the ambulance class, increasing global cls may be less appropriate than class weighting or additional ambulance data.

Per-class metrics tell you whether the problem is class-specific or affects classification broadly.

Tune One Loss Component at a Time

A controlled tuning sequence might be:

Run 1:
Defaults

Run 2:
Change box only

Run 3:
Return to defaults
Change cls only

Run 4:
Return to defaults
Change dfl only

Then compare validation results.

If class imbalance is being tested, change cls_pw independently as another experiment.

Common Problems with Class and Loss Weights

Changing loss weights can improve one metric while damaging another.

This is why weight tuning should always be accompanied by controlled validation experiments.

Unstable Training Loss

Aggressive changes can make one objective dominate training.

For example:

cls=5.0

is ten times the current default classification gain.

That does not automatically mean classification performance becomes ten times better. It may distort the balance between classification and localization.

If training becomes unstable after changing a loss gain, return toward the default and make smaller adjustments.

Poor Minority-Class Accuracy

Low minority-class accuracy may persist even after weighting.

Possible reasons include:

  • too few real examples,
  • poor label quality,
  • large visual variation,
  • class confusion,
  • tiny objects,
  • severe imbalance.

Weighting does not solve missing information.

Collecting better minority-class samples may still be necessary.

Overemphasis on One Loss Component

Suppose you greatly increase:

box

The network may place stronger emphasis on localization relative to classification.

Likewise, excessive:

cls

may over-prioritize classification.

The goal is not to maximize each individual loss gain. It is to find a balance that produces the strongest validation results.

Lower Overall Detection Performance

A custom weighting configuration may improve one class but lower overall performance.

For example:

Baseline:
mAP50-95 = 0.68

Weighted:
mAP50-95 = 0.63

But perhaps:

rare-class AP:
0.22 → 0.46

Whether this tradeoff is acceptable depends on project priorities.

For safety-critical or rare-event detection, minority recall may matter more than overall average accuracy.

FAQs About YOLOv8 Class Weights and Loss Weights

What are class weights in YOLOv8?

Class weights change the relative contribution of different object classes to classification loss.

Current Ultralytics detection training computes inverse-frequency class weights when cls_pw is enabled, giving rarer classes greater relative influence.

Does YOLOv8 support class weights?

Current Ultralytics detection training does.

Use:

cls_pw

where:

cls_pw=0.0

disables weighting and larger values up to 1.0 progressively apply inverse-frequency weighting.

This functionality has evolved over time, so older YOLOv8 discussions may report that native class weighting was unavailable.

What are loss weights in YOLOv8?

Loss weights are scaling factors that control how much different training objectives contribute to optimization.

For detection, important weights include:

box
cls
dfl

Current defaults are:

box=7.5
cls=0.5
dfl=1.5

What do box, cls, and dfl weights mean in YOLOv8?

box controls the gain applied to bounding-box localization loss.

cls controls the gain applied to classification loss.

dfl controls the gain applied to Distribution Focal Loss used as part of bounding-box regression.

All three are configurable training hyperparameters in current Ultralytics.

Can loss weights help with class imbalance?

The global cls loss gain can increase classification importance, but it does not specifically target minority classes.

For class imbalance, use:

cls_pw

or improve the class distribution through additional data, oversampling, or augmentation.

cls_pw is the more targeted class-weighting mechanism in current detection training.

How do I change loss weights in YOLOv8?

Using CLI:

yolo detect train \
model=yolov8n.pt \
data=data.yaml \
box=8.0 \
cls=0.7 \
dfl=1.5

Using Python:

model.train(
    data="data.yaml",
    box=8.0,
    cls=0.7,
    dfl=1.5
)

These values override the standard loss gains for that training run.

Should I change the default YOLOv8 loss weights?

Not automatically.

Start with the defaults:

box=7.5
cls=0.5
dfl=1.5

and establish a baseline first.

Change them only when validation results show a specific weakness that loss-weight tuning may address.

Conclusion

YOLOv8 class weights and loss weights influence training in fundamentally different ways.

Class weighting controls which classes receive greater classification emphasis. Current Ultralytics detection training exposes this through:

cls_pw

which derives normalized weights from inverse class frequency. A value of 0.0 disables class weighting, while values up to 1.0 progressively strengthen it.

Loss weights control which training objectives receive greater emphasis. The standard detection gains are currently:

box=7.5
cls=0.5
dfl=1.5

The distinction can be summarized as:

cls_pw
→ balance individual classes

box
→ localization-loss importance

cls
→ overall classification-loss importance

dfl
→ distribution-regression importance

A practical tuning workflow is:

Train with Defaults
       ↓
Evaluate Per-Class Metrics
       ↓
Identify the Problem
       ↓
Class Imbalance?
   ↓             ↓
  Yes            No
   ↓              ↓
Test cls_pw   Evaluate box/cls/dfl
   ↓              ↓
Retrain and Validate
       ↓
Compare mAP, Precision, Recall

For imbalanced datasets, improve the data first whenever possible. Add diverse minority-class examples, correct annotation gaps, and inspect per-class precision, recall, and AP. Then use class weighting when the imbalance still affects performance.

For loss-weight tuning, change one component at a time and compare against the default baseline. Higher loss weights are not automatically better. The best configuration is the one that improves validation performance for the metrics and classes that matter most to the application.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top