|
| 1 | +import numpy as np |
| 2 | +import torch |
| 3 | +from torch import nn |
| 4 | + |
| 5 | +from auto_cast.types import TensorBCTSPlus |
| 6 | + |
| 7 | + |
| 8 | +class Metric(nn.Module): |
| 9 | + """ |
| 10 | + Base class for metrics. |
| 11 | +
|
| 12 | + This class standardizes the input arguments and |
| 13 | + checks the dimensions of the input tensors. |
| 14 | +
|
| 15 | + Args: |
| 16 | + f: function |
| 17 | + Metric function that takes in the following arguments: |
| 18 | + y_pred: torch.Tensor | np.ndarray |
| 19 | + Predicted values tensor. |
| 20 | + y_true: torch.Tensor | np.ndarray |
| 21 | + Target values tensor. |
| 22 | + **kwargs : dict |
| 23 | + Additional arguments for the metric. |
| 24 | + """ |
| 25 | + |
| 26 | + def forward(self, *args, **kwargs): |
| 27 | + assert len(args) >= 2, ( |
| 28 | + "At least two arguments required (y_pred, y_true, n_spatial_dims)" |
| 29 | + ) |
| 30 | + y_pred, y_true, n_spatial_dims = args[:3] |
| 31 | + |
| 32 | + # Convert y_pred and y_true to torch.Tensor if they are np.ndarray |
| 33 | + if isinstance(y_pred, np.ndarray): |
| 34 | + y_pred = torch.from_numpy(y_pred) |
| 35 | + if isinstance(y_true, np.ndarray): |
| 36 | + y_true = torch.from_numpy(y_true) |
| 37 | + assert isinstance(y_pred, torch.Tensor), ( |
| 38 | + "y_pred must be a torch.Tensor or np.ndarray" |
| 39 | + ) |
| 40 | + assert isinstance(y_true, torch.Tensor), ( |
| 41 | + "y_true must be a torch.Tensor or np.ndarray" |
| 42 | + ) |
| 43 | + |
| 44 | + # Check dimensions |
| 45 | + assert y_pred.ndim >= n_spatial_dims + 1, ( |
| 46 | + "y_pred must have at least n_spatial_dims + 1 dimensions" |
| 47 | + ) |
| 48 | + assert y_true.ndim >= n_spatial_dims + 1, ( |
| 49 | + "y_true must have at least n_spatial_dims + 1 dimensions" |
| 50 | + ) |
| 51 | + return self.score(y_pred, y_true, n_spatial_dims, **kwargs) |
| 52 | + |
| 53 | + @staticmethod |
| 54 | + def score( |
| 55 | + y_pred: TensorBCTSPlus, y_true: TensorBCTSPlus, n_spatial_dims: int, **kwargs |
| 56 | + ): |
| 57 | + raise NotImplementedError |
0 commit comments