.pipertmp-WMYPqp-dsn_eval.py 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153
  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 google3
  32. import numpy as np
  33. import tensorflow as tf
  34. from google3.robotics.cad_learning.domain_adaptation.fnist import data_provider
  35. from google3.third_party.tensorflow_models.domain_adaptation.domain_separation import losses
  36. from google3.third_party.tensorflow_models.domain_adaptation.domain_separation import models
  37. slim = tf.contrib.slim
  38. FLAGS = tf.app.flags.FLAGS
  39. tf.app.flags.DEFINE_integer('batch_size', 32,
  40. 'The number of images in each batch.')
  41. tf.app.flags.DEFINE_string('master', 'local',
  42. 'BNS name of the TensorFlow master to use.')
  43. tf.app.flags.DEFINE_string('checkpoint_dir', '/tmp/da/',
  44. 'Directory where the model was written to.')
  45. tf.app.flags.DEFINE_string(
  46. 'eval_dir', '/tmp/da/',
  47. 'Directory where we should write the tf summaries to.')
  48. tf.app.flags.DEFINE_string(
  49. 'dataset', 'pose_real',
  50. 'Which dataset to test on: "pose_real", "pose_synthetic".')
  51. tf.app.flags.DEFINE_string('portion', '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', 'dsn_cropped_linemod',
  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 main(_):
  70. g = tf.Graph()
  71. with g.as_default():
  72. images, labels = data_provider.provide(FLAGS.dataset, FLAGS.portion,
  73. FLAGS.batch_size)
  74. num_classes = labels['classes'].get_shape().as_list()[1]
  75. # Define the model:
  76. with tf.variable_scope('towers'):
  77. basic_tower = getattr(models, FLAGS.basic_tower)
  78. predictions, endpoints = basic_tower(
  79. images,
  80. num_classes=num_classes,
  81. is_training=False,
  82. batch_norm_params=None)
  83. metric_names_to_values = {}
  84. # Define the metrics:
  85. if 'quaternions' in labels: # Also have to evaluate pose estimation!
  86. quaternion_loss = quaternion_metric(labels['quaternions'],
  87. endpoints['quaternion_pred'])
  88. angle_errors, = tf.py_func(
  89. angle_diff, [labels['quaternions'], endpoints['quaternion_pred']],
  90. [tf.float32])
  91. metric_names_to_values[
  92. 'Angular mean error'] = slim.metrics.streaming_mean(angle_errors)
  93. metric_names_to_values['Quaternion Loss'] = quaternion_loss
  94. accuracy = tf.contrib.metrics.streaming_accuracy(
  95. tf.argmax(predictions, 1), tf.argmax(labels['classes'], 1))
  96. predictions = tf.argmax(predictions, 1)
  97. labels = tf.argmax(labels['classes'], 1)
  98. metric_names_to_values['Accuracy'] = accuracy
  99. names_to_values, names_to_updates = slim.metrics.aggregate_metric_map(
  100. metric_names_to_values)
  101. # Create the summary ops such that they also print out to std output:
  102. summary_ops = []
  103. for metric_name, metric_value in names_to_values.iteritems():
  104. op = tf.summary.scalar(metric_name, metric_value)
  105. op = tf.Print(op, [metric_value], metric_name)
  106. summary_ops.append(op)
  107. # This ensures that we make a single pass over all of the data.
  108. num_batches = math.ceil(FLAGS.num_examples / float(FLAGS.batch_size))
  109. # Setup the global step.
  110. slim.get_or_create_global_step()
  111. slim.evaluation.evaluation_loop(
  112. FLAGS.master,
  113. checkpoint_dir=FLAGS.checkpoint_dir,
  114. logdir=FLAGS.eval_dir,
  115. num_evals=num_batches,
  116. eval_op=names_to_updates.values(),
  117. summary_op=tf.summary.merge(summary_ops))
  118. if __name__ == '__main__':
  119. tf.app.run()