|
| 1 | +from typing import Any, Callable, Tuple, Union |
| 2 | + |
| 3 | +import torch |
| 4 | + |
| 5 | +from torch import Tensor |
| 6 | + |
| 7 | +from ignite.exceptions import NotComputableError |
| 8 | +from ignite.metrics.epoch_metric import EpochMetric |
| 9 | +from ignite.metrics.regression._base import _check_output_shapes, _check_output_types |
| 10 | + |
| 11 | + |
| 12 | +def _get_kendall_tau(variant: str = "b") -> Callable[[Tensor, Tensor], float]: |
| 13 | + from scipy.stats import kendalltau |
| 14 | + |
| 15 | + if variant not in ("b", "c"): |
| 16 | + raise ValueError(f"variant accepts 'b' or 'c', got {variant!r}.") |
| 17 | + |
| 18 | + def _tau(predictions: Tensor, targets: Tensor) -> float: |
| 19 | + np_preds = predictions.flatten().numpy() |
| 20 | + np_targets = targets.flatten().numpy() |
| 21 | + r = kendalltau(np_preds, np_targets, variant=variant).statistic |
| 22 | + return r |
| 23 | + |
| 24 | + return _tau |
| 25 | + |
| 26 | + |
| 27 | +class KendallRankCorrelation(EpochMetric): |
| 28 | + r"""Calculates the |
| 29 | + `Kendall rank correlation coefficient <https://en.wikipedia.org/wiki/Kendall_rank_correlation_coefficient>`_. |
| 30 | +
|
| 31 | + .. math:: |
| 32 | + \tau = 1-\frac{2(\text{number of discordant pairs})}{\left( \begin{array}{c}n\\2\end{array} \right)} |
| 33 | +
|
| 34 | + Two prediction-target pairs :math:`(P_i, A_i)` and :math:`(P_j, A_j)`, where :math:`i<j`, |
| 35 | + are said to be concordant when both :math:`P_i<P_j` and :math:`A_i<A_j` holds |
| 36 | + or both :math:`P_i>P_j` and :math:`A_i>A_j`. |
| 37 | +
|
| 38 | + The `number of discordant pairs` counts the number of pairs that are not concordant. |
| 39 | +
|
| 40 | + The computation of this metric is implemented with |
| 41 | + `scipy.stats.kendalltau <https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.kendalltau.html>`_. |
| 42 | +
|
| 43 | + - ``update`` must receive output of the form ``(y_pred, y)`` or ``{'y_pred': y_pred, 'y': y}``. |
| 44 | + - `y` and `y_pred` must be of same shape `(N, )` or `(N, 1)`. |
| 45 | +
|
| 46 | + Parameters are inherited from ``Metric.__init__``. |
| 47 | +
|
| 48 | + Args: |
| 49 | + variant: variant of kendall rank correlation. ``b`` or ``c`` is accepted. |
| 50 | + Details can be found |
| 51 | + `here <https://en.wikipedia.org/wiki/Kendall_rank_correlation_coefficient#Accounting_for_ties>`_. |
| 52 | + Default: ``b`` |
| 53 | + output_transform: a callable that is used to transform the |
| 54 | + :class:`~ignite.engine.engine.Engine`'s ``process_function``'s output into the |
| 55 | + form expected by the metric. This can be useful if, for example, you have a multi-output model and |
| 56 | + you want to compute the metric with respect to one of the outputs. |
| 57 | + By default, metrics require the output as ``(y_pred, y)`` or ``{'y_pred': y_pred, 'y': y}``. |
| 58 | + device: specifies which device updates are accumulated on. Setting the |
| 59 | + metric's device to be the same as your ``update`` arguments ensures the ``update`` method is |
| 60 | + non-blocking. By default, CPU. |
| 61 | +
|
| 62 | + Examples: |
| 63 | + To use with ``Engine`` and ``process_function``, simply attach the metric instance to the engine. |
| 64 | + The output of the engine's ``process_function`` needs to be in format of |
| 65 | + ``(y_pred, y)`` or ``{'y_pred': y_pred, 'y': y, ...}``. |
| 66 | +
|
| 67 | + .. include:: defaults.rst |
| 68 | + :start-after: :orphan: |
| 69 | +
|
| 70 | + .. testcode:: |
| 71 | +
|
| 72 | + metric = KendallRankCorrelation() |
| 73 | + metric.attach(default_evaluator, 'kendall_tau') |
| 74 | + y_true = torch.tensor([0., 1., 2., 3., 4., 5.]) |
| 75 | + y_pred = torch.tensor([0.5, 2.8, 1.9, 1.3, 6.0, 4.1]) |
| 76 | + state = default_evaluator.run([[y_pred, y_true]]) |
| 77 | + print(state.metrics['kendall_tau']) |
| 78 | +
|
| 79 | + .. testoutput:: |
| 80 | +
|
| 81 | + 0.4666666666666666 |
| 82 | + """ |
| 83 | + |
| 84 | + def __init__( |
| 85 | + self, |
| 86 | + variant: str = "b", |
| 87 | + output_transform: Callable[..., Any] = lambda x: x, |
| 88 | + check_compute_fn: bool = True, |
| 89 | + device: Union[str, torch.device] = torch.device("cpu"), |
| 90 | + skip_unrolling: bool = False, |
| 91 | + ) -> None: |
| 92 | + try: |
| 93 | + from scipy.stats import kendalltau # noqa: F401 |
| 94 | + except ImportError: |
| 95 | + raise ModuleNotFoundError("This module requires scipy to be installed.") |
| 96 | + |
| 97 | + super().__init__(_get_kendall_tau(variant), output_transform, check_compute_fn, device, skip_unrolling) |
| 98 | + |
| 99 | + def update(self, output: Tuple[torch.Tensor, torch.Tensor]) -> None: |
| 100 | + y_pred, y = output[0].detach(), output[1].detach() |
| 101 | + if y_pred.ndim == 1: |
| 102 | + y_pred = y_pred.unsqueeze(1) |
| 103 | + if y.ndim == 1: |
| 104 | + y = y.unsqueeze(1) |
| 105 | + |
| 106 | + _check_output_shapes(output) |
| 107 | + _check_output_types(output) |
| 108 | + |
| 109 | + super().update(output) |
| 110 | + |
| 111 | + def compute(self) -> float: |
| 112 | + if len(self._predictions) < 1 or len(self._targets) < 1: |
| 113 | + raise NotComputableError("KendallRankCorrelation must have at least one example before it can be computed.") |
| 114 | + |
| 115 | + return super().compute() |
0 commit comments