Skip to content

Add MCC loss#8785

Open
kakumarabhishek wants to merge 1 commit intoProject-MONAI:devfrom
kakumarabhishek:8784-add-mcc-loss
Open

Add MCC loss#8785
kakumarabhishek wants to merge 1 commit intoProject-MONAI:devfrom
kakumarabhishek:8784-add-mcc-loss

Conversation

@kakumarabhishek
Copy link

Add Matthews Correlation Coefficient (MCC) Lossa

Fixes #8784 .

Description

Add the Matthews Correlation Coefficient (MCC) loss function to monai.losses. Unlike Dice and Tversky losses which only use TP, FP, and FN, the MCC loss considers all four entries of the confusion matrix (TP, TN, FP, FN), making it effective for class-imbalanced segmentation tasks. The loss was proposed in Abhishek & Hamarneh (IEEE ISBI 2021), has been cited 75 times, and has been adopted by Segmentation Models PyTorch (smp). The implementation follows MONAI conventions, supporting sigmoid, softmax, to_onehot_y, include_background, batch, and reduction parameters.

Types of changes

  • Non-breaking change (fix or new feature that would not break existing functionality).
  • Breaking change (fix or new feature that would cause existing functionality to change).
  • New tests added to cover the changes.
  • Integration tests passed locally by running ./runtests.sh -f -u --net --coverage.
  • Quick tests passed locally by running ./runtests.sh --quick --unittests --disttests.
  • In-line docstrings updated.
  • Documentation updated, tested make html command in the docs/ folder.

Add implementation of Matthews Correlation Coefficient (MCC)-based loss
Add tests for MCC loss
Add entry for MCC loss in documentation

Signed-off-by: Kumar Abhishek <7644965+kakumarabhishek@users.noreply.github.com>
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Mar 19, 2026

📝 Walkthrough

Walkthrough

This PR introduces MCCLoss, a new loss function for medical image segmentation that uses all four confusion matrix entries (TP, TN, FP, FN) to address class imbalance issues. The implementation spans four files: a core loss class with configurable activation modes and reduction strategies, an __init__.py export, documentation updates, and comprehensive unit tests covering parameterized input shapes, error conditions, warning validation, and TorchScript compatibility.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 28.57% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed Title 'Add MCC loss' directly matches the main changeset: new MCCLoss implementation with tests, docs, and exports.
Description check ✅ Passed Description covers all required sections: fixes issue reference, clear summary of MCC loss purpose, and comprehensive types-of-changes checklist with all applicable items marked.
Linked Issues check ✅ Passed All core requirements from issue #8784 are met: MCCLoss implementation using all four confusion-matrix entries, soft/differentiable formula, MONAI conventions, unit tests, and documentation integration.
Out of Scope Changes check ✅ Passed All changes directly support MCC loss addition: new loss class, tests, documentation, and export registration. No unrelated modifications detected.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
📝 Coding Plan
  • Generate coding plan for human review comments

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Tip

CodeRabbit can approve the review once all CodeRabbit's comments are resolved.

Enable the reviews.request_changes_workflow setting to automatically approve the review once all CodeRabbit's comments are resolved.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (2)
tests/losses/test_mcc_loss.py (1)

116-150: Add short docstrings to the test class/methods.

This keeps new definitions aligned with the repository’s docstring requirement.

As per coding guidelines, "Docstrings should be present for all definition which describe each variable, return value, and raised exception in the appropriate section of the Google-style of docstrings."

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@tests/losses/test_mcc_loss.py` around lines 116 - 150, Add concise
Google-style docstrings to the TestMCCLoss test class and each test method
(TestMCCLoss, test_shape, test_ill_shape, test_ill_opts, test_input_warnings,
test_script) describing what the test verifies, the key inputs, expected
outcome, and any exceptions/warnings asserted; place a short summary line
followed by brief sections for Args (inputs used, if needed), Raises (expected
exceptions or warnings), and Returns (none) where appropriate to satisfy the
repository docstring requirement.
monai/losses/mcc_loss.py (1)

111-129: Add a Returns section to forward docstring.

Args/Raises/Example are present, but returned tensor semantics and shape are undocumented.

Proposed docstring patch
     def forward(self, input: torch.Tensor, target: torch.Tensor) -> torch.Tensor:
         """
         Args:
             input: the shape should be BNH[WD], where N is the number of classes.
             target: the shape should be BNH[WD] or B1H[WD], where N is the number of classes.
+
+        Returns:
+            torch.Tensor: MCC loss tensor. Shape depends on ``reduction``:
+                - ``"mean"``/``"sum"``: scalar
+                - ``"none"``: per-item/per-class loss tensor after spatial (and optional batch) reduction.
 
         Raises:
             AssertionError: When input and target (after one hot transform if set)
                 have different shapes.
             ValueError: When ``self.reduction`` is not one of ["mean", "sum", "none"].

As per coding guidelines, "Docstrings should be present for all definition which describe each variable, return value, and raised exception in the appropriate section of the Google-style of docstrings."

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@monai/losses/mcc_loss.py` around lines 111 - 129, The forward docstring of
MCCLoss is missing a Returns section; update the MCCLoss.forward docstring to
add a Returns block that describes the returned object (a torch.Tensor), its
dtype and device semantics, and the output shape depending on self.reduction
(e.g., if reduction=='none' return per-sample/per-voxel loss with shape matching
input/target spatial dims, otherwise scalar loss for 'mean' or 'sum'), and
mention any special cases (e.g., broadcasting from B1H[WD] target). Ensure the
section uses Google-style “Returns:” heading and succinctly references reduction
behavior and shape semantics so readers can understand what MCCLoss.forward
returns.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@monai/losses/mcc_loss.py`:
- Around line 111-129: The forward docstring of MCCLoss is missing a Returns
section; update the MCCLoss.forward docstring to add a Returns block that
describes the returned object (a torch.Tensor), its dtype and device semantics,
and the output shape depending on self.reduction (e.g., if reduction=='none'
return per-sample/per-voxel loss with shape matching input/target spatial dims,
otherwise scalar loss for 'mean' or 'sum'), and mention any special cases (e.g.,
broadcasting from B1H[WD] target). Ensure the section uses Google-style
“Returns:” heading and succinctly references reduction behavior and shape
semantics so readers can understand what MCCLoss.forward returns.

In `@tests/losses/test_mcc_loss.py`:
- Around line 116-150: Add concise Google-style docstrings to the TestMCCLoss
test class and each test method (TestMCCLoss, test_shape, test_ill_shape,
test_ill_opts, test_input_warnings, test_script) describing what the test
verifies, the key inputs, expected outcome, and any exceptions/warnings
asserted; place a short summary line followed by brief sections for Args (inputs
used, if needed), Raises (expected exceptions or warnings), and Returns (none)
where appropriate to satisfy the repository docstring requirement.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 1e2b4ea9-a8d2-4eb7-8709-c4400ee7c062

📥 Commits

Reviewing files that changed from the base of the PR and between daaedaa and cc21cef.

📒 Files selected for processing (4)
  • docs/source/losses.rst
  • monai/losses/__init__.py
  • monai/losses/mcc_loss.py
  • tests/losses/test_mcc_loss.py

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Add Matthews Correlation Coefficient (MCC) Loss

1 participant