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.

295 lines
12 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. """Detection model evaluator.
  16. This file provides a generic evaluation method that can be used to evaluate a
  17. DetectionModel.
  18. """
  19. import logging
  20. import tensorflow as tf
  21. from object_detection import eval_util
  22. from object_detection.core import prefetcher
  23. from object_detection.core import standard_fields as fields
  24. from object_detection.metrics import coco_evaluation
  25. from object_detection.utils import object_detection_evaluation
  26. # A dictionary of metric names to classes that implement the metric. The classes
  27. # in the dictionary must implement
  28. # utils.object_detection_evaluation.DetectionEvaluator interface.
  29. EVAL_METRICS_CLASS_DICT = {
  30. 'pascal_voc_detection_metrics':
  31. object_detection_evaluation.PascalDetectionEvaluator,
  32. 'weighted_pascal_voc_detection_metrics':
  33. object_detection_evaluation.WeightedPascalDetectionEvaluator,
  34. 'pascal_voc_instance_segmentation_metrics':
  35. object_detection_evaluation.PascalInstanceSegmentationEvaluator,
  36. 'weighted_pascal_voc_instance_segmentation_metrics':
  37. object_detection_evaluation.WeightedPascalInstanceSegmentationEvaluator,
  38. 'oid_V2_detection_metrics':
  39. object_detection_evaluation.OpenImagesDetectionEvaluator,
  40. # DEPRECATED: please use oid_V2_detection_metrics instead
  41. 'open_images_V2_detection_metrics':
  42. object_detection_evaluation.OpenImagesDetectionEvaluator,
  43. 'coco_detection_metrics':
  44. coco_evaluation.CocoDetectionEvaluator,
  45. 'coco_mask_metrics':
  46. coco_evaluation.CocoMaskEvaluator,
  47. 'oid_challenge_detection_metrics':
  48. object_detection_evaluation.OpenImagesDetectionChallengeEvaluator,
  49. # DEPRECATED: please use oid_challenge_detection_metrics instead
  50. 'oid_challenge_object_detection_metrics':
  51. object_detection_evaluation.OpenImagesDetectionChallengeEvaluator,
  52. }
  53. EVAL_DEFAULT_METRIC = 'pascal_voc_detection_metrics'
  54. def _extract_predictions_and_losses(model,
  55. create_input_dict_fn,
  56. ignore_groundtruth=False):
  57. """Constructs tensorflow detection graph and returns output tensors.
  58. Args:
  59. model: model to perform predictions with.
  60. create_input_dict_fn: function to create input tensor dictionaries.
  61. ignore_groundtruth: whether groundtruth should be ignored.
  62. Returns:
  63. prediction_groundtruth_dict: A dictionary with postprocessed tensors (keyed
  64. by standard_fields.DetectionResultsFields) and optional groundtruth
  65. tensors (keyed by standard_fields.InputDataFields).
  66. losses_dict: A dictionary containing detection losses. This is empty when
  67. ignore_groundtruth is true.
  68. """
  69. input_dict = create_input_dict_fn()
  70. prefetch_queue = prefetcher.prefetch(input_dict, capacity=500)
  71. input_dict = prefetch_queue.dequeue()
  72. original_image = tf.expand_dims(input_dict[fields.InputDataFields.image], 0)
  73. preprocessed_image, true_image_shapes = model.preprocess(
  74. tf.to_float(original_image))
  75. prediction_dict = model.predict(preprocessed_image, true_image_shapes)
  76. detections = model.postprocess(prediction_dict, true_image_shapes)
  77. groundtruth = None
  78. losses_dict = {}
  79. if not ignore_groundtruth:
  80. groundtruth = {
  81. fields.InputDataFields.groundtruth_boxes:
  82. input_dict[fields.InputDataFields.groundtruth_boxes],
  83. fields.InputDataFields.groundtruth_classes:
  84. input_dict[fields.InputDataFields.groundtruth_classes],
  85. fields.InputDataFields.groundtruth_area:
  86. input_dict[fields.InputDataFields.groundtruth_area],
  87. fields.InputDataFields.groundtruth_is_crowd:
  88. input_dict[fields.InputDataFields.groundtruth_is_crowd],
  89. fields.InputDataFields.groundtruth_difficult:
  90. input_dict[fields.InputDataFields.groundtruth_difficult]
  91. }
  92. if fields.InputDataFields.groundtruth_group_of in input_dict:
  93. groundtruth[fields.InputDataFields.groundtruth_group_of] = (
  94. input_dict[fields.InputDataFields.groundtruth_group_of])
  95. groundtruth_masks_list = None
  96. if fields.DetectionResultFields.detection_masks in detections:
  97. groundtruth[fields.InputDataFields.groundtruth_instance_masks] = (
  98. input_dict[fields.InputDataFields.groundtruth_instance_masks])
  99. groundtruth_masks_list = [
  100. input_dict[fields.InputDataFields.groundtruth_instance_masks]]
  101. groundtruth_keypoints_list = None
  102. if fields.DetectionResultFields.detection_keypoints in detections:
  103. groundtruth[fields.InputDataFields.groundtruth_keypoints] = (
  104. input_dict[fields.InputDataFields.groundtruth_keypoints])
  105. groundtruth_keypoints_list = [
  106. input_dict[fields.InputDataFields.groundtruth_keypoints]]
  107. label_id_offset = 1
  108. model.provide_groundtruth(
  109. [input_dict[fields.InputDataFields.groundtruth_boxes]],
  110. [tf.one_hot(input_dict[fields.InputDataFields.groundtruth_classes]
  111. - label_id_offset, depth=model.num_classes)],
  112. groundtruth_masks_list, groundtruth_keypoints_list)
  113. losses_dict.update(model.loss(prediction_dict, true_image_shapes))
  114. result_dict = eval_util.result_dict_for_single_example(
  115. original_image,
  116. input_dict[fields.InputDataFields.source_id],
  117. detections,
  118. groundtruth,
  119. class_agnostic=(
  120. fields.DetectionResultFields.detection_classes not in detections),
  121. scale_to_absolute=True)
  122. return result_dict, losses_dict
  123. def get_evaluators(eval_config, categories):
  124. """Returns the evaluator class according to eval_config, valid for categories.
  125. Args:
  126. eval_config: evaluation configurations.
  127. categories: a list of categories to evaluate.
  128. Returns:
  129. An list of instances of DetectionEvaluator.
  130. Raises:
  131. ValueError: if metric is not in the metric class dictionary.
  132. """
  133. eval_metric_fn_keys = eval_config.metrics_set
  134. if not eval_metric_fn_keys:
  135. eval_metric_fn_keys = [EVAL_DEFAULT_METRIC]
  136. evaluators_list = []
  137. for eval_metric_fn_key in eval_metric_fn_keys:
  138. if eval_metric_fn_key not in EVAL_METRICS_CLASS_DICT:
  139. raise ValueError('Metric not found: {}'.format(eval_metric_fn_key))
  140. if eval_metric_fn_key == 'oid_challenge_object_detection_metrics':
  141. logging.warning(
  142. 'oid_challenge_object_detection_metrics is deprecated; '
  143. 'use oid_challenge_detection_metrics instead'
  144. )
  145. if eval_metric_fn_key == 'oid_V2_detection_metrics':
  146. logging.warning(
  147. 'open_images_V2_detection_metrics is deprecated; '
  148. 'use oid_V2_detection_metrics instead'
  149. )
  150. evaluators_list.append(
  151. EVAL_METRICS_CLASS_DICT[eval_metric_fn_key](categories=categories))
  152. return evaluators_list
  153. def evaluate(create_input_dict_fn, create_model_fn, eval_config, categories,
  154. checkpoint_dir, eval_dir, graph_hook_fn=None, evaluator_list=None):
  155. """Evaluation function for detection models.
  156. Args:
  157. create_input_dict_fn: a function to create a tensor input dictionary.
  158. create_model_fn: a function that creates a DetectionModel.
  159. eval_config: a eval_pb2.EvalConfig protobuf.
  160. categories: a list of category dictionaries. Each dict in the list should
  161. have an integer 'id' field and string 'name' field.
  162. checkpoint_dir: directory to load the checkpoints to evaluate from.
  163. eval_dir: directory to write evaluation metrics summary to.
  164. graph_hook_fn: Optional function that is called after the training graph is
  165. completely built. This is helpful to perform additional changes to the
  166. training graph such as optimizing batchnorm. The function should modify
  167. the default graph.
  168. evaluator_list: Optional list of instances of DetectionEvaluator. If not
  169. given, this list of metrics is created according to the eval_config.
  170. Returns:
  171. metrics: A dictionary containing metric names and values from the latest
  172. run.
  173. """
  174. model = create_model_fn()
  175. if eval_config.ignore_groundtruth and not eval_config.export_path:
  176. logging.fatal('If ignore_groundtruth=True then an export_path is '
  177. 'required. Aborting!!!')
  178. tensor_dict, losses_dict = _extract_predictions_and_losses(
  179. model=model,
  180. create_input_dict_fn=create_input_dict_fn,
  181. ignore_groundtruth=eval_config.ignore_groundtruth)
  182. def _process_batch(tensor_dict, sess, batch_index, counters,
  183. losses_dict=None):
  184. """Evaluates tensors in tensor_dict, losses_dict and visualizes examples.
  185. This function calls sess.run on tensor_dict, evaluating the original_image
  186. tensor only on the first K examples and visualizing detections overlaid
  187. on this original_image.
  188. Args:
  189. tensor_dict: a dictionary of tensors
  190. sess: tensorflow session
  191. batch_index: the index of the batch amongst all batches in the run.
  192. counters: a dictionary holding 'success' and 'skipped' fields which can
  193. be updated to keep track of number of successful and failed runs,
  194. respectively. If these fields are not updated, then the success/skipped
  195. counter values shown at the end of evaluation will be incorrect.
  196. losses_dict: Optional dictonary of scalar loss tensors.
  197. Returns:
  198. result_dict: a dictionary of numpy arrays
  199. result_losses_dict: a dictionary of scalar losses. This is empty if input
  200. losses_dict is None.
  201. """
  202. try:
  203. if not losses_dict:
  204. losses_dict = {}
  205. result_dict, result_losses_dict = sess.run([tensor_dict, losses_dict])
  206. counters['success'] += 1
  207. except tf.errors.InvalidArgumentError:
  208. logging.info('Skipping image')
  209. counters['skipped'] += 1
  210. return {}, {}
  211. global_step = tf.train.global_step(sess, tf.train.get_global_step())
  212. if batch_index < eval_config.num_visualizations:
  213. tag = 'image-{}'.format(batch_index)
  214. eval_util.visualize_detection_results(
  215. result_dict,
  216. tag,
  217. global_step,
  218. categories=categories,
  219. summary_dir=eval_dir,
  220. export_dir=eval_config.visualization_export_dir,
  221. show_groundtruth=eval_config.visualize_groundtruth_boxes,
  222. groundtruth_box_visualization_color=eval_config.
  223. groundtruth_box_visualization_color,
  224. min_score_thresh=eval_config.min_score_threshold,
  225. max_num_predictions=eval_config.max_num_boxes_to_visualize,
  226. skip_scores=eval_config.skip_scores,
  227. skip_labels=eval_config.skip_labels,
  228. keep_image_id_for_visualization_export=eval_config.
  229. keep_image_id_for_visualization_export)
  230. return result_dict, result_losses_dict
  231. if graph_hook_fn: graph_hook_fn()
  232. variables_to_restore = tf.global_variables()
  233. global_step = tf.train.get_or_create_global_step()
  234. variables_to_restore.append(global_step)
  235. if eval_config.use_moving_averages:
  236. variable_averages = tf.train.ExponentialMovingAverage(0.0)
  237. variables_to_restore = variable_averages.variables_to_restore()
  238. saver = tf.train.Saver(variables_to_restore)
  239. def _restore_latest_checkpoint(sess):
  240. latest_checkpoint = tf.train.latest_checkpoint(checkpoint_dir)
  241. saver.restore(sess, latest_checkpoint)
  242. if not evaluator_list:
  243. evaluator_list = get_evaluators(eval_config, categories)
  244. metrics = eval_util.repeated_checkpoint_run(
  245. tensor_dict=tensor_dict,
  246. summary_dir=eval_dir,
  247. evaluators=evaluator_list,
  248. batch_processor=_process_batch,
  249. checkpoint_dirs=[checkpoint_dir],
  250. variables_to_restore=None,
  251. restore_fn=_restore_latest_checkpoint,
  252. num_batches=eval_config.num_examples,
  253. eval_interval_secs=eval_config.eval_interval_secs,
  254. max_number_of_evaluations=(1 if eval_config.ignore_groundtruth else
  255. eval_config.max_evals
  256. if eval_config.max_evals else None),
  257. master=eval_config.eval_master,
  258. save_graph=eval_config.save_graph,
  259. save_graph_dir=(eval_dir if eval_config.save_graph else ''),
  260. losses_dict=losses_dict,
  261. eval_export_path=eval_config.export_path)
  262. return metrics