From 2f6ce1ae7fff34d16d3707571f6a9a7b0fb0c50a Mon Sep 17 00:00:00 2001 From: Jirka Borovec Date: Wed, 17 Mar 2021 12:37:10 +0100 Subject: [PATCH] prune metric: accuracy 4/n (#6515) * prune accuracy * chlog * flake8 * Apply suggestions from code review Co-authored-by: Nicki Skafte * wrap * test * test * fix Co-authored-by: Nicki Skafte --- CHANGELOG.md | 2 + .../metrics/classification/accuracy.py | 127 +------------ .../metrics/functional/accuracy.py | 103 +--------- .../deprecated_api/test_remove_1-5_metrics.py | 19 +- tests/metrics/classification/test_accuracy.py | 176 ------------------ 5 files changed, 32 insertions(+), 395 deletions(-) delete mode 100644 tests/metrics/classification/test_accuracy.py diff --git a/CHANGELOG.md b/CHANGELOG.md index f60d13f493dcb..cc78de0f9c0c1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -75,6 +75,8 @@ The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/). [#6547](https://github.com/PyTorchLightning/pytorch-lightning/pull/6547), + [#6515](https://github.com/PyTorchLightning/pytorch-lightning/pull/6515), + ) diff --git a/pytorch_lightning/metrics/classification/accuracy.py b/pytorch_lightning/metrics/classification/accuracy.py index 367c9b029d841..b9d0a45e6fd33 100644 --- a/pytorch_lightning/metrics/classification/accuracy.py +++ b/pytorch_lightning/metrics/classification/accuracy.py @@ -13,92 +13,14 @@ # limitations under the License. from typing import Any, Callable, Optional -import torch -from torchmetrics import Metric +from torchmetrics import Accuracy as _Accuracy -from pytorch_lightning.metrics.functional.accuracy import _accuracy_compute, _accuracy_update +from pytorch_lightning.utilities.deprecation import deprecated -class Accuracy(Metric): - r""" - Computes `Accuracy `__: - - .. math:: - \text{Accuracy} = \frac{1}{N}\sum_i^N 1(y_i = \hat{y}_i) - - Where :math:`y` is a tensor of target values, and :math:`\hat{y}` is a - tensor of predictions. - - For multi-class and multi-dimensional multi-class data with probability predictions, the - parameter ``top_k`` generalizes this metric to a Top-K accuracy metric: for each sample the - top-K highest probability items are considered to find the correct label. - - For multi-label and multi-dimensional multi-class inputs, this metric computes the "global" - accuracy by default, which counts all labels or sub-samples separately. This can be - changed to subset accuracy (which requires all labels or sub-samples in the sample to - be correctly predicted) by setting ``subset_accuracy=True``. - - Args: - threshold: - Threshold probability value for transforming probability predictions to binary - (0,1) predictions, in the case of binary or multi-label inputs. - top_k: - Number of highest probability predictions considered to find the correct label, relevant - only for (multi-dimensional) multi-class inputs with probability predictions. The - default value (``None``) will be interpreted as 1 for these inputs. - - Should be left at default (``None``) for all other types of inputs. - subset_accuracy: - Whether to compute subset accuracy for multi-label and multi-dimensional - multi-class inputs (has no effect for other input types). - - - For multi-label inputs, if the parameter is set to ``True``, then all labels for - each sample must be correctly predicted for the sample to count as correct. If it - is set to ``False``, then all labels are counted separately - this is equivalent to - flattening inputs beforehand (i.e. ``preds = preds.flatten()`` and same for ``target``). - - - For multi-dimensional multi-class inputs, if the parameter is set to ``True``, then all - sub-sample (on the extra axis) must be correct for the sample to be counted as correct. - If it is set to ``False``, then all sub-samples are counter separately - this is equivalent, - in the case of label predictions, to flattening the inputs beforehand (i.e. - ``preds = preds.flatten()`` and same for ``target``). Note that the ``top_k`` parameter - still applies in both cases, if set. - - compute_on_step: - Forward only calls ``update()`` and return ``None`` if this is set to ``False``. - dist_sync_on_step: - Synchronize metric state across processes at each ``forward()`` - before returning the value at the step - process_group: - Specify the process group on which synchronization is called. - default: ``None`` (which selects the entire world) - dist_sync_fn: - Callback that performs the allgather operation on the metric state. When ``None``, DDP - will be used to perform the allgather - - Raises: - ValueError: - If ``threshold`` is not between ``0`` and ``1``. - ValueError: - If ``top_k`` is not an ``integer`` larger than ``0``. - - Example: - - >>> from pytorch_lightning.metrics import Accuracy - >>> target = torch.tensor([0, 1, 2, 3]) - >>> preds = torch.tensor([0, 2, 1, 3]) - >>> accuracy = Accuracy() - >>> accuracy(preds, target) - tensor(0.5000) - - >>> target = torch.tensor([0, 1, 2]) - >>> preds = torch.tensor([[0.1, 0.9, 0], [0.3, 0.1, 0.6], [0.2, 0.5, 0.3]]) - >>> accuracy = Accuracy(top_k=2) - >>> accuracy(preds, target) - tensor(0.6667) - - """ +class Accuracy(_Accuracy): + @deprecated(target=_Accuracy, ver_deprecate="1.3.0", ver_remove="1.5.0") def __init__( self, threshold: float = 0.5, @@ -109,44 +31,9 @@ def __init__( process_group: Optional[Any] = None, dist_sync_fn: Callable = None, ): - super().__init__( - compute_on_step=compute_on_step, - dist_sync_on_step=dist_sync_on_step, - process_group=process_group, - dist_sync_fn=dist_sync_fn, - ) - - self.add_state("correct", default=torch.tensor(0), dist_reduce_fx="sum") - self.add_state("total", default=torch.tensor(0), dist_reduce_fx="sum") - - if not 0 < threshold < 1: - raise ValueError(f"The `threshold` should be a float in the (0,1) interval, got {threshold}") - - if top_k is not None and (not isinstance(top_k, int) or top_k <= 0): - raise ValueError(f"The `top_k` should be an integer larger than 0, got {top_k}") - - self.threshold = threshold - self.top_k = top_k - self.subset_accuracy = subset_accuracy - - def update(self, preds: torch.Tensor, target: torch.Tensor): - """ - Update state with predictions and targets. - - Args: - preds: Predictions from model (probabilities, or labels) - target: Ground truth labels """ + This implementation refers to :class:`~torchmetrics.Accuracy`. - correct, total = _accuracy_update( - preds, target, threshold=self.threshold, top_k=self.top_k, subset_accuracy=self.subset_accuracy - ) - - self.correct += correct - self.total += total - - def compute(self) -> torch.Tensor: - """ - Computes accuracy based on inputs passed in to ``update`` previously. + .. deprecated:: + Use :class:`~torchmetrics.Accuracy`. Will be removed in v1.5.0. """ - return _accuracy_compute(self.correct, self.total) diff --git a/pytorch_lightning/metrics/functional/accuracy.py b/pytorch_lightning/metrics/functional/accuracy.py index 53a47611cd49a..601442cd01202 100644 --- a/pytorch_lightning/metrics/functional/accuracy.py +++ b/pytorch_lightning/metrics/functional/accuracy.py @@ -11,43 +11,15 @@ # 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 typing import Optional, Tuple +from typing import Optional import torch -from torchmetrics.classification.checks import _input_format_classification -from torchmetrics.utilities.enums import DataType +from torchmetrics.functional import accuracy as _accuracy - -def _accuracy_update( - preds: torch.Tensor, target: torch.Tensor, threshold: float, top_k: Optional[int], subset_accuracy: bool -) -> Tuple[torch.Tensor, torch.Tensor]: - - preds, target, mode = _input_format_classification(preds, target, threshold=threshold, top_k=top_k) - - if mode == DataType.MULTILABEL and top_k: - raise ValueError("You can not use the `top_k` parameter to calculate accuracy for multi-label inputs.") - - if mode == DataType.BINARY or (mode == DataType.MULTILABEL and subset_accuracy): - correct = (preds == target).all(dim=1).sum() - total = torch.tensor(target.shape[0], device=target.device) - elif mode == DataType.MULTILABEL and not subset_accuracy: - correct = (preds == target).sum() - total = torch.tensor(target.numel(), device=target.device) - elif mode == DataType.MULTICLASS or (mode == DataType.MULTIDIM_MULTICLASS and not subset_accuracy): - correct = (preds * target).sum() - total = target.sum() - elif mode == DataType.MULTIDIM_MULTICLASS and subset_accuracy: - sample_correct = (preds * target).sum(dim=(1, 2)) - correct = (sample_correct == target.shape[2]).sum() - total = torch.tensor(target.shape[0], device=target.device) - - return correct, total - - -def _accuracy_compute(correct: torch.Tensor, total: torch.Tensor) -> torch.Tensor: - return correct.float() / total +from pytorch_lightning.utilities.deprecation import deprecated +@deprecated(target=_accuracy, ver_deprecate="1.3.0", ver_remove="1.5.0") def accuracy( preds: torch.Tensor, target: torch.Tensor, @@ -55,68 +27,7 @@ def accuracy( top_k: Optional[int] = None, subset_accuracy: bool = False, ) -> torch.Tensor: - r"""Computes `Accuracy `_: - - .. math:: - \text{Accuracy} = \frac{1}{N}\sum_i^N 1(y_i = \hat{y}_i) - - Where :math:`y` is a tensor of target values, and :math:`\hat{y}` is a - tensor of predictions. - - For multi-class and multi-dimensional multi-class data with probability predictions, the - parameter ``top_k`` generalizes this metric to a Top-K accuracy metric: for each sample the - top-K highest probability items are considered to find the correct label. - - For multi-label and multi-dimensional multi-class inputs, this metric computes the "global" - accuracy by default, which counts all labels or sub-samples separately. This can be - changed to subset accuracy (which requires all labels or sub-samples in the sample to - be correctly predicted) by setting ``subset_accuracy=True``. - - Args: - preds: Predictions from model (probabilities, or labels) - target: Ground truth labels - threshold: - Threshold probability value for transforming probability predictions to binary - (0,1) predictions, in the case of binary or multi-label inputs. - top_k: - Number of highest probability predictions considered to find the correct label, relevant - only for (multi-dimensional) multi-class inputs with probability predictions. The - default value (``None``) will be interpreted as 1 for these inputs. - - Should be left at default (``None``) for all other types of inputs. - subset_accuracy: - Whether to compute subset accuracy for multi-label and multi-dimensional - multi-class inputs (has no effect for other input types). - - - For multi-label inputs, if the parameter is set to ``True``, then all labels for - each sample must be correctly predicted for the sample to count as correct. If it - is set to ``False``, then all labels are counted separately - this is equivalent to - flattening inputs beforehand (i.e. ``preds = preds.flatten()`` and same for ``target``). - - - For multi-dimensional multi-class inputs, if the parameter is set to ``True``, then all - sub-sample (on the extra axis) must be correct for the sample to be counted as correct. - If it is set to ``False``, then all sub-samples are counter separately - this is equivalent, - in the case of label predictions, to flattening the inputs beforehand (i.e. - ``preds = preds.flatten()`` and same for ``target``). Note that the ``top_k`` parameter - still applies in both cases, if set. - - Raises: - ValueError: - If ``top_k`` parameter is set for ``multi-label`` inputs. - - Example: - - >>> from pytorch_lightning.metrics.functional import accuracy - >>> target = torch.tensor([0, 1, 2, 3]) - >>> preds = torch.tensor([0, 2, 1, 3]) - >>> accuracy(preds, target) - tensor(0.5000) - - >>> target = torch.tensor([0, 1, 2]) - >>> preds = torch.tensor([[0.1, 0.9, 0], [0.3, 0.1, 0.6], [0.2, 0.5, 0.3]]) - >>> accuracy(preds, target, top_k=2) - tensor(0.6667) """ - - correct, total = _accuracy_update(preds, target, threshold, top_k, subset_accuracy) - return _accuracy_compute(correct, total) + .. deprecated:: + Use :func:`torchmetrics.functional.accuracy`. Will be removed in v1.5.0. + """ diff --git a/tests/deprecated_api/test_remove_1-5_metrics.py b/tests/deprecated_api/test_remove_1-5_metrics.py index 3428c0b761e93..239241dfac2ed 100644 --- a/tests/deprecated_api/test_remove_1-5_metrics.py +++ b/tests/deprecated_api/test_remove_1-5_metrics.py @@ -17,10 +17,11 @@ import torch from pytorch_lightning.metrics import Accuracy, MetricCollection +from pytorch_lightning.metrics.functional.accuracy import accuracy from pytorch_lightning.metrics.utils import get_num_classes, select_topk, to_categorical, to_onehot -def test_v1_5_0_metrics_utils(): +def test_v1_5_metrics_utils(): x = torch.tensor([1, 2, 3]) with pytest.deprecated_call(match="It will be removed in v1.5.0"): assert torch.equal(to_onehot(x), torch.Tensor([[0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]]).to(int)) @@ -37,12 +38,24 @@ def test_v1_5_0_metrics_utils(): assert torch.equal(to_categorical(x), torch.Tensor([1, 0]).to(int)) -def test_v1_5_0_metrics_collection(): +def test_v1_5_metric_accuracy(): + accuracy.warned = False + with pytest.deprecated_call(match='It will be removed in v1.5.0'): + assert accuracy(preds=torch.tensor([0, 1]), target=torch.tensor([0, 1])) == torch.tensor(1.) + + Accuracy.__init__.warned = False + with pytest.deprecated_call(match='It will be removed in v1.5.0'): + Accuracy() + + +def test_v1_5_metrics_collection(): target = torch.tensor([0, 2, 0, 2, 0, 1, 0, 2]) preds = torch.tensor([2, 1, 2, 0, 1, 2, 2, 2]) + + MetricCollection.__init__.warned = False with pytest.deprecated_call( match="`pytorch_lightning.metrics.metric.MetricCollection` was deprecated since v1.3.0 in favor" " of `torchmetrics.collections.MetricCollection`. It will be removed in v1.5.0." ): metrics = MetricCollection([Accuracy()]) - assert metrics(preds, target) == {'Accuracy': torch.Tensor([0.1250])[0]} + assert metrics(preds, target) == {'Accuracy': torch.tensor(0.1250)} diff --git a/tests/metrics/classification/test_accuracy.py b/tests/metrics/classification/test_accuracy.py deleted file mode 100644 index 63a4870ed422e..0000000000000 --- a/tests/metrics/classification/test_accuracy.py +++ /dev/null @@ -1,176 +0,0 @@ -from functools import partial - -import numpy as np -import pytest -import torch -from sklearn.metrics import accuracy_score as sk_accuracy -from torchmetrics.classification.checks import _input_format_classification -from torchmetrics.utilities.enums import DataType - -from pytorch_lightning.metrics import Accuracy -from pytorch_lightning.metrics.functional import accuracy -from tests.metrics.classification.inputs import _input_binary, _input_binary_prob -from tests.metrics.classification.inputs import _input_multiclass as _input_mcls -from tests.metrics.classification.inputs import _input_multiclass_prob as _input_mcls_prob -from tests.metrics.classification.inputs import _input_multidim_multiclass as _input_mdmc -from tests.metrics.classification.inputs import _input_multidim_multiclass_prob as _input_mdmc_prob -from tests.metrics.classification.inputs import _input_multilabel as _input_mlb -from tests.metrics.classification.inputs import _input_multilabel_multidim as _input_mlmd -from tests.metrics.classification.inputs import _input_multilabel_multidim_prob as _input_mlmd_prob -from tests.metrics.classification.inputs import _input_multilabel_prob as _input_mlb_prob -from tests.metrics.utils import MetricTester, THRESHOLD - -torch.manual_seed(42) - - -def _sk_accuracy(preds, target, subset_accuracy): - sk_preds, sk_target, mode = _input_format_classification(preds, target, threshold=THRESHOLD) - sk_preds, sk_target = sk_preds.numpy(), sk_target.numpy() - - if mode == DataType.MULTIDIM_MULTICLASS and not subset_accuracy: - sk_preds, sk_target = np.transpose(sk_preds, (0, 2, 1)), np.transpose(sk_target, (0, 2, 1)) - sk_preds, sk_target = sk_preds.reshape(-1, sk_preds.shape[2]), sk_target.reshape(-1, sk_target.shape[2]) - elif mode == DataType.MULTIDIM_MULTICLASS and subset_accuracy: - return np.all(sk_preds == sk_target, axis=(1, 2)).mean() - elif mode == DataType.MULTILABEL and not subset_accuracy: - sk_preds, sk_target = sk_preds.reshape(-1), sk_target.reshape(-1) - - return sk_accuracy(y_true=sk_target, y_pred=sk_preds) - - -@pytest.mark.parametrize( - "preds, target, subset_accuracy", - [ - (_input_binary_prob.preds, _input_binary_prob.target, False), - (_input_binary.preds, _input_binary.target, False), - (_input_mlb_prob.preds, _input_mlb_prob.target, True), - (_input_mlb_prob.preds, _input_mlb_prob.target, False), - (_input_mlb.preds, _input_mlb.target, True), - (_input_mlb.preds, _input_mlb.target, False), - (_input_mcls_prob.preds, _input_mcls_prob.target, False), - (_input_mcls.preds, _input_mcls.target, False), - (_input_mdmc_prob.preds, _input_mdmc_prob.target, False), - (_input_mdmc_prob.preds, _input_mdmc_prob.target, True), - (_input_mdmc.preds, _input_mdmc.target, False), - (_input_mdmc.preds, _input_mdmc.target, True), - (_input_mlmd_prob.preds, _input_mlmd_prob.target, True), - (_input_mlmd_prob.preds, _input_mlmd_prob.target, False), - (_input_mlmd.preds, _input_mlmd.target, True), - (_input_mlmd.preds, _input_mlmd.target, False), - ], -) -class TestAccuracies(MetricTester): - - @pytest.mark.parametrize("ddp", [False, True]) - @pytest.mark.parametrize("dist_sync_on_step", [False, True]) - def test_accuracy_class(self, ddp, dist_sync_on_step, preds, target, subset_accuracy): - self.run_class_metric_test( - ddp=ddp, - preds=preds, - target=target, - metric_class=Accuracy, - sk_metric=partial(_sk_accuracy, subset_accuracy=subset_accuracy), - dist_sync_on_step=dist_sync_on_step, - metric_args={ - "threshold": THRESHOLD, - "subset_accuracy": subset_accuracy - }, - ) - - def test_accuracy_fn(self, preds, target, subset_accuracy): - self.run_functional_metric_test( - preds, - target, - metric_functional=accuracy, - sk_metric=partial(_sk_accuracy, subset_accuracy=subset_accuracy), - metric_args={ - "threshold": THRESHOLD, - "subset_accuracy": subset_accuracy - }, - ) - - -_l1to4 = [0.1, 0.2, 0.3, 0.4] -_l1to4t3 = np.array([_l1to4, _l1to4, _l1to4]) -_l1to4t3_mcls = [_l1to4t3.T, _l1to4t3.T, _l1to4t3.T] - -# The preds in these examples always put highest probability on class 3, second highest on class 2, -# third highest on class 1, and lowest on class 0 -_topk_preds_mcls = torch.tensor([_l1to4t3, _l1to4t3]).float() -_topk_target_mcls = torch.tensor([[1, 2, 3], [2, 1, 0]]) - -# This is like for MC case, but one sample in each batch is sabotaged with 0 class prediction :) -_topk_preds_mdmc = torch.tensor([_l1to4t3_mcls, _l1to4t3_mcls]).float() -_topk_target_mdmc = torch.tensor([[[1, 1, 0], [2, 2, 2], [3, 3, 3]], [[2, 2, 0], [1, 1, 1], [0, 0, 0]]]) - - -# Replace with a proper sk_metric test once sklearn 0.24 hits :) -@pytest.mark.parametrize( - "preds, target, exp_result, k, subset_accuracy", - [ - (_topk_preds_mcls, _topk_target_mcls, 1 / 6, 1, False), - (_topk_preds_mcls, _topk_target_mcls, 3 / 6, 2, False), - (_topk_preds_mcls, _topk_target_mcls, 5 / 6, 3, False), - (_topk_preds_mcls, _topk_target_mcls, 1 / 6, 1, True), - (_topk_preds_mcls, _topk_target_mcls, 3 / 6, 2, True), - (_topk_preds_mcls, _topk_target_mcls, 5 / 6, 3, True), - (_topk_preds_mdmc, _topk_target_mdmc, 1 / 6, 1, False), - (_topk_preds_mdmc, _topk_target_mdmc, 8 / 18, 2, False), - (_topk_preds_mdmc, _topk_target_mdmc, 13 / 18, 3, False), - (_topk_preds_mdmc, _topk_target_mdmc, 1 / 6, 1, True), - (_topk_preds_mdmc, _topk_target_mdmc, 2 / 6, 2, True), - (_topk_preds_mdmc, _topk_target_mdmc, 3 / 6, 3, True), - ], -) -def test_topk_accuracy(preds, target, exp_result, k, subset_accuracy): - topk = Accuracy(top_k=k, subset_accuracy=subset_accuracy) - - for batch in range(preds.shape[0]): - topk(preds[batch], target[batch]) - - assert topk.compute() == exp_result - - # Test functional - total_samples = target.shape[0] * target.shape[1] - - preds = preds.view(total_samples, 4, -1) - target = target.view(total_samples, -1) - - assert accuracy(preds, target, top_k=k, subset_accuracy=subset_accuracy) == exp_result - - -# Only MC and MDMC with probs input type should be accepted for top_k -@pytest.mark.parametrize( - "preds, target", - [ - (_input_binary_prob.preds, _input_binary_prob.target), - (_input_binary.preds, _input_binary.target), - (_input_mlb_prob.preds, _input_mlb_prob.target), - (_input_mlb.preds, _input_mlb.target), - (_input_mcls.preds, _input_mcls.target), - (_input_mdmc.preds, _input_mdmc.target), - (_input_mlmd_prob.preds, _input_mlmd_prob.target), - (_input_mlmd.preds, _input_mlmd.target), - ], -) -def test_topk_accuracy_wrong_input_types(preds, target): - topk = Accuracy(top_k=1) - - with pytest.raises(ValueError): - topk(preds[0], target[0]) - - with pytest.raises(ValueError): - accuracy(preds[0], target[0], top_k=1) - - -@pytest.mark.parametrize("top_k, threshold", [(0, 0.5), (None, 1.5)]) -def test_wrong_params(top_k, threshold): - preds, target = _input_mcls_prob.preds, _input_mcls_prob.target - - with pytest.raises(ValueError): - acc = Accuracy(threshold=threshold, top_k=top_k) - acc(preds, target) - acc.compute() - - with pytest.raises(ValueError): - accuracy(preds, target, threshold=threshold, top_k=top_k)