|
| 1 | +# Copyright (c) MONAI Consortium |
| 2 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 3 | +# you may not use this file except in compliance with the License. |
| 4 | +# You may obtain a copy of the License at |
| 5 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 6 | +# Unless required by applicable law or agreed to in writing, software |
| 7 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 8 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 9 | +# See the License for the specific language governing permissions and |
| 10 | +# limitations under the License. |
| 11 | + |
| 12 | +from typing import Union |
| 13 | + |
| 14 | +import torch |
| 15 | +from torch.nn.modules.loss import _Loss |
| 16 | + |
| 17 | +from monai.metrics.utils import do_metric_reduction |
| 18 | +from monai.utils import MetricReduction |
| 19 | + |
| 20 | +from .metric import CumulativeIterationMetric |
| 21 | + |
| 22 | + |
| 23 | +class LossMetric(CumulativeIterationMetric): |
| 24 | + """ |
| 25 | + A wrapper to make ``loss_fn`` available as a cumulative metric. That is, the loss values computed from |
| 26 | + mini-batches can be combined in the ``reduction`` mode across multiple iterations, as a quantitative measurement |
| 27 | + of a model. |
| 28 | +
|
| 29 | + Example: |
| 30 | +
|
| 31 | + .. code-block:: python |
| 32 | +
|
| 33 | + import torch |
| 34 | + from monai.losses import DiceLoss |
| 35 | + from monai.metrics import LossMetric |
| 36 | +
|
| 37 | + dice_loss = DiceLoss(include_background=True) |
| 38 | + loss_metric = LossMetric(loss_fn=dice_loss) |
| 39 | +
|
| 40 | + # first iteration |
| 41 | + y_pred = torch.tensor([[[[1.0, 0.0], [0.0, 1.0]]]]) # shape [batch=1, channel=1, 2, 2] |
| 42 | + y = torch.tensor([[[[1.0, 0.0], [1.0, 1.0]]]]) # shape [batch=1, channel=1, 2, 2] |
| 43 | + loss_metric(y_pred, y) |
| 44 | +
|
| 45 | + # second iteration |
| 46 | + y_pred = torch.tensor([[[[1.0, 0.0], [0.0, 0.0]]]]) # shape [batch=1, channel=1, 2, 2] |
| 47 | + y = torch.tensor([[[[1.0, 0.0], [1.0, 1.0]]]]) # shape [batch=1, channel=1, 2, 2] |
| 48 | + loss_metric(y_pred, y) |
| 49 | +
|
| 50 | + # aggregate |
| 51 | + print(loss_metric.aggregate(reduction="none")) # tensor([[0.2000], [0.5000]]) (shape [batch=2, channel=1]) |
| 52 | +
|
| 53 | + # reset |
| 54 | + loss_metric.reset() |
| 55 | + print(loss_metric.aggregate()) |
| 56 | +
|
| 57 | +
|
| 58 | + Args: |
| 59 | + loss_fn: a callable function that takes ``y_pred`` and optionally ``y`` as input (in the "batch-first" format), |
| 60 | + returns a "batch-first" tensor of loss values. |
| 61 | + reduction: define mode of reduction to the metrics, will only apply reduction on `not-nan` values, |
| 62 | + available reduction modes: {``"none"``, ``"mean"``, ``"sum"``, ``"mean_batch"``, ``"sum_batch"``, |
| 63 | + ``"mean_channel"``, ``"sum_channel"``}, default to ``"mean"``. if "none", will not do reduction. |
| 64 | + get_not_nans: whether to return the `not_nans` count, if True, aggregate() returns (metric, not_nans). |
| 65 | + Here `not_nans` count the number of not nans for the metric, thus its shape equals to the shape of the metric. |
| 66 | +
|
| 67 | + """ |
| 68 | + |
| 69 | + def __init__( |
| 70 | + self, loss_fn: _Loss, reduction: Union[MetricReduction, str] = MetricReduction.MEAN, get_not_nans: bool = False |
| 71 | + ) -> None: |
| 72 | + super().__init__() |
| 73 | + self.loss_fn = loss_fn |
| 74 | + self.reduction = reduction |
| 75 | + self.get_not_nans = get_not_nans |
| 76 | + |
| 77 | + def aggregate(self, reduction: Union[MetricReduction, str, None] = None): |
| 78 | + """ |
| 79 | + Returns the aggregated loss value across multiple iterations. |
| 80 | +
|
| 81 | + Args: |
| 82 | + reduction: define mode of reduction to the metrics, will only apply reduction on `not-nan` values, |
| 83 | + available reduction modes: {``"none"``, ``"mean"``, ``"sum"``, ``"mean_batch"``, ``"sum_batch"``, |
| 84 | + ``"mean_channel"``, ``"sum_channel"``}, default to `self.reduction`. if "none", will not do reduction. |
| 85 | + """ |
| 86 | + data = self.get_buffer() |
| 87 | + if data is None: |
| 88 | + return (torch.tensor(0.0), torch.tensor(0.0)) if self.get_not_nans else torch.tensor(0.0) |
| 89 | + f, not_nans = do_metric_reduction(data, reduction or self.reduction) |
| 90 | + return (f, not_nans) if self.get_not_nans else f |
| 91 | + |
| 92 | + def _compute_tensor(self, y_pred: torch.Tensor, y: torch.Tensor = None): # type: ignore |
| 93 | + """ |
| 94 | + Input `y_pred` is compared with ground truth `y`. |
| 95 | + Both `y_pred` and `y` are expected to be a batch-first Tensor (BC[HWD]). |
| 96 | +
|
| 97 | + Returns: |
| 98 | + a tensor with shape (BC[HWD]), or a list of tensors, each tensor with shape (C[HWD]). |
| 99 | + """ |
| 100 | + iter_loss = self.loss_fn(y_pred) if y is None else self.loss_fn(y_pred, y) |
| 101 | + if isinstance(iter_loss, torch.Tensor): |
| 102 | + while iter_loss.dim() < 2: |
| 103 | + iter_loss = iter_loss[None] |
| 104 | + # to be compatible with `Cumulative`, iter_loss should at least have a batch dim. |
| 105 | + # to be compatible with `do_metric_reduction`, iter_loss should at least have a batch and a channel dim. |
| 106 | + return iter_loss |
0 commit comments