topk_eval.py 3.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118
  1. # Copyright (c) 2024 PaddlePaddle Authors. All Rights Reserved.
  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. import argparse
  15. import json
  16. import os
  17. import paddle
  18. from ....utils import logging
  19. def parse_args():
  20. """Parse all arguments"""
  21. parser = argparse.ArgumentParser()
  22. parser.add_argument("--prediction_json_path", type=str, default="./pre_res.json")
  23. parser.add_argument("--gt_val_path", type=str, default="./val.txt")
  24. parser.add_argument("--image_dir", type=str)
  25. parser.add_argument("--num_classes", type=int)
  26. args = parser.parse_args()
  27. return args
  28. class AvgMetrics(paddle.nn.Layer):
  29. """Average metrics"""
  30. def __init__(self):
  31. super().__init__()
  32. self.avg_meters = {}
  33. @property
  34. def avg(self):
  35. """Return average value of each metric"""
  36. if self.avg_meters:
  37. for metric_key in self.avg_meters:
  38. return self.avg_meters[metric_key].avg
  39. @property
  40. def avg_info(self):
  41. """Return a formatted string of average values and names"""
  42. return ", ".join([self.avg_meters[key].avg_info for key in self.avg_meters])
  43. class TopkAcc(AvgMetrics):
  44. """Top-k accuracy metric"""
  45. def __init__(self, topk=(1, 5)):
  46. super().__init__()
  47. assert isinstance(topk, (int, list, tuple))
  48. if isinstance(topk, int):
  49. topk = [topk]
  50. self.topk = topk
  51. self.warned = False
  52. def forward(self, x, label):
  53. """forward function"""
  54. if isinstance(x, dict):
  55. x = x["logits"]
  56. output_dims = x.shape[-1]
  57. metric_dict = dict()
  58. for idx, k in enumerate(self.topk):
  59. if output_dims < k:
  60. if not self.warned:
  61. msg = f"The output dims({output_dims}) is less than k({k}), so the Top-{k} metric is meaningless."
  62. logging.info(msg)
  63. self.warned = True
  64. metric_dict[f"top{k}"] = 1
  65. else:
  66. metric_dict[f"top{k}"] = paddle.metric.accuracy(x, label, k=k).item()
  67. return metric_dict
  68. def prase_pt_info(pt_info, num_classes):
  69. """Parse prediction information to probability vector"""
  70. pre_list = [0.0] * num_classes
  71. for idx, val in zip(pt_info["class_ids"], pt_info["scores"]):
  72. pre_list[idx] = val
  73. return pre_list
  74. def main(args):
  75. """main function"""
  76. with open(args.prediction_json_path, "r") as fp:
  77. predication_result = json.load(fp)
  78. gt_info = {}
  79. pred = []
  80. label = []
  81. for line in open(args.gt_val_path):
  82. img_file, gt_label = line.strip().split(" ")
  83. img_file = img_file.split("/")[-1]
  84. gt_info[img_file] = int(gt_label)
  85. for pt_info in predication_result:
  86. img_file = os.path.relpath(pt_info["file_name"], args.image_dir)
  87. pred.append(prase_pt_info(pt_info, args.num_classes))
  88. label.append([gt_info[img_file]])
  89. metric_dict = TopkAcc()(paddle.to_tensor(pred), paddle.to_tensor(label))
  90. logging.info(metric_dict)
  91. if __name__ == "__main__":
  92. args = parse_args()
  93. main(args)