Skip to content

Add MCC loss#8785

Merged
ericspod merged 3 commits intoProject-MONAI:devfrom
kakumarabhishek:8784-add-mcc-loss
Apr 1, 2026
Merged

Add MCC loss#8785
ericspod merged 3 commits intoProject-MONAI:devfrom
kakumarabhishek:8784-add-mcc-loss

Conversation

@kakumarabhishek
Copy link
Copy Markdown
Contributor

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
Copy Markdown
Contributor

coderabbitai bot commented Mar 19, 2026

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 4128dfe6-a1b3-4bb7-8ca5-27ba4ed5a672

📥 Commits

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

📒 Files selected for processing (1)
  • monai/losses/__init__.py
✅ Files skipped from review due to trivial changes (1)
  • monai/losses/init.py

📝 Walkthrough

Walkthrough

Adds a new MCCLoss class implementing a soft Matthews Correlation Coefficient–based loss (with options: sigmoid, softmax, custom activation, one-hot conversion, background exclusion, batch reduction, smoothing, and standard reductions) in monai/losses/mcc_loss.py; re-exports MCCLoss in monai/losses/init.py; adds API docs entry in docs/source/losses.rst; and introduces comprehensive unit tests in tests/losses/test_mcc_loss.py covering shapes, options/errors, warnings, and TorchScript.

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 The title clearly and concisely describes the main change: adding an MCC loss implementation.
Description check ✅ Passed Description covers the solution, explains the problem motivation, cites the academic source, and confirms all test types and documentation updates completed.
Linked Issues check ✅ Passed All coding requirements from issue #8784 are met: MCC loss implemented using all confusion-matrix entries (TP, TN, FP, FN), supports MONAI conventions (sigmoid, softmax, to_onehot_y, include_background, batch, reduction), includes unit tests, and documentation.
Out of Scope Changes check ✅ Passed All changes are directly related to implementing MCCLoss: new loss class, tests, init export, and documentation subsection.

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

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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.

Copy link
Copy Markdown
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

Copy link
Copy Markdown
Member

@ericspod ericspod left a comment

Choose a reason for hiding this comment

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

Looks good to me, thanks!

ericspod added 2 commits April 1, 2026 21:56
Signed-off-by: Eric Kerfoot <17726042+ericspod@users.noreply.github.com>
@ericspod ericspod enabled auto-merge (squash) April 1, 2026 20:56
@ericspod ericspod merged commit d30de96 into Project-MONAI:dev Apr 1, 2026
31 of 34 checks passed
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

2 participants