|
1 | 1 | # Copyright (c) OpenMMLab. All rights reserved.
|
| 2 | +import bisect |
| 3 | +from itertools import chain |
| 4 | + |
| 5 | +import mmcv |
| 6 | +import numpy as np |
| 7 | +from mmcv.utils import print_log |
2 | 8 | from torch.utils.data.dataset import ConcatDataset as _ConcatDataset
|
3 | 9 |
|
4 | 10 | from .builder import DATASETS
|
| 11 | +from .cityscapes import CityscapesDataset |
5 | 12 |
|
6 | 13 |
|
7 | 14 | @DATASETS.register_module()
|
8 | 15 | class ConcatDataset(_ConcatDataset):
|
9 | 16 | """A wrapper of concatenated dataset.
|
10 | 17 |
|
11 | 18 | Same as :obj:`torch.utils.data.dataset.ConcatDataset`, but
|
12 |
| - concat the group flag for image aspect ratio. |
| 19 | + support evaluation and formatting results |
13 | 20 |
|
14 | 21 | Args:
|
15 | 22 | datasets (list[:obj:`Dataset`]): A list of datasets.
|
| 23 | + separate_eval (bool): Whether to evaluate the concatenated |
| 24 | + dataset results separately, Defaults to True. |
16 | 25 | """
|
17 | 26 |
|
18 |
| - def __init__(self, datasets): |
| 27 | + def __init__(self, datasets, separate_eval=True): |
19 | 28 | super(ConcatDataset, self).__init__(datasets)
|
20 | 29 | self.CLASSES = datasets[0].CLASSES
|
21 | 30 | self.PALETTE = datasets[0].PALETTE
|
| 31 | + self.separate_eval = separate_eval |
| 32 | + assert separate_eval in [True, False], \ |
| 33 | + f'separate_eval can only be True or False,' \ |
| 34 | + f'but get {separate_eval}' |
| 35 | + if any([isinstance(ds, CityscapesDataset) for ds in datasets]): |
| 36 | + raise NotImplementedError( |
| 37 | + 'Evaluating ConcatDataset containing CityscapesDataset' |
| 38 | + 'is not supported!') |
| 39 | + |
| 40 | + def evaluate(self, results, logger=None, **kwargs): |
| 41 | + """Evaluate the results. |
| 42 | +
|
| 43 | + Args: |
| 44 | + results (list[tuple[torch.Tensor]] | list[str]]): per image |
| 45 | + pre_eval results or predict segmentation map for |
| 46 | + computing evaluation metric. |
| 47 | + logger (logging.Logger | str | None): Logger used for printing |
| 48 | + related information during evaluation. Default: None. |
| 49 | +
|
| 50 | + Returns: |
| 51 | + dict[str: float]: evaluate results of the total dataset |
| 52 | + or each separate |
| 53 | + dataset if `self.separate_eval=True`. |
| 54 | + """ |
| 55 | + assert len(results) == self.cumulative_sizes[-1], \ |
| 56 | + ('Dataset and results have different sizes: ' |
| 57 | + f'{self.cumulative_sizes[-1]} v.s. {len(results)}') |
| 58 | + |
| 59 | + # Check whether all the datasets support evaluation |
| 60 | + for dataset in self.datasets: |
| 61 | + assert hasattr(dataset, 'evaluate'), \ |
| 62 | + f'{type(dataset)} does not implement evaluate function' |
| 63 | + |
| 64 | + if self.separate_eval: |
| 65 | + dataset_idx = -1 |
| 66 | + total_eval_results = dict() |
| 67 | + for size, dataset in zip(self.cumulative_sizes, self.datasets): |
| 68 | + start_idx = 0 if dataset_idx == -1 else \ |
| 69 | + self.cumulative_sizes[dataset_idx] |
| 70 | + end_idx = self.cumulative_sizes[dataset_idx + 1] |
| 71 | + |
| 72 | + results_per_dataset = results[start_idx:end_idx] |
| 73 | + print_log( |
| 74 | + f'\nEvaluateing {dataset.img_dir} with ' |
| 75 | + f'{len(results_per_dataset)} images now', |
| 76 | + logger=logger) |
| 77 | + |
| 78 | + eval_results_per_dataset = dataset.evaluate( |
| 79 | + results_per_dataset, logger=logger, **kwargs) |
| 80 | + dataset_idx += 1 |
| 81 | + for k, v in eval_results_per_dataset.items(): |
| 82 | + total_eval_results.update({f'{dataset_idx}_{k}': v}) |
| 83 | + |
| 84 | + return total_eval_results |
| 85 | + |
| 86 | + if len(set([type(ds) for ds in self.datasets])) != 1: |
| 87 | + raise NotImplementedError( |
| 88 | + 'All the datasets should have same types when ' |
| 89 | + 'self.separate_eval=False') |
| 90 | + else: |
| 91 | + if mmcv.is_list_of(results, np.ndarray) or mmcv.is_list_of( |
| 92 | + results, str): |
| 93 | + # merge the generators of gt_seg_maps |
| 94 | + gt_seg_maps = chain( |
| 95 | + *[dataset.get_gt_seg_maps() for dataset in self.datasets]) |
| 96 | + else: |
| 97 | + # if the results are `pre_eval` results, |
| 98 | + # we do not need gt_seg_maps to evaluate |
| 99 | + gt_seg_maps = None |
| 100 | + eval_results = self.datasets[0].evaluate( |
| 101 | + results, gt_seg_maps=gt_seg_maps, logger=logger, **kwargs) |
| 102 | + return eval_results |
| 103 | + |
| 104 | + def get_dataset_idx_and_sample_idx(self, indice): |
| 105 | + """Return dataset and sample index when given an indice of |
| 106 | + ConcatDataset. |
| 107 | +
|
| 108 | + Args: |
| 109 | + indice (int): indice of sample in ConcatDataset |
| 110 | +
|
| 111 | + Returns: |
| 112 | + int: the index of sub dataset the sample belong to |
| 113 | + int: the index of sample in its corresponding subset |
| 114 | + """ |
| 115 | + if indice < 0: |
| 116 | + if -indice > len(self): |
| 117 | + raise ValueError( |
| 118 | + 'absolute value of index should not exceed dataset length') |
| 119 | + indice = len(self) + indice |
| 120 | + dataset_idx = bisect.bisect_right(self.cumulative_sizes, indice) |
| 121 | + if dataset_idx == 0: |
| 122 | + sample_idx = indice |
| 123 | + else: |
| 124 | + sample_idx = indice - self.cumulative_sizes[dataset_idx - 1] |
| 125 | + return dataset_idx, sample_idx |
| 126 | + |
| 127 | + def format_results(self, results, imgfile_prefix, indices=None, **kwargs): |
| 128 | + """format result for every sample of ConcatDataset.""" |
| 129 | + if indices is None: |
| 130 | + indices = list(range(len(self))) |
| 131 | + |
| 132 | + assert isinstance(results, list), 'results must be a list.' |
| 133 | + assert isinstance(indices, list), 'indices must be a list.' |
| 134 | + |
| 135 | + ret_res = [] |
| 136 | + for i, indice in enumerate(indices): |
| 137 | + dataset_idx, sample_idx = self.get_dataset_idx_and_sample_idx( |
| 138 | + indice) |
| 139 | + res = self.datasets[dataset_idx].format_results( |
| 140 | + [results[i]], |
| 141 | + imgfile_prefix + f'/{dataset_idx}', |
| 142 | + indices=[sample_idx], |
| 143 | + **kwargs) |
| 144 | + ret_res.append(res) |
| 145 | + return sum(ret_res, []) |
| 146 | + |
| 147 | + def pre_eval(self, preds, indices): |
| 148 | + """do pre eval for every sample of ConcatDataset.""" |
| 149 | + # In order to compat with batch inference |
| 150 | + if not isinstance(indices, list): |
| 151 | + indices = [indices] |
| 152 | + if not isinstance(preds, list): |
| 153 | + preds = [preds] |
| 154 | + ret_res = [] |
| 155 | + for i, indice in enumerate(indices): |
| 156 | + dataset_idx, sample_idx = self.get_dataset_idx_and_sample_idx( |
| 157 | + indice) |
| 158 | + res = self.datasets[dataset_idx].pre_eval(preds[i], sample_idx) |
| 159 | + ret_res.append(res) |
| 160 | + return sum(ret_res, []) |
22 | 161 |
|
23 | 162 |
|
24 | 163 | @DATASETS.register_module()
|
|
0 commit comments