-
Notifications
You must be signed in to change notification settings - Fork 1.4k
Add Fréchet Radiomics Distance (FRD) to MONAI metrics (#8643) #8769
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
AymanL
wants to merge
3
commits into
Project-MONAI:dev
Choose a base branch
from
AymanL:implement_frd_metric
base: dev
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
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
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,71 @@ | ||
| # Copyright (c) MONAI Consortium | ||
| # Licensed under the Apache License, Version 2.0 (the "License"); | ||
| # you may not use this file except in compliance with the License. | ||
| # You may obtain a copy of the License at | ||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||
| # Unless required by applicable law or agreed to in writing, software | ||
| # distributed under the License is distributed on an "AS IS" BASIS, | ||
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| # See the License for the specific language governing permissions and | ||
| # limitations under the License. | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import torch | ||
|
|
||
| from monai.metrics.fid import get_fid_score | ||
| from monai.metrics.metric import Metric | ||
|
|
||
| __all__ = ["FrechetRadiomicsDistance", "get_frd_score"] | ||
|
|
||
|
|
||
| class FrechetRadiomicsDistance(Metric): | ||
| """ | ||
| Fréchet Radiomics Distance (FRD). Computes the Fréchet distance between two | ||
| distributions of radiomic feature vectors, in the same way as the Fréchet | ||
| Inception Distance (FID) but for radiomics-based features. | ||
|
|
||
| Unlike FID, FRD uses interpretable, clinically relevant radiomic features | ||
| (e.g. from PyRadiomics) and works for both 2D and 3D images, with optional | ||
| conditioning by anatomical masks. See Konz et al. "Fréchet Radiomic Distance | ||
| (FRD): A Versatile Metric for Comparing Medical Imaging Datasets." | ||
| https://arxiv.org/abs/2412.01496 | ||
|
|
||
| This metric accepts two groups of pre-extracted radiomic feature vectors with | ||
| shape (number of samples, number of features). The same Fréchet distance | ||
| formula as in FID is applied to the mean and covariance of these features. | ||
|
|
||
| Args: | ||
| y_pred: Radiomic feature vectors for the first distribution (e.g. from | ||
| generated or reconstructed images), shape (N, F). | ||
| y: Radiomic feature vectors for the second distribution (e.g. from real | ||
| images), shape (N, F). | ||
|
|
||
| Returns: | ||
| Scalar tensor containing the FRD value. | ||
| """ | ||
|
|
||
| def __call__(self, y_pred: torch.Tensor, y: torch.Tensor) -> torch.Tensor: | ||
| return get_frd_score(y_pred, y) | ||
|
|
||
|
|
||
| def get_frd_score(y_pred: torch.Tensor, y: torch.Tensor) -> torch.Tensor: | ||
| """Computes the FRD score from two batches of radiomic feature vectors. | ||
|
|
||
| The implementation reuses the same Fréchet distance as FID; only the | ||
| semantics (radiomic features vs. deep features) differ. | ||
|
|
||
| Args: | ||
| y_pred: Feature vectors for the first distribution, shape (N, F). | ||
| y: Feature vectors for the second distribution, shape (N, F). | ||
|
|
||
| Returns: | ||
| Scalar tensor containing the Fréchet Radiomics Distance. | ||
|
|
||
| Raises: | ||
| ValueError: When either tensor has more than 2 dimensions. Inputs must have | ||
| shape (number of samples, number of features). | ||
| """ | ||
| if y_pred.ndimension() > 2 or y.ndimension() > 2: | ||
| raise ValueError("Inputs should have (number images, number of features) shape.") | ||
| return get_fid_score(y_pred, y) | ||
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,49 @@ | ||
| # Copyright (c) MONAI Consortium | ||
| # Licensed under the Apache License, Version 2.0 (the "License"); | ||
| # you may not use this file except in compliance with the License. | ||
| # You may obtain a copy of the License at | ||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||
| # Unless required by applicable law or agreed to in writing, software | ||
| # distributed under the License is distributed on an "AS IS" BASIS, | ||
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| # See the License for the specific language governing permissions and | ||
| # limitations under the License. | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import unittest | ||
|
|
||
| import numpy as np | ||
| import torch | ||
|
|
||
| from monai.metrics import FIDMetric, FrechetRadiomicsDistance | ||
| from monai.utils import optional_import | ||
|
|
||
| _, has_scipy = optional_import("scipy") | ||
|
|
||
|
|
||
| @unittest.skipUnless(has_scipy, "Requires scipy") | ||
| class TestFrechetRadiomicsDistance(unittest.TestCase): | ||
| def test_results(self): | ||
| x = torch.Tensor([[1, 2], [1, 2], [1, 2]]) | ||
| y = torch.Tensor([[2, 2], [1, 2], [1, 2]]) | ||
| results = FrechetRadiomicsDistance()(x, y) | ||
| np.testing.assert_allclose(results.cpu().numpy(), 0.4444, atol=1e-4) | ||
|
|
||
| def test_frd_matches_fid_for_same_features(self): | ||
| """FRD uses the same Fréchet formula as FID; same inputs give same value.""" | ||
| y_pred = torch.Tensor([[1.0, 2.0], [1.0, 2.0], [1.0, 2.0]]) | ||
| y = torch.Tensor([[2.0, 2.0], [1.0, 2.0], [1.0, 2.0]]) | ||
| frd_score = FrechetRadiomicsDistance()(y_pred, y) | ||
| fid_score = FIDMetric()(y_pred, y) | ||
| np.testing.assert_allclose(frd_score.cpu().numpy(), fid_score.cpu().numpy(), atol=1e-6) | ||
|
|
||
| def test_rejects_high_dimensional_input(self): | ||
| """FrechetRadiomicsDistance raises ValueError when inputs have ndimension() > 2.""" | ||
| high_dim = torch.ones([3, 3, 144, 144]) | ||
| with self.assertRaises(ValueError): | ||
| FrechetRadiomicsDistance()(high_dim, high_dim) | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| unittest.main() |
Oops, something went wrong.
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Enforce the full
(N, F)contract here.ndimension() > 2still lets 0D/1D tensors andN < 2batches fall through intoget_fid_score, where covariance estimation is not well-defined and failures get opaque. Please reject non-2D inputs and single-sample batches here, then add tests for both cases.🩹 Proposed fix
🧰 Tools
🪛 Ruff (0.15.4)
[warning] 70-70: Avoid specifying long messages outside the exception class
(TRY003)
🤖 Prompt for AI Agents