accuracy.py 4.66 KB
Newer Older
1
2
3
# Copyright (c) OpenMMLab. All rights reserved.
from numbers import Number

unknown's avatar
unknown committed
4
5
6
7
8
import numpy as np
import torch
import torch.nn as nn


9
10
def accuracy_numpy(pred, target, topk=(1, ), thrs=0.):
    if isinstance(thrs, Number):
unknown's avatar
unknown committed
11
12
13
14
15
16
        thrs = (thrs, )
        res_single = True
    elif isinstance(thrs, tuple):
        res_single = False
    else:
        raise TypeError(
17
            f'thrs should be a number or tuple, but got {type(thrs)}.')
unknown's avatar
unknown committed
18
19
20
21

    res = []
    maxk = max(topk)
    num = pred.shape[0]
22
23
24
25
26
27
28
29

    static_inds = np.indices((num, maxk))[0]
    pred_label = pred.argpartition(-maxk, axis=1)[:, -maxk:]
    pred_score = pred[static_inds, pred_label]

    sort_inds = np.argsort(pred_score, axis=1)[:, ::-1]
    pred_label = pred_label[static_inds, sort_inds]
    pred_score = pred_score[static_inds, sort_inds]
unknown's avatar
unknown committed
30
31
32
33
34
35
36
37

    for k in topk:
        correct_k = pred_label[:, :k] == target.reshape(-1, 1)
        res_thr = []
        for thr in thrs:
            # Only prediction values larger than thr are counted as correct
            _correct_k = correct_k & (pred_score[:, :k] > thr)
            _correct_k = np.logical_or.reduce(_correct_k, axis=1)
38
            res_thr.append((_correct_k.sum() * 100. / num))
unknown's avatar
unknown committed
39
40
41
42
43
44
45
        if res_single:
            res.append(res_thr[0])
        else:
            res.append(res_thr)
    return res


46
47
def accuracy_torch(pred, target, topk=(1, ), thrs=0.):
    if isinstance(thrs, Number):
unknown's avatar
unknown committed
48
49
50
51
52
53
        thrs = (thrs, )
        res_single = True
    elif isinstance(thrs, tuple):
        res_single = False
    else:
        raise TypeError(
54
            f'thrs should be a number or tuple, but got {type(thrs)}.')
unknown's avatar
unknown committed
55
56
57
58

    res = []
    maxk = max(topk)
    num = pred.size(0)
59
    pred = pred.float()
unknown's avatar
unknown committed
60
61
62
63
64
65
66
67
68
    pred_score, pred_label = pred.topk(maxk, dim=1)
    pred_label = pred_label.t()
    correct = pred_label.eq(target.view(1, -1).expand_as(pred_label))
    for k in topk:
        res_thr = []
        for thr in thrs:
            # Only prediction values larger than thr are counted as correct
            _correct = correct & (pred_score.t() > thr)
            correct_k = _correct[:k].reshape(-1).float().sum(0, keepdim=True)
69
            res_thr.append((correct_k.mul_(100. / num)))
unknown's avatar
unknown committed
70
71
72
73
74
75
76
        if res_single:
            res.append(res_thr[0])
        else:
            res.append(res_thr)
    return res


77
def accuracy(pred, target, topk=1, thrs=0.):
unknown's avatar
unknown committed
78
79
80
81
82
83
84
85
    """Calculate accuracy according to the prediction and target.

    Args:
        pred (torch.Tensor | np.array): The model prediction.
        target (torch.Tensor | np.array): The target of each prediction
        topk (int | tuple[int]): If the predictions in ``topk``
            matches the target, the predictions will be regarded as
            correct ones. Defaults to 1.
86
87
        thrs (Number | tuple[Number], optional): Predictions with scores under
            the thresholds are considered negative. Default to 0.
unknown's avatar
unknown committed
88
89

    Returns:
90
91
92
93
94
        torch.Tensor | list[torch.Tensor] | list[list[torch.Tensor]]: Accuracy
            - torch.Tensor: If both ``topk`` and ``thrs`` is a single value.
            - list[torch.Tensor]: If one of ``topk`` or ``thrs`` is a tuple.
            - list[list[torch.Tensor]]: If both ``topk`` and ``thrs`` is a \
              tuple. And the first dim is ``topk``, the second dim is ``thrs``.
unknown's avatar
unknown committed
95
96
97
98
99
100
101
102
    """
    assert isinstance(topk, (int, tuple))
    if isinstance(topk, int):
        topk = (topk, )
        return_single = True
    else:
        return_single = False

103
104
105
106
107
108
109
110
111
112
113
114
115
116
    assert isinstance(pred, (torch.Tensor, np.ndarray)), \
        f'The pred should be torch.Tensor or np.ndarray ' \
        f'instead of {type(pred)}.'
    assert isinstance(target, (torch.Tensor, np.ndarray)), \
        f'The target should be torch.Tensor or np.ndarray ' \
        f'instead of {type(target)}.'

    # torch version is faster in most situations.
    to_tensor = (lambda x: torch.from_numpy(x)
                 if isinstance(x, np.ndarray) else x)
    pred = to_tensor(pred)
    target = to_tensor(target)

    res = accuracy_torch(pred, target, topk, thrs)
unknown's avatar
unknown committed
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140

    return res[0] if return_single else res


class Accuracy(nn.Module):

    def __init__(self, topk=(1, )):
        """Module to calculate the accuracy.

        Args:
            topk (tuple): The criterion used to calculate the
                accuracy. Defaults to (1,).
        """
        super().__init__()
        self.topk = topk

    def forward(self, pred, target):
        """Forward function to calculate accuracy.

        Args:
            pred (torch.Tensor): Prediction of models.
            target (torch.Tensor): Target for each prediction.

        Returns:
141
            list[torch.Tensor]: The accuracies under different topk criterions.
unknown's avatar
unknown committed
142
143
        """
        return accuracy(pred, target, self.topk)