reid_metric.py 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138
  1. # Copyright (c) OpenMMLab. All rights reserved.
  2. from typing import Optional, Sequence, Union
  3. import numpy as np
  4. import torch
  5. from mmengine.evaluator import BaseMetric
  6. from mmdet.registry import METRICS
  7. @METRICS.register_module()
  8. class ReIDMetrics(BaseMetric):
  9. """mAP and CMC evaluation metrics for the ReID task.
  10. Args:
  11. metric (str | list[str]): Metrics to be evaluated.
  12. Default value is `mAP`.
  13. metric_options: (dict, optional): Options for calculating metrics.
  14. Allowed keys are 'rank_list' and 'max_rank'. Defaults to None.
  15. collect_device (str): Device name used for collecting results from
  16. different ranks during distributed training. Must be 'cpu' or
  17. 'gpu'. Defaults to 'cpu'.
  18. prefix (str, optional): The prefix that will be added in the metric
  19. names to disambiguate homonymous metrics of different evaluators.
  20. If prefix is not provided in the argument, self.default_prefix
  21. will be used instead. Default: None
  22. """
  23. allowed_metrics = ['mAP', 'CMC']
  24. default_prefix: Optional[str] = 'reid-metric'
  25. def __init__(self,
  26. metric: Union[str, Sequence[str]] = 'mAP',
  27. metric_options: Optional[dict] = None,
  28. collect_device: str = 'cpu',
  29. prefix: Optional[str] = None) -> None:
  30. super().__init__(collect_device, prefix)
  31. if isinstance(metric, list):
  32. metrics = metric
  33. elif isinstance(metric, str):
  34. metrics = [metric]
  35. else:
  36. raise TypeError('metric must be a list or a str.')
  37. for metric in metrics:
  38. if metric not in self.allowed_metrics:
  39. raise KeyError(f'metric {metric} is not supported.')
  40. self.metrics = metrics
  41. self.metric_options = metric_options or dict(
  42. rank_list=[1, 5, 10, 20], max_rank=20)
  43. for rank in self.metric_options['rank_list']:
  44. assert 1 <= rank <= self.metric_options['max_rank']
  45. def process(self, data_batch: dict, data_samples: Sequence[dict]) -> None:
  46. """Process one batch of data samples and predictions.
  47. The processed results should be stored in ``self.results``, which will
  48. be used to compute the metrics when all batches have been processed.
  49. Args:
  50. data_batch (dict): A batch of data from the dataloader.
  51. data_samples (Sequence[dict]): A batch of data samples that
  52. contain annotations and predictions.
  53. """
  54. for data_sample in data_samples:
  55. pred_feature = data_sample['pred_feature']
  56. assert isinstance(pred_feature, torch.Tensor)
  57. gt_label = data_sample.get('gt_label', data_sample['gt_label'])
  58. assert isinstance(gt_label['label'], torch.Tensor)
  59. result = dict(
  60. pred_feature=pred_feature.data.cpu(),
  61. gt_label=gt_label['label'].cpu())
  62. self.results.append(result)
  63. def compute_metrics(self, results: list) -> dict:
  64. """Compute the metrics from processed results.
  65. Args:
  66. results (list): The processed results of each batch.
  67. Returns:
  68. dict: The computed metrics. The keys are the names of the metrics,
  69. and the values are corresponding results.
  70. """
  71. # NOTICE: don't access `self.results` from the method.
  72. metrics = {}
  73. pids = torch.cat([result['gt_label'] for result in results]).numpy()
  74. features = torch.stack([result['pred_feature'] for result in results])
  75. n, c = features.size()
  76. mat = torch.pow(features, 2).sum(dim=1, keepdim=True).expand(n, n)
  77. distmat = mat + mat.t()
  78. distmat.addmm_(features, features.t(), beta=1, alpha=-2)
  79. distmat = distmat.numpy()
  80. indices = np.argsort(distmat, axis=1)
  81. matches = (pids[indices] == pids[:, np.newaxis]).astype(np.int32)
  82. all_cmc = []
  83. all_AP = []
  84. num_valid_q = 0.
  85. for q_idx in range(n):
  86. # remove self
  87. raw_cmc = matches[q_idx][1:]
  88. if not np.any(raw_cmc):
  89. # this condition is true when query identity
  90. # does not appear in gallery
  91. continue
  92. cmc = raw_cmc.cumsum()
  93. cmc[cmc > 1] = 1
  94. all_cmc.append(cmc[:self.metric_options['max_rank']])
  95. num_valid_q += 1.
  96. # compute average precision
  97. num_rel = raw_cmc.sum()
  98. tmp_cmc = raw_cmc.cumsum()
  99. tmp_cmc = [x / (i + 1.) for i, x in enumerate(tmp_cmc)]
  100. tmp_cmc = np.asarray(tmp_cmc) * raw_cmc
  101. AP = tmp_cmc.sum() / num_rel
  102. all_AP.append(AP)
  103. assert num_valid_q > 0, \
  104. 'Error: all query identities do not appear in gallery'
  105. all_cmc = np.asarray(all_cmc)
  106. all_cmc = all_cmc.sum(0) / num_valid_q
  107. mAP = np.mean(all_AP)
  108. if 'mAP' in self.metrics:
  109. metrics['mAP'] = np.around(mAP, decimals=3)
  110. if 'CMC' in self.metrics:
  111. for rank in self.metric_options['rank_list']:
  112. metrics[f'R{rank}'] = np.around(all_cmc[rank - 1], decimals=3)
  113. return metrics