eval_image_classifier.py 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192
  1. # Copyright 2016 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. """Generic evaluation script that evaluates a model using a given dataset."""
  16. from __future__ import absolute_import
  17. from __future__ import division
  18. from __future__ import print_function
  19. import math
  20. import tensorflow as tf
  21. from datasets import dataset_factory
  22. from nets import nets_factory
  23. from preprocessing import preprocessing_factory
  24. slim = tf.contrib.slim
  25. tf.app.flags.DEFINE_integer(
  26. 'batch_size', 100, 'The number of samples in each batch.')
  27. tf.app.flags.DEFINE_integer(
  28. 'max_num_batches', None,
  29. 'Max number of batches to evaluate by default use all.')
  30. tf.app.flags.DEFINE_string(
  31. 'master', '', 'The address of the TensorFlow master to use.')
  32. tf.app.flags.DEFINE_string(
  33. 'checkpoint_path', '/tmp/tfmodel/',
  34. 'The directory where the model was written to or an absolute path to a '
  35. 'checkpoint file.')
  36. tf.app.flags.DEFINE_string(
  37. 'eval_dir', '/tmp/tfmodel/', 'Directory where the results are saved to.')
  38. tf.app.flags.DEFINE_integer(
  39. 'num_preprocessing_threads', 4,
  40. 'The number of threads used to create the batches.')
  41. tf.app.flags.DEFINE_string(
  42. 'dataset_name', 'imagenet', 'The name of the dataset to load.')
  43. tf.app.flags.DEFINE_string(
  44. 'dataset_split_name', 'test', 'The name of the train/test split.')
  45. tf.app.flags.DEFINE_string(
  46. 'dataset_dir', None, 'The directory where the dataset files are stored.')
  47. tf.app.flags.DEFINE_integer(
  48. 'labels_offset', 0,
  49. 'An offset for the labels in the dataset. This flag is primarily used to '
  50. 'evaluate the VGG and ResNet architectures which do not use a background '
  51. 'class for the ImageNet dataset.')
  52. tf.app.flags.DEFINE_string(
  53. 'model_name', 'inception_v3', 'The name of the architecture to evaluate.')
  54. tf.app.flags.DEFINE_string(
  55. 'preprocessing_name', None, 'The name of the preprocessing to use. If left '
  56. 'as `None`, then the model_name flag is used.')
  57. tf.app.flags.DEFINE_float(
  58. 'moving_average_decay', None,
  59. 'The decay to use for the moving average.'
  60. 'If left as None, then moving averages are not used.')
  61. tf.app.flags.DEFINE_integer(
  62. 'eval_image_size', None, 'Eval image size')
  63. FLAGS = tf.app.flags.FLAGS
  64. def main(_):
  65. if not FLAGS.dataset_dir:
  66. raise ValueError('You must supply the dataset directory with --dataset_dir')
  67. tf.logging.set_verbosity(tf.logging.INFO)
  68. with tf.Graph().as_default():
  69. tf_global_step = slim.get_or_create_global_step()
  70. ######################
  71. # Select the dataset #
  72. ######################
  73. dataset = dataset_factory.get_dataset(
  74. FLAGS.dataset_name, FLAGS.dataset_split_name, FLAGS.dataset_dir)
  75. ####################
  76. # Select the model #
  77. ####################
  78. network_fn = nets_factory.get_network_fn(
  79. FLAGS.model_name,
  80. num_classes=(dataset.num_classes - FLAGS.labels_offset),
  81. is_training=False)
  82. ##############################################################
  83. # Create a dataset provider that loads data from the dataset #
  84. ##############################################################
  85. provider = slim.dataset_data_provider.DatasetDataProvider(
  86. dataset,
  87. shuffle=False,
  88. common_queue_capacity=2 * FLAGS.batch_size,
  89. common_queue_min=FLAGS.batch_size)
  90. [image, label] = provider.get(['image', 'label'])
  91. label -= FLAGS.labels_offset
  92. #####################################
  93. # Select the preprocessing function #
  94. #####################################
  95. preprocessing_name = FLAGS.preprocessing_name or FLAGS.model_name
  96. image_preprocessing_fn = preprocessing_factory.get_preprocessing(
  97. preprocessing_name,
  98. is_training=False)
  99. eval_image_size = FLAGS.eval_image_size or network_fn.default_image_size
  100. image = image_preprocessing_fn(image, eval_image_size, eval_image_size)
  101. images, labels = tf.train.batch(
  102. [image, label],
  103. batch_size=FLAGS.batch_size,
  104. num_threads=FLAGS.num_preprocessing_threads,
  105. capacity=5 * FLAGS.batch_size)
  106. ####################
  107. # Define the model #
  108. ####################
  109. logits, _ = network_fn(images)
  110. if FLAGS.moving_average_decay:
  111. variable_averages = tf.train.ExponentialMovingAverage(
  112. FLAGS.moving_average_decay, tf_global_step)
  113. variables_to_restore = variable_averages.variables_to_restore(
  114. slim.get_model_variables())
  115. variables_to_restore[tf_global_step.op.name] = tf_global_step
  116. else:
  117. variables_to_restore = slim.get_variables_to_restore()
  118. predictions = tf.argmax(logits, 1)
  119. labels = tf.squeeze(labels)
  120. # Define the metrics:
  121. names_to_values, names_to_updates = slim.metrics.aggregate_metric_map({
  122. 'Accuracy': slim.metrics.streaming_accuracy(predictions, labels),
  123. 'Recall_5': slim.metrics.streaming_recall_at_k(
  124. logits, labels, 5),
  125. })
  126. # Print the summaries to screen.
  127. for name, value in names_to_values.iteritems():
  128. summary_name = 'eval/%s' % name
  129. op = tf.summary.scalar(summary_name, value, collections=[])
  130. op = tf.Print(op, [value], summary_name)
  131. tf.add_to_collection(tf.GraphKeys.SUMMARIES, op)
  132. # TODO(sguada) use num_epochs=1
  133. if FLAGS.max_num_batches:
  134. num_batches = FLAGS.max_num_batches
  135. else:
  136. # This ensures that we make a single pass over all of the data.
  137. num_batches = math.ceil(dataset.num_samples / float(FLAGS.batch_size))
  138. if tf.gfile.IsDirectory(FLAGS.checkpoint_path):
  139. checkpoint_path = tf.train.latest_checkpoint(FLAGS.checkpoint_path)
  140. else:
  141. checkpoint_path = FLAGS.checkpoint_path
  142. tf.logging.info('Evaluating %s' % checkpoint_path)
  143. slim.evaluation.evaluate_once(
  144. master=FLAGS.master,
  145. checkpoint_path=checkpoint_path,
  146. logdir=FLAGS.eval_dir,
  147. num_evals=num_batches,
  148. eval_op=list(names_to_updates.values()),
  149. variables_to_restore=variables_to_restore)
  150. if __name__ == '__main__':
  151. tf.app.run()