base_dataset.py 7.51 KB
Newer Older
1
# Copyright (c) OpenMMLab. All rights reserved.
unknown's avatar
unknown committed
2
import copy
3
import os.path as osp
unknown's avatar
unknown committed
4
from abc import ABCMeta, abstractmethod
5
6
from os import PathLike
from typing import List
unknown's avatar
unknown committed
7
8
9
10
11
12
13
14
15
16

import mmcv
import numpy as np
from torch.utils.data import Dataset

from mmcls.core.evaluation import precision_recall_f1, support
from mmcls.models.losses import accuracy
from .pipelines import Compose


17
18
19
20
21
22
23
def expanduser(path):
    if isinstance(path, (str, PathLike)):
        return osp.expanduser(path)
    else:
        return path


unknown's avatar
unknown committed
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
class BaseDataset(Dataset, metaclass=ABCMeta):
    """Base dataset.

    Args:
        data_prefix (str): the prefix of data path
        pipeline (list): a list of dict, where each element represents
            a operation defined in `mmcls.datasets.pipelines`
        ann_file (str | None): the annotation file. When ann_file is str,
            the subclass is expected to read from the ann_file. When ann_file
            is None, the subclass is expected to read according to data_prefix
        test_mode (bool): in train mode or test mode
    """

    CLASSES = None

    def __init__(self,
                 data_prefix,
                 pipeline,
                 classes=None,
                 ann_file=None,
                 test_mode=False):
        super(BaseDataset, self).__init__()
46
        self.data_prefix = expanduser(data_prefix)
unknown's avatar
unknown committed
47
48
        self.pipeline = Compose(pipeline)
        self.CLASSES = self.get_classes(classes)
49
50
        self.ann_file = expanduser(ann_file)
        self.test_mode = test_mode
unknown's avatar
unknown committed
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
        self.data_infos = self.load_annotations()

    @abstractmethod
    def load_annotations(self):
        pass

    @property
    def class_to_idx(self):
        """Map mapping class name to class index.

        Returns:
            dict: mapping from class name to class index.
        """

        return {_class: i for i, _class in enumerate(self.CLASSES)}

    def get_gt_labels(self):
        """Get all ground-truth labels (categories).

        Returns:
71
            np.ndarray: categories for all images.
unknown's avatar
unknown committed
72
73
74
75
76
        """

        gt_labels = np.array([data['gt_label'] for data in self.data_infos])
        return gt_labels

77
    def get_cat_ids(self, idx: int) -> List[int]:
unknown's avatar
unknown committed
78
79
80
81
82
83
        """Get category id by index.

        Args:
            idx (int): Index of data.

        Returns:
84
            cat_ids (List[int]): Image category of specified index.
unknown's avatar
unknown committed
85
86
        """

87
        return [int(self.data_infos[idx]['gt_label'])]
unknown's avatar
unknown committed
88
89
90
91
92
93
94
95
96
97
98
99
100
101

    def prepare_data(self, idx):
        results = copy.deepcopy(self.data_infos[idx])
        return self.pipeline(results)

    def __len__(self):
        return len(self.data_infos)

    def __getitem__(self, idx):
        return self.prepare_data(idx)

    @classmethod
    def get_classes(cls, classes=None):
        """Get class names of current dataset.
102

unknown's avatar
unknown committed
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
        Args:
            classes (Sequence[str] | str | None): If classes is None, use
                default CLASSES defined by builtin dataset. If classes is a
                string, take it as a file name. The file contains the name of
                classes where each line contains one class name. If classes is
                a tuple or list, override the CLASSES defined by the dataset.

        Returns:
            tuple[str] or list[str]: Names of categories of the dataset.
        """
        if classes is None:
            return cls.CLASSES

        if isinstance(classes, str):
            # take it as a file path
118
            class_names = mmcv.list_from_file(expanduser(classes))
unknown's avatar
unknown committed
119
120
121
122
123
124
125
126
127
128
129
        elif isinstance(classes, (tuple, list)):
            class_names = classes
        else:
            raise ValueError(f'Unsupported type {type(classes)} of classes.')

        return class_names

    def evaluate(self,
                 results,
                 metric='accuracy',
                 metric_options=None,
130
                 indices=None,
unknown's avatar
unknown committed
131
132
133
134
135
136
137
138
139
140
                 logger=None):
        """Evaluate the dataset.

        Args:
            results (list): Testing results of the dataset.
            metric (str | list[str]): Metrics to be evaluated.
                Default value is `accuracy`.
            metric_options (dict, optional): Options for calculating metrics.
                Allowed keys are 'topk', 'thrs' and 'average_mode'.
                Defaults to None.
141
142
            indices (list, optional): The indices of samples corresponding to
                the results. Defaults to None.
unknown's avatar
unknown committed
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
            logger (logging.Logger | str, optional): Logger used for printing
                related information during evaluation. Defaults to None.
        Returns:
            dict: evaluation results
        """
        if metric_options is None:
            metric_options = {'topk': (1, 5)}
        if isinstance(metric, str):
            metrics = [metric]
        else:
            metrics = metric
        allowed_metrics = [
            'accuracy', 'precision', 'recall', 'f1_score', 'support'
        ]
        eval_results = {}
        results = np.vstack(results)
        gt_labels = self.get_gt_labels()
160
161
        if indices is not None:
            gt_labels = gt_labels[indices]
unknown's avatar
unknown committed
162
163
164
165
166
167
        num_imgs = len(results)
        assert len(gt_labels) == num_imgs, 'dataset testing results should '\
            'be of the same length as gt_labels.'

        invalid_metrics = set(metrics) - set(allowed_metrics)
        if len(invalid_metrics) != 0:
168
            raise ValueError(f'metric {invalid_metrics} is not supported.')
unknown's avatar
unknown committed
169
170
171
172
173
174

        topk = metric_options.get('topk', (1, 5))
        thrs = metric_options.get('thrs')
        average_mode = metric_options.get('average_mode', 'macro')

        if 'accuracy' in metrics:
175
176
177
178
            if thrs is not None:
                acc = accuracy(results, gt_labels, topk=topk, thrs=thrs)
            else:
                acc = accuracy(results, gt_labels, topk=topk)
unknown's avatar
unknown committed
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
            if isinstance(topk, tuple):
                eval_results_ = {
                    f'accuracy_top-{k}': a
                    for k, a in zip(topk, acc)
                }
            else:
                eval_results_ = {'accuracy': acc}
            if isinstance(thrs, tuple):
                for key, values in eval_results_.items():
                    eval_results.update({
                        f'{key}_thr_{thr:.2f}': value.item()
                        for thr, value in zip(thrs, values)
                    })
            else:
                eval_results.update(
                    {k: v.item()
                     for k, v in eval_results_.items()})

        if 'support' in metrics:
            support_value = support(
                results, gt_labels, average_mode=average_mode)
            eval_results['support'] = support_value

        precision_recall_f1_keys = ['precision', 'recall', 'f1_score']
        if len(set(metrics) & set(precision_recall_f1_keys)) != 0:
204
205
206
207
208
209
            if thrs is not None:
                precision_recall_f1_values = precision_recall_f1(
                    results, gt_labels, average_mode=average_mode, thrs=thrs)
            else:
                precision_recall_f1_values = precision_recall_f1(
                    results, gt_labels, average_mode=average_mode)
unknown's avatar
unknown committed
210
211
212
213
214
215
216
217
218
219
220
221
            for key, values in zip(precision_recall_f1_keys,
                                   precision_recall_f1_values):
                if key in metrics:
                    if isinstance(thrs, tuple):
                        eval_results.update({
                            f'{key}_thr_{thr:.2f}': value
                            for thr, value in zip(thrs, values)
                        })
                    else:
                        eval_results[key] = values

        return eval_results