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

190 lines
7.0 KiB

6 years ago
  1. # Copyright 2017 The TensorFlow 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. # ==============================================================================
  15. """Functions for computing metrics like precision, recall, CorLoc and etc."""
  16. from __future__ import division
  17. import numpy as np
  18. def compute_precision_recall(scores, labels, num_gt):
  19. """Compute precision and recall.
  20. Args:
  21. scores: A float numpy array representing detection score
  22. labels: A float numpy array representing weighted true/false positive labels
  23. num_gt: Number of ground truth instances
  24. Raises:
  25. ValueError: if the input is not of the correct format
  26. Returns:
  27. precision: Fraction of positive instances over detected ones. This value is
  28. None if no ground truth labels are present.
  29. recall: Fraction of detected positive instance over all positive instances.
  30. This value is None if no ground truth labels are present.
  31. """
  32. if not isinstance(labels, np.ndarray) or len(labels.shape) != 1:
  33. raise ValueError("labels must be single dimension numpy array")
  34. if labels.dtype != np.float and labels.dtype != np.bool:
  35. raise ValueError("labels type must be either bool or float")
  36. if not isinstance(scores, np.ndarray) or len(scores.shape) != 1:
  37. raise ValueError("scores must be single dimension numpy array")
  38. if num_gt < np.sum(labels):
  39. raise ValueError("Number of true positives must be smaller than num_gt.")
  40. if len(scores) != len(labels):
  41. raise ValueError("scores and labels must be of the same size.")
  42. if num_gt == 0:
  43. return None, None
  44. sorted_indices = np.argsort(scores)
  45. sorted_indices = sorted_indices[::-1]
  46. true_positive_labels = labels[sorted_indices]
  47. false_positive_labels = (true_positive_labels <= 0).astype(float)
  48. cum_true_positives = np.cumsum(true_positive_labels)
  49. cum_false_positives = np.cumsum(false_positive_labels)
  50. precision = cum_true_positives.astype(float) / (
  51. cum_true_positives + cum_false_positives)
  52. recall = cum_true_positives.astype(float) / num_gt
  53. return precision, recall
  54. def compute_average_precision(precision, recall):
  55. """Compute Average Precision according to the definition in VOCdevkit.
  56. Precision is modified to ensure that it does not decrease as recall
  57. decrease.
  58. Args:
  59. precision: A float [N, 1] numpy array of precisions
  60. recall: A float [N, 1] numpy array of recalls
  61. Raises:
  62. ValueError: if the input is not of the correct format
  63. Returns:
  64. average_precison: The area under the precision recall curve. NaN if
  65. precision and recall are None.
  66. """
  67. if precision is None:
  68. if recall is not None:
  69. raise ValueError("If precision is None, recall must also be None")
  70. return np.NAN
  71. if not isinstance(precision, np.ndarray) or not isinstance(
  72. recall, np.ndarray):
  73. raise ValueError("precision and recall must be numpy array")
  74. if precision.dtype != np.float or recall.dtype != np.float:
  75. raise ValueError("input must be float numpy array.")
  76. if len(precision) != len(recall):
  77. raise ValueError("precision and recall must be of the same size.")
  78. if not precision.size:
  79. return 0.0
  80. if np.amin(precision) < 0 or np.amax(precision) > 1:
  81. raise ValueError("Precision must be in the range of [0, 1].")
  82. if np.amin(recall) < 0 or np.amax(recall) > 1:
  83. raise ValueError("recall must be in the range of [0, 1].")
  84. if not all(recall[i] <= recall[i + 1] for i in range(len(recall) - 1)):
  85. raise ValueError("recall must be a non-decreasing array")
  86. recall = np.concatenate([[0], recall, [1]])
  87. precision = np.concatenate([[0], precision, [0]])
  88. # Preprocess precision to be a non-decreasing array
  89. for i in range(len(precision) - 2, -1, -1):
  90. precision[i] = np.maximum(precision[i], precision[i + 1])
  91. indices = np.where(recall[1:] != recall[:-1])[0] + 1
  92. average_precision = np.sum(
  93. (recall[indices] - recall[indices - 1]) * precision[indices])
  94. return average_precision
  95. def compute_cor_loc(num_gt_imgs_per_class,
  96. num_images_correctly_detected_per_class):
  97. """Compute CorLoc according to the definition in the following paper.
  98. https://www.robots.ox.ac.uk/~vgg/rg/papers/deselaers-eccv10.pdf
  99. Returns nans if there are no ground truth images for a class.
  100. Args:
  101. num_gt_imgs_per_class: 1D array, representing number of images containing
  102. at least one object instance of a particular class
  103. num_images_correctly_detected_per_class: 1D array, representing number of
  104. images that are correctly detected at least one object instance of a
  105. particular class
  106. Returns:
  107. corloc_per_class: A float numpy array represents the corloc score of each
  108. class
  109. """
  110. return np.where(
  111. num_gt_imgs_per_class == 0, np.nan,
  112. num_images_correctly_detected_per_class / num_gt_imgs_per_class)
  113. def compute_median_rank_at_k(tp_fp_list, k):
  114. """Computes MedianRank@k, where k is the top-scoring labels.
  115. Args:
  116. tp_fp_list: a list of numpy arrays; each numpy array corresponds to the all
  117. detection on a single image, where the detections are sorted by score in
  118. descending order. Further, each numpy array element can have boolean or
  119. float values. True positive elements have either value >0.0 or True;
  120. any other value is considered false positive.
  121. k: number of top-scoring proposals to take.
  122. Returns:
  123. median_rank: median rank of all true positive proposals among top k by
  124. score.
  125. """
  126. ranks = []
  127. for i in range(len(tp_fp_list)):
  128. ranks.append(
  129. np.where(tp_fp_list[i][0:min(k, tp_fp_list[i].shape[0])] > 0)[0])
  130. concatenated_ranks = np.concatenate(ranks)
  131. return np.median(concatenated_ranks)
  132. def compute_recall_at_k(tp_fp_list, num_gt, k):
  133. """Computes Recall@k, MedianRank@k, where k is the top-scoring labels.
  134. Args:
  135. tp_fp_list: a list of numpy arrays; each numpy array corresponds to the all
  136. detection on a single image, where the detections are sorted by score in
  137. descending order. Further, each numpy array element can have boolean or
  138. float values. True positive elements have either value >0.0 or True;
  139. any other value is considered false positive.
  140. num_gt: number of groundtruth anotations.
  141. k: number of top-scoring proposals to take.
  142. Returns:
  143. recall: recall evaluated on the top k by score detections.
  144. """
  145. tp_fp_eval = []
  146. for i in range(len(tp_fp_list)):
  147. tp_fp_eval.append(tp_fp_list[i][0:min(k, tp_fp_list[i].shape[0])])
  148. tp_fp_eval = np.concatenate(tp_fp_eval)
  149. return np.sum(tp_fp_eval) / num_gt