dsn_eval.py 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176
  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. # pylint: disable=line-too-long
  16. r"""Evaluation for Domain Separation Networks (DSNs).
  17. To build locally for CPU:
  18. blaze build -c opt --copt=-mavx \
  19. third_party/tensorflow_models/domain_adaptation/domain_separation:dsn_eval
  20. To build locally for GPU:
  21. blaze build -c opt --copt=-mavx --config=cuda_clang \
  22. third_party/tensorflow_models/domain_adaptation/domain_separation:dsn_eval
  23. To run locally:
  24. $
  25. ./blaze-bin/third_party/tensorflow_models/domain_adaptation/domain_separation/dsn_eval
  26. \
  27. --alsologtostderr
  28. """
  29. # pylint: enable=line-too-long
  30. import math
  31. import numpy as np
  32. import tensorflow as tf
  33. from domain_adaptation.datasets import dataset_factory
  34. from domain_adaptation.domain_separation import losses
  35. from domain_adaptation.domain_separation import models
  36. slim = tf.contrib.slim
  37. FLAGS = tf.app.flags.FLAGS
  38. tf.app.flags.DEFINE_integer('batch_size', 32,
  39. 'The number of images in each batch.')
  40. tf.app.flags.DEFINE_string('master', '',
  41. 'BNS name of the TensorFlow master to use.')
  42. tf.app.flags.DEFINE_string('checkpoint_dir', '/tmp/da/',
  43. 'Directory where the model was written to.')
  44. tf.app.flags.DEFINE_string(
  45. 'eval_dir', '/tmp/da/',
  46. 'Directory where we should write the tf summaries to.')
  47. tf.app.flags.DEFINE_string('dataset_dir', '/cns/ok-d/home/konstantinos/cad_learning/',
  48. 'The directory where the dataset files are stored.')
  49. tf.app.flags.DEFINE_string('dataset', 'mnist_m',
  50. 'Which dataset to test on: "mnist", "mnist_m".')
  51. tf.app.flags.DEFINE_string('split', 'valid',
  52. 'Which portion to test on: "valid", "test".')
  53. tf.app.flags.DEFINE_integer('num_examples', 1000, 'Number of test examples.')
  54. tf.app.flags.DEFINE_string('basic_tower', 'dann_mnist',
  55. 'The basic tower building block.')
  56. tf.app.flags.DEFINE_bool('enable_precision_recall', False,
  57. 'If True, precision and recall for each class will '
  58. 'be added to the metrics.')
  59. tf.app.flags.DEFINE_bool('use_logging', False, 'Debugging messages.')
  60. def quaternion_metric(predictions, labels):
  61. params = {'batch_size': FLAGS.batch_size, 'use_logging': False}
  62. logcost = losses.log_quaternion_loss_batch(predictions, labels, params)
  63. return slim.metrics.streaming_mean(logcost)
  64. def angle_diff(true_q, pred_q):
  65. angles = 2 * (
  66. 180.0 /
  67. np.pi) * np.arccos(np.abs(np.sum(np.multiply(pred_q, true_q), axis=1)))
  68. return angles
  69. def provide_batch_fn():
  70. """ The provide_batch function to use. """
  71. return dataset_factory.provide_batch
  72. def main(_):
  73. g = tf.Graph()
  74. with g.as_default():
  75. # Load the data.
  76. images, labels = provide_batch_fn()(
  77. FLAGS.dataset, FLAGS.split, FLAGS.dataset_dir, 4, FLAGS.batch_size, 4)
  78. num_classes = labels['classes'].get_shape().as_list()[1]
  79. tf.summary.image('eval_images', images, max_outputs=3)
  80. # Define the model:
  81. with tf.variable_scope('towers'):
  82. basic_tower = getattr(models, FLAGS.basic_tower)
  83. predictions, endpoints = basic_tower(
  84. images,
  85. num_classes=num_classes,
  86. is_training=False,
  87. batch_norm_params=None)
  88. metric_names_to_values = {}
  89. # Define the metrics:
  90. if 'quaternions' in labels: # Also have to evaluate pose estimation!
  91. quaternion_loss = quaternion_metric(labels['quaternions'],
  92. endpoints['quaternion_pred'])
  93. angle_errors, = tf.py_func(
  94. angle_diff, [labels['quaternions'], endpoints['quaternion_pred']],
  95. [tf.float32])
  96. metric_names_to_values[
  97. 'Angular mean error'] = slim.metrics.streaming_mean(angle_errors)
  98. metric_names_to_values['Quaternion Loss'] = quaternion_loss
  99. accuracy = tf.contrib.metrics.streaming_accuracy(
  100. tf.argmax(predictions, 1), tf.argmax(labels['classes'], 1))
  101. predictions = tf.argmax(predictions, 1)
  102. labels = tf.argmax(labels['classes'], 1)
  103. metric_names_to_values['Accuracy'] = accuracy
  104. if FLAGS.enable_precision_recall:
  105. for i in xrange(num_classes):
  106. index_map = tf.one_hot(i, depth=num_classes)
  107. name = 'PR/Precision_{}'.format(i)
  108. metric_names_to_values[name] = slim.metrics.streaming_precision(
  109. tf.gather(index_map, predictions), tf.gather(index_map, labels))
  110. name = 'PR/Recall_{}'.format(i)
  111. metric_names_to_values[name] = slim.metrics.streaming_recall(
  112. tf.gather(index_map, predictions), tf.gather(index_map, labels))
  113. names_to_values, names_to_updates = slim.metrics.aggregate_metric_map(
  114. metric_names_to_values)
  115. # Create the summary ops such that they also print out to std output:
  116. summary_ops = []
  117. for metric_name, metric_value in names_to_values.iteritems():
  118. op = tf.summary.scalar(metric_name, metric_value)
  119. op = tf.Print(op, [metric_value], metric_name)
  120. summary_ops.append(op)
  121. # This ensures that we make a single pass over all of the data.
  122. num_batches = math.ceil(FLAGS.num_examples / float(FLAGS.batch_size))
  123. # Setup the global step.
  124. slim.get_or_create_global_step()
  125. slim.evaluation.evaluation_loop(
  126. FLAGS.master,
  127. checkpoint_dir=FLAGS.checkpoint_dir,
  128. logdir=FLAGS.eval_dir,
  129. num_evals=num_batches,
  130. eval_op=names_to_updates.values(),
  131. summary_op=tf.summary.merge(summary_ops))
  132. if __name__ == '__main__':
  133. tf.app.run()