You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

util.py 6.6 kB

5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192
  1. # Copyright 2020 Huawei Technologies Co., Ltd
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. # ============================================================================
  15. """metrics utils"""
  16. import os
  17. import json
  18. import math
  19. import numpy as np
  20. from mindspore import Tensor
  21. from mindspore.common.initializer import initializer, TruncatedNormal
  22. from config import ConfigSSD
  23. from dataset import ssd_bboxes_decode
  24. def get_lr(global_step, lr_init, lr_end, lr_max, warmup_epochs, total_epochs, steps_per_epoch):
  25. """
  26. generate learning rate array
  27. Args:
  28. global_step(int): total steps of the training
  29. lr_init(float): init learning rate
  30. lr_end(float): end learning rate
  31. lr_max(float): max learning rate
  32. warmup_epochs(int): number of warmup epochs
  33. total_epochs(int): total epoch of training
  34. steps_per_epoch(int): steps of one epoch
  35. Returns:
  36. np.array, learning rate array
  37. """
  38. lr_each_step = []
  39. total_steps = steps_per_epoch * total_epochs
  40. warmup_steps = steps_per_epoch * warmup_epochs
  41. for i in range(total_steps):
  42. if i < warmup_steps:
  43. lr = lr_init + (lr_max - lr_init) * i / warmup_steps
  44. else:
  45. lr = lr_end + \
  46. (lr_max - lr_end) * \
  47. (1. + math.cos(math.pi * (i - warmup_steps) / (total_steps - warmup_steps))) / 2.
  48. if lr < 0.0:
  49. lr = 0.0
  50. lr_each_step.append(lr)
  51. current_step = global_step
  52. lr_each_step = np.array(lr_each_step).astype(np.float32)
  53. learning_rate = lr_each_step[current_step:]
  54. return learning_rate
  55. def init_net_param(network, initialize_mode='TruncatedNormal'):
  56. """Init the parameters in net."""
  57. params = network.trainable_params()
  58. for p in params:
  59. if isinstance(p.data, Tensor) and 'beta' not in p.name and 'gamma' not in p.name and 'bias' not in p.name:
  60. if initialize_mode == 'TruncatedNormal':
  61. p.set_parameter_data(initializer(TruncatedNormal(0.03), p.data.shape(), p.data.dtype()))
  62. else:
  63. p.set_parameter_data(initialize_mode, p.data.shape(), p.data.dtype())
  64. def load_backbone_params(network, param_dict):
  65. """Init the parameters from pre-train model, default is mobilenetv2."""
  66. for _, param in net.parameters_and_names():
  67. param_name = param.name.replace('network.backbone.', '')
  68. name_split = param_name.split('.')
  69. if 'features_1' in param_name:
  70. param_name = param_name.replace('features_1', 'features')
  71. if 'features_2' in param_name:
  72. param_name = '.'.join(['features', str(int(name_split[1]) + 14)] + name_split[2:])
  73. if param_name in param_dict:
  74. param.set_parameter_data(param_dict[param_name].data)
  75. def apply_nms(all_boxes, all_scores, thres, max_boxes):
  76. """Apply NMS to bboxes."""
  77. y1 = all_boxes[:, 0]
  78. x1 = all_boxes[:, 1]
  79. y2 = all_boxes[:, 2]
  80. x2 = all_boxes[:, 3]
  81. areas = (x2 - x1 + 1) * (y2 - y1 + 1)
  82. order = all_scores.argsort()[::-1]
  83. keep = []
  84. while order.size > 0:
  85. i = order[0]
  86. keep.append(i)
  87. if len(keep) >= max_boxes:
  88. break
  89. xx1 = np.maximum(x1[i], x1[order[1:]])
  90. yy1 = np.maximum(y1[i], y1[order[1:]])
  91. xx2 = np.minimum(x2[i], x2[order[1:]])
  92. yy2 = np.minimum(y2[i], y2[order[1:]])
  93. w = np.maximum(0.0, xx2 - xx1 + 1)
  94. h = np.maximum(0.0, yy2 - yy1 + 1)
  95. inter = w * h
  96. ovr = inter / (areas[i] + areas[order[1:]] - inter)
  97. inds = np.where(ovr <= thres)[0]
  98. order = order[inds + 1]
  99. return keep
  100. def metrics(pred_data):
  101. """Calculate mAP of predicted bboxes."""
  102. from pycocotools.coco import COCO
  103. from pycocotools.cocoeval import COCOeval
  104. config = ConfigSSD()
  105. num_classes = config.NUM_CLASSES
  106. coco_root = config.COCO_ROOT
  107. data_type = config.VAL_DATA_TYPE
  108. #Classes need to train or test.
  109. val_cls = config.COCO_CLASSES
  110. val_cls_dict = {}
  111. for i, cls in enumerate(val_cls):
  112. val_cls_dict[i] = cls
  113. anno_json = os.path.join(coco_root, config.INSTANCES_SET.format(data_type))
  114. coco_gt = COCO(anno_json)
  115. classs_dict = {}
  116. cat_ids = coco_gt.loadCats(coco_gt.getCatIds())
  117. for cat in cat_ids:
  118. classs_dict[cat["name"]] = cat["id"]
  119. predictions = []
  120. img_ids = []
  121. for sample in pred_data:
  122. pred_boxes = sample['boxes']
  123. box_scores = sample['box_scores']
  124. img_id = sample['img_id']
  125. h, w = sample['image_shape']
  126. pred_boxes = ssd_bboxes_decode(pred_boxes)
  127. final_boxes = []
  128. final_label = []
  129. final_score = []
  130. img_ids.append(img_id)
  131. for c in range(1, num_classes):
  132. class_box_scores = box_scores[:, c]
  133. score_mask = class_box_scores > config.MIN_SCORE
  134. class_box_scores = class_box_scores[score_mask]
  135. class_boxes = pred_boxes[score_mask] * [h, w, h, w]
  136. if score_mask.any():
  137. nms_index = apply_nms(class_boxes, class_box_scores, config.NMS_THRESHOLD, config.TOP_K)
  138. class_boxes = class_boxes[nms_index]
  139. class_box_scores = class_box_scores[nms_index]
  140. final_boxes += class_boxes.tolist()
  141. final_score += class_box_scores.tolist()
  142. final_label += [classs_dict[val_cls_dict[c]]] * len(class_box_scores)
  143. for loc, label, score in zip(final_boxes, final_label, final_score):
  144. res = {}
  145. res['image_id'] = img_id
  146. res['bbox'] = [loc[1], loc[0], loc[3] - loc[1], loc[2] - loc[0]]
  147. res['score'] = score
  148. res['category_id'] = label
  149. predictions.append(res)
  150. with open('predictions.json', 'w') as f:
  151. json.dump(predictions, f)
  152. coco_dt = coco_gt.loadRes('predictions.json')
  153. E = COCOeval(coco_gt, coco_dt, iouType='bbox')
  154. E.params.imgIds = img_ids
  155. E.evaluate()
  156. E.accumulate()
  157. E.summarize()
  158. return E.stats[0]