Skip to content

Commit

Permalink
prune accuracy
Browse files Browse the repository at this point in the history
  • Loading branch information
Borda committed Mar 15, 2021
1 parent b341b53 commit 1867e61
Show file tree
Hide file tree
Showing 4 changed files with 40 additions and 382 deletions.
125 changes: 12 additions & 113 deletions pytorch_lightning/metrics/classification/accuracy.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,89 +14,16 @@
from typing import Any, Callable, Optional

import torch
from torchmetrics import Accuracy as __Accuracy

from pytorch_lightning.metrics.functional.accuracy import _accuracy_compute, _accuracy_update
from pytorch_lightning.metrics.metric import Metric
from pytorch_lightning.utilities import rank_zero_warn


class Accuracy(Metric):
class Accuracy(__Accuracy):
r"""
Computes `Accuracy <https://en.wikipedia.org/wiki/Accuracy_and_precision>`__:
.. 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)
This implementation refers to :class:`~torchmetrics.Accuracy`.
.. warning:: This metric is deprecated, use ``torchmetrics.Accuracy``. Will be removed in v1.5.0.
"""

def __init__(
Expand All @@ -109,44 +36,16 @@ def __init__(
process_group: Optional[Any] = None,
dist_sync_fn: Callable = None,
):
rank_zero_warn(
"This `Accuracy` was deprecated in v1.3.0 in favor of `torchmetrics.Accuracy`."
" It will be removed in v1.5.0", DeprecationWarning
)
super().__init__(
threshold=threshold,
top_k=top_k,
subset_accuracy=subset_accuracy,
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
"""

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.
"""
return _accuracy_compute(self.correct, self.total)
111 changes: 17 additions & 94 deletions pytorch_lightning/metrics/functional/accuracy.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,41 +11,12 @@
# 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.functional import accuracy as __accuracy

from pytorch_lightning.metrics.classification.helpers import _input_format_classification, DataType


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 import rank_zero_warn


def accuracy(
Expand All @@ -55,68 +26,20 @@ def accuracy(
top_k: Optional[int] = None,
subset_accuracy: bool = False,
) -> torch.Tensor:
r"""Computes `Accuracy <https://en.wikipedia.org/wiki/Accuracy_and_precision>`_:
.. 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)
r"""
This implementation refers to :class:`~torchmetrics.functional.accuracy`.
>>> 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)
.. warning:: This metric is deprecated, use ``torchmetrics.functional.accuracy``. Will be removed in v1.5.0.
"""

correct, total = _accuracy_update(preds, target, threshold, top_k, subset_accuracy)
return _accuracy_compute(correct, total)
rank_zero_warn(
"This `accuracy` was deprecated in v1.3.0 in favor of `torchmetrics.functional.accuracy`."
" It will be removed in v1.5.0", DeprecationWarning
)
return __accuracy(
preds=preds,
target=target,
threshold=threshold,
top_k=top_k,
subset_accuracy=subset_accuracy,
)
11 changes: 11 additions & 0 deletions tests/deprecated_api/test_remove_1-5.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
from unittest import mock

import pytest
import torch
from torch import optim

from pytorch_lightning import Callback, Trainer
Expand Down Expand Up @@ -111,3 +112,13 @@ def test_v1_5_0_model_checkpoint_period(tmpdir):
ModelCheckpoint(dirpath=tmpdir)
with pytest.deprecated_call(match="is deprecated in v1.3 and will be removed in v1.5"):
ModelCheckpoint(dirpath=tmpdir, period=1)


def test_v1_5_0_deprecated_metric_accuracy():
from pytorch_lightning.metrics import Accuracy
with pytest.deprecated_call(match='It will be removed in v1.5.0'):
Accuracy()

from pytorch_lightning.metrics.functional.accuracy import accuracy
with pytest.deprecated_call(match='It will be removed in v1.5.0'):
accuracy(preds=torch.tensor([0, 1]), target=torch.tensor([0, 1]))
Loading

0 comments on commit 1867e61

Please sign in to comment.