feat(losses): add class_weights support to Dice, Jaccard, Tversky and Focal losses#1290
Merged
qubvel merged 2 commits intoqubvel-org:mainfrom Mar 19, 2026
Merged
Conversation
qubvel
approved these changes
Mar 12, 2026
Collaborator
qubvel
left a comment
There was a problem hiding this comment.
Looks good, thanks for adding tests
| ignore_index: Label that indicates ignored pixels (does not contribute to loss) | ||
| eps: A small epsilon for numerical stability to avoid zero division error | ||
| (denominator will be always greater or equal to eps) | ||
| class_weights: Array of weights for each class. If not None, the loss for each class |
Collaborator
There was a problem hiding this comment.
Suggested change
| class_weights: Array of weights for each class. If not None, the loss for each class | |
| class_weights: List of weights for each class. If not ``None``, the loss for each class |
Contributor
Author
|
Thanks for the review! I've applied your docstring suggestion across all four loss files and also fixed the failing style check. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Closes #881
Description
This PR adds a
class_weightsparameter toDiceLoss,JaccardLoss,TverskyLoss, andFocalLoss,allowing users to weight the contribution of each class to the final loss.
This is useful for dealing with class imbalance.
Changes
DiceLoss,JaccardLoss,TverskyLoss:class_weightssupported inmulticlassandmultilabelmodes. RaisesValueErrorforbinarymode.FocalLoss:class_weightssupported inmulticlassmode only (the per-class loop already exists). RaisesValueErrorfor other modes.weights.sum().Example
loss = DiceLoss(mode="multiclass", class_weights=[1.0, 2.0, 0.5])Tests
All 29 tests pass: