resnet_main.py 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210
  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. """ResNet Train/Eval module.
  16. """
  17. import time
  18. import sys
  19. import cifar_input
  20. import numpy as np
  21. import resnet_model
  22. import tensorflow as tf
  23. FLAGS = tf.app.flags.FLAGS
  24. tf.app.flags.DEFINE_string('dataset', 'cifar10', 'cifar10 or cifar100.')
  25. tf.app.flags.DEFINE_string('mode', 'train', 'train or eval.')
  26. tf.app.flags.DEFINE_string('train_data_path', '',
  27. 'Filepattern for training data.')
  28. tf.app.flags.DEFINE_string('eval_data_path', '',
  29. 'Filepattern for eval data')
  30. tf.app.flags.DEFINE_integer('image_size', 32, 'Image side length.')
  31. tf.app.flags.DEFINE_string('train_dir', '',
  32. 'Directory to keep training outputs.')
  33. tf.app.flags.DEFINE_string('eval_dir', '',
  34. 'Directory to keep eval outputs.')
  35. tf.app.flags.DEFINE_integer('eval_batch_count', 50,
  36. 'Number of batches to eval.')
  37. tf.app.flags.DEFINE_bool('eval_once', False,
  38. 'Whether evaluate the model only once.')
  39. tf.app.flags.DEFINE_string('log_root', '',
  40. 'Directory to keep the checkpoints. Should be a '
  41. 'parent directory of FLAGS.train_dir/eval_dir.')
  42. tf.app.flags.DEFINE_integer('num_gpus', 0,
  43. 'Number of gpus used for training. (0 or 1)')
  44. def train(hps):
  45. """Training loop."""
  46. images, labels = cifar_input.build_input(
  47. FLAGS.dataset, FLAGS.train_data_path, hps.batch_size, FLAGS.mode)
  48. model = resnet_model.ResNet(hps, images, labels, FLAGS.mode)
  49. model.build_graph()
  50. param_stats = tf.contrib.tfprof.model_analyzer.print_model_analysis(
  51. tf.get_default_graph(),
  52. tfprof_options=tf.contrib.tfprof.model_analyzer.
  53. TRAINABLE_VARS_PARAMS_STAT_OPTIONS)
  54. sys.stdout.write('total_params: %d\n' % param_stats.total_parameters)
  55. tf.contrib.tfprof.model_analyzer.print_model_analysis(
  56. tf.get_default_graph(),
  57. tfprof_options=tf.contrib.tfprof.model_analyzer.FLOAT_OPS_OPTIONS)
  58. truth = tf.argmax(model.labels, axis=1)
  59. predictions = tf.argmax(model.predictions, axis=1)
  60. precision = tf.reduce_mean(tf.to_float(tf.equal(predictions, truth)))
  61. summary_hook = tf.train.SummarySaverHook(
  62. save_steps=100,
  63. output_dir=FLAGS.train_dir,
  64. summary_op=[model.summaries,
  65. tf.summary.scalar('Precision', precision)])
  66. logging_hook = tf.train.LoggingTensorHook(
  67. tensors={'step': model.global_step,
  68. 'loss': model.cost,
  69. 'precision': precision},
  70. every_n_iter=100)
  71. class _LearningRateSetterHook(tf.train.SessionRunHook):
  72. """Sets learning_rate based on global step."""
  73. def begin(self):
  74. self._lrn_rate = 0.1
  75. def before_run(self, run_context):
  76. return tf.train.SessionRunArgs(
  77. model.global_step, # Asks for global step value.
  78. feed_dict={model.lrn_rate: self._lrn_rate}) # Sets learning rate
  79. def after_run(self, run_context, run_values):
  80. train_step = run_values.results
  81. if train_step < 40000:
  82. self._lrn_rate = 0.1
  83. elif train_step < 60000:
  84. self._lrn_rate = 0.01
  85. elif train_step < 80000:
  86. self._lrn_rate = 0.001
  87. else:
  88. self._lrn_rate = 0.0001
  89. with tf.train.MonitoredTrainingSession(
  90. checkpoint_dir=FLAGS.log_root,
  91. hooks=[logging_hook, _LearningRateSetterHook()],
  92. chief_only_hooks=[summary_hook],
  93. # Since we provide a SummarySaverHook, we need to disable default
  94. # SummarySaverHook. To do that we set save_summaries_steps to 0.
  95. save_summaries_steps=0,
  96. config=tf.ConfigProto(allow_soft_placement=True)) as mon_sess:
  97. while not mon_sess.should_stop():
  98. mon_sess.run(model.train_op)
  99. def evaluate(hps):
  100. """Eval loop."""
  101. images, labels = cifar_input.build_input(
  102. FLAGS.dataset, FLAGS.eval_data_path, hps.batch_size, FLAGS.mode)
  103. model = resnet_model.ResNet(hps, images, labels, FLAGS.mode)
  104. model.build_graph()
  105. saver = tf.train.Saver()
  106. summary_writer = tf.summary.FileWriter(FLAGS.eval_dir)
  107. sess = tf.Session(config=tf.ConfigProto(allow_soft_placement=True))
  108. tf.train.start_queue_runners(sess)
  109. best_precision = 0.0
  110. while True:
  111. time.sleep(60)
  112. try:
  113. ckpt_state = tf.train.get_checkpoint_state(FLAGS.log_root)
  114. except tf.errors.OutOfRangeError as e:
  115. tf.logging.error('Cannot restore checkpoint: %s', e)
  116. continue
  117. if not (ckpt_state and ckpt_state.model_checkpoint_path):
  118. tf.logging.info('No model to eval yet at %s', FLAGS.log_root)
  119. continue
  120. tf.logging.info('Loading checkpoint %s', ckpt_state.model_checkpoint_path)
  121. saver.restore(sess, ckpt_state.model_checkpoint_path)
  122. total_prediction, correct_prediction = 0, 0
  123. for _ in xrange(FLAGS.eval_batch_count):
  124. (summaries, loss, predictions, truth, train_step) = sess.run(
  125. [model.summaries, model.cost, model.predictions,
  126. model.labels, model.global_step])
  127. truth = np.argmax(truth, axis=1)
  128. predictions = np.argmax(predictions, axis=1)
  129. correct_prediction += np.sum(truth == predictions)
  130. total_prediction += predictions.shape[0]
  131. precision = 1.0 * correct_prediction / total_prediction
  132. best_precision = max(precision, best_precision)
  133. precision_summ = tf.Summary()
  134. precision_summ.value.add(
  135. tag='Precision', simple_value=precision)
  136. summary_writer.add_summary(precision_summ, train_step)
  137. best_precision_summ = tf.Summary()
  138. best_precision_summ.value.add(
  139. tag='Best Precision', simple_value=best_precision)
  140. summary_writer.add_summary(best_precision_summ, train_step)
  141. summary_writer.add_summary(summaries, train_step)
  142. tf.logging.info('loss: %.3f, precision: %.3f, best precision: %.3f\n' %
  143. (loss, precision, best_precision))
  144. summary_writer.flush()
  145. if FLAGS.eval_once:
  146. break
  147. def main(_):
  148. if FLAGS.num_gpus == 0:
  149. dev = '/cpu:0'
  150. elif FLAGS.num_gpus == 1:
  151. dev = '/gpu:0'
  152. else:
  153. raise ValueError('Only support 0 or 1 gpu.')
  154. if FLAGS.mode == 'train':
  155. batch_size = 128
  156. elif FLAGS.mode == 'eval':
  157. batch_size = 100
  158. if FLAGS.dataset == 'cifar10':
  159. num_classes = 10
  160. elif FLAGS.dataset == 'cifar100':
  161. num_classes = 100
  162. hps = resnet_model.HParams(batch_size=batch_size,
  163. num_classes=num_classes,
  164. min_lrn_rate=0.0001,
  165. lrn_rate=0.1,
  166. num_residual_units=5,
  167. use_bottleneck=False,
  168. weight_decay_rate=0.0002,
  169. relu_leakiness=0.1,
  170. optimizer='mom')
  171. with tf.device(dev):
  172. if FLAGS.mode == 'train':
  173. train(hps)
  174. elif FLAGS.mode == 'eval':
  175. evaluate(hps)
  176. if __name__ == '__main__':
  177. tf.app.run()