base.py 8.27 KB
Newer Older
1
# Copyright (c) OpenMMLab. All rights reserved.
unknown's avatar
unknown committed
2
3
from abc import ABCMeta, abstractmethod
from collections import OrderedDict
4
from typing import Sequence
unknown's avatar
unknown committed
5
6
7
8

import mmcv
import torch
import torch.distributed as dist
9
from mmcv.runner import BaseModule, auto_fp16
unknown's avatar
unknown committed
10

11
from mmcls.core.visualization import imshow_infos
unknown's avatar
unknown committed
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29


class BaseClassifier(BaseModule, metaclass=ABCMeta):
    """Base class for classifiers."""

    def __init__(self, init_cfg=None):
        super(BaseClassifier, self).__init__(init_cfg)
        self.fp16_enabled = False

    @property
    def with_neck(self):
        return hasattr(self, 'neck') and self.neck is not None

    @property
    def with_head(self):
        return hasattr(self, 'head') and self.head is not None

    @abstractmethod
30
    def extract_feat(self, imgs, stage=None):
unknown's avatar
unknown committed
31
32
        pass

33
34
35
    def extract_feats(self, imgs, stage=None):
        assert isinstance(imgs, Sequence)
        kwargs = {} if stage is None else {'stage': stage}
unknown's avatar
unknown committed
36
        for img in imgs:
37
            yield self.extract_feat(img, **kwargs)
unknown's avatar
unknown committed
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113

    @abstractmethod
    def forward_train(self, imgs, **kwargs):
        """
        Args:
            img (list[Tensor]): List of tensors of shape (1, C, H, W).
                Typically these should be mean centered and std scaled.
            kwargs (keyword arguments): Specific to concrete implementation.
        """
        pass

    @abstractmethod
    def simple_test(self, img, **kwargs):
        pass

    def forward_test(self, imgs, **kwargs):
        """
        Args:
            imgs (List[Tensor]): the outer list indicates test-time
                augmentations and inner Tensor should have a shape NxCxHxW,
                which contains all images in the batch.
        """
        if isinstance(imgs, torch.Tensor):
            imgs = [imgs]
        for var, name in [(imgs, 'imgs')]:
            if not isinstance(var, list):
                raise TypeError(f'{name} must be a list, but got {type(var)}')

        if len(imgs) == 1:
            return self.simple_test(imgs[0], **kwargs)
        else:
            raise NotImplementedError('aug_test has not been implemented')

    @auto_fp16(apply_to=('img', ))
    def forward(self, img, return_loss=True, **kwargs):
        """Calls either forward_train or forward_test depending on whether
        return_loss=True.

        Note this setting will change the expected inputs. When
        `return_loss=True`, img and img_meta are single-nested (i.e. Tensor and
        List[dict]), and when `resturn_loss=False`, img and img_meta should be
        double nested (i.e.  List[Tensor], List[List[dict]]), with the outer
        list indicating test time augmentations.
        """
        if return_loss:
            return self.forward_train(img, **kwargs)
        else:
            return self.forward_test(img, **kwargs)

    def _parse_losses(self, losses):
        log_vars = OrderedDict()
        for loss_name, loss_value in losses.items():
            if isinstance(loss_value, torch.Tensor):
                log_vars[loss_name] = loss_value.mean()
            elif isinstance(loss_value, list):
                log_vars[loss_name] = sum(_loss.mean() for _loss in loss_value)
            elif isinstance(loss_value, dict):
                for name, value in loss_value.items():
                    log_vars[name] = value
            else:
                raise TypeError(
                    f'{loss_name} is not a tensor or list of tensors')

        loss = sum(_value for _key, _value in log_vars.items()
                   if 'loss' in _key)

        log_vars['loss'] = loss
        for loss_name, loss_value in log_vars.items():
            # reduce loss when distributed training
            if dist.is_available() and dist.is_initialized():
                loss_value = loss_value.data.clone()
                dist.all_reduce(loss_value.div_(dist.get_world_size()))
            log_vars[loss_name] = loss_value.item()

        return loss, log_vars

114
    def train_step(self, data, optimizer=None, **kwargs):
unknown's avatar
unknown committed
115
116
117
118
119
120
121
122
123
124
        """The iteration step during training.

        This method defines an iteration step during training, except for the
        back propagation and optimizer updating, which are done in an optimizer
        hook. Note that in some complicated cases or models, the whole process
        including back propagation and optimizer updating are also defined in
        this method, such as GAN.

        Args:
            data (dict): The output of dataloader.
125
126
127
            optimizer (:obj:`torch.optim.Optimizer` | dict, optional): The
                optimizer of runner is passed to ``train_step()``. This
                argument is unused and reserved.
unknown's avatar
unknown committed
128
129

        Returns:
130
131
132
133
134
135
136
137
            dict: Dict of outputs. The following fields are contained.
                - loss (torch.Tensor): A tensor for back propagation, which \
                    can be a weighted sum of multiple losses.
                - log_vars (dict): Dict contains all the variables to be sent \
                    to the logger.
                - num_samples (int): Indicates the batch size (when the model \
                    is DDP, it means the batch size on each GPU), which is \
                    used for averaging the logs.
unknown's avatar
unknown committed
138
139
140
141
142
143
144
145
146
        """
        losses = self(**data)
        loss, log_vars = self._parse_losses(losses)

        outputs = dict(
            loss=loss, log_vars=log_vars, num_samples=len(data['img'].data))

        return outputs

147
    def val_step(self, data, optimizer=None, **kwargs):
unknown's avatar
unknown committed
148
149
150
151
152
        """The iteration step during validation.

        This method shares the same signature as :func:`train_step`, but used
        during val epochs. Note that the evaluation after training epochs is
        not implemented with this method, but an evaluation hook.
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168

        Args:
            data (dict): The output of dataloader.
            optimizer (:obj:`torch.optim.Optimizer` | dict, optional): The
                optimizer of runner is passed to ``train_step()``. This
                argument is unused and reserved.

        Returns:
            dict: Dict of outputs. The following fields are contained.
                - loss (torch.Tensor): A tensor for back propagation, which \
                    can be a weighted sum of multiple losses.
                - log_vars (dict): Dict contains all the variables to be sent \
                    to the logger.
                - num_samples (int): Indicates the batch size (when the model \
                    is DDP, it means the batch size on each GPU), which is \
                    used for averaging the logs.
unknown's avatar
unknown committed
169
170
171
172
173
174
175
176
177
178
179
180
        """
        losses = self(**data)
        loss, log_vars = self._parse_losses(losses)

        outputs = dict(
            loss=loss, log_vars=log_vars, num_samples=len(data['img'].data))

        return outputs

    def show_result(self,
                    img,
                    result,
181
                    text_color='white',
unknown's avatar
unknown committed
182
183
184
                    font_scale=0.5,
                    row_width=20,
                    show=False,
185
                    fig_size=(15, 10),
unknown's avatar
unknown committed
186
187
188
189
190
191
                    win_name='',
                    wait_time=0,
                    out_file=None):
        """Draw `result` over `img`.

        Args:
192
193
            img (str or ndarray): The image to be displayed.
            result (dict): The classification results to draw over `img`.
unknown's avatar
unknown committed
194
195
196
197
198
            text_color (str or tuple or :obj:`Color`): Color of texts.
            font_scale (float): Font scales of texts.
            row_width (int): width between each row of results on the image.
            show (bool): Whether to show the image.
                Default: False.
199
            fig_size (tuple): Image show figure size. Defaults to (15, 10).
unknown's avatar
unknown committed
200
            win_name (str): The window name.
201
202
            wait_time (int): How many seconds to display the image.
                Defaults to 0.
unknown's avatar
unknown committed
203
204
205
206
            out_file (str or None): The filename to write the image.
                Default: None.

        Returns:
207
            img (ndarray): Image with overlaid results.
unknown's avatar
unknown committed
208
209
210
211
        """
        img = mmcv.imread(img)
        img = img.copy()

212
213
214
215
216
217
218
219
220
221
222
223
224
        img = imshow_infos(
            img,
            result,
            text_color=text_color,
            font_size=int(font_scale * 50),
            row_width=row_width,
            win_name=win_name,
            show=show,
            fig_size=fig_size,
            wait_time=wait_time,
            out_file=out_file)

        return img