spearmancorrcoef
Metric
SpearmanCorrCoeffromtorchmetrics(torchmetrics.SpearmanCorrCoef)
When to invoke this skill
The user has predictions + ground truth and asks to evaluate with SpearmanCorrCoef, or
mentions torchmetrics.SpearmanCorrCoef directly, or wants the standard torchmetrics implementation.
Reference signature
from torchmetrics import SpearmanCorrCoef
# SpearmanCorrCoef(num_outputs: int = 1, **kwargs: Any) -> None
Library docstring
Compute `spearmans rank correlation coefficient`_.
.. math:
r_s = = \frac{cov(rg_x, rg_y)}{\sigma_{rg_x} * \sigma_{rg_y}}
where :math:`rg_x` and :math:`rg_y` are the rank associated to the variables :math:`x` and :math:`y`.
Spearmans correlations coefficient corresponds to the standard pearsons correlation coefficient calculated
on the rank variables.
As input to ``forward`` and ``update`` the metric accepts the following input:
- ``preds`` (:class:`~torch.Tensor`): Predictions from model in float tensor with shape ``(N,d)``
- ``target`` (:class:`~torch.Tensor`): Ground truth values in float tensor with shape ``(N,d)``
As output of ``forward`` and ``compute`` the metric returns the following output:
- ``spearman`` (:class:`~torch.Tensor`): A tensor with the spearman correlation(s)
Args:
num_outputs: Number of outputs in multioutput setting
kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info.
Example (single output regression):
>>> from torch import tensor
>>> from torchmetrics.regression import SpearmanCorrCoef
>>> target = tensor([3, -0.5, 2, 7])
>>> preds = tensor([2.5, 0.0, 2, 8])
>>> spearman = SpearmanCorrCoef()
>>> spearman(preds, target)
tensor(1.0000)
Example (multi output regression):
>>> from torchmetrics.regression import SpearmanCorrCoef
>>> target = tensor([[3, -0.5], [2, 7]])
>>> preds = tensor([[2.5, 0.0], [2, 8]])
>>> spearman = SpearmanCorrCoef(num_outputs=2)
>>> spearman(preds, target)
tensor([1.0000, 1.0000])
Quick recipe
import torchmetrics as _m
score = _m.SpearmanCorrCoef(y_true, y_pred)
Don'ts
- Don't reimplement when the library version handles edge cases (NaN, ties, empty inputs) better than a hand-rolled formula.
- Always check the library version's argument order — sklearn is
(y_true, y_pred)while torchmetrics is(preds, target).