train.py 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  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. """Train the model."""
  16. from __future__ import absolute_import
  17. from __future__ import division
  18. from __future__ import print_function
  19. import tensorflow as tf
  20. from im2txt import configuration
  21. from im2txt import show_and_tell_model
  22. FLAGS = tf.app.flags.FLAGS
  23. tf.flags.DEFINE_string("input_file_pattern", "",
  24. "File pattern of sharded TFRecord input files.")
  25. tf.flags.DEFINE_string("inception_checkpoint_file", "",
  26. "Path to a pretrained inception_v3 model.")
  27. tf.flags.DEFINE_string("train_dir", "",
  28. "Directory for saving and loading model checkpoints.")
  29. tf.flags.DEFINE_boolean("train_inception", False,
  30. "Whether to train inception submodel variables.")
  31. tf.flags.DEFINE_integer("number_of_steps", 1000000, "Number of training steps.")
  32. tf.flags.DEFINE_integer("log_every_n_steps", 1,
  33. "Frequency at which loss and global step are logged.")
  34. tf.logging.set_verbosity(tf.logging.INFO)
  35. def main(unused_argv):
  36. assert FLAGS.input_file_pattern, "--input_file_pattern is required"
  37. assert FLAGS.train_dir, "--train_dir is required"
  38. model_config = configuration.ModelConfig()
  39. model_config.input_file_pattern = FLAGS.input_file_pattern
  40. model_config.inception_checkpoint_file = FLAGS.inception_checkpoint_file
  41. training_config = configuration.TrainingConfig()
  42. # Create training directory.
  43. train_dir = FLAGS.train_dir
  44. if not tf.gfile.IsDirectory(train_dir):
  45. tf.logging.info("Creating training directory: %s", train_dir)
  46. tf.gfile.MakeDirs(train_dir)
  47. # Build the TensorFlow graph.
  48. g = tf.Graph()
  49. with g.as_default():
  50. # Build the model.
  51. model = show_and_tell_model.ShowAndTellModel(
  52. model_config, mode="train", train_inception=FLAGS.train_inception)
  53. model.build()
  54. # Set up the learning rate.
  55. learning_rate_decay_fn = None
  56. if FLAGS.train_inception:
  57. learning_rate = tf.constant(training_config.train_inception_learning_rate)
  58. else:
  59. learning_rate = tf.constant(training_config.initial_learning_rate)
  60. if training_config.learning_rate_decay_factor > 0:
  61. num_batches_per_epoch = (training_config.num_examples_per_epoch /
  62. model_config.batch_size)
  63. decay_steps = int(num_batches_per_epoch *
  64. training_config.num_epochs_per_decay)
  65. def _learning_rate_decay_fn(learning_rate, global_step):
  66. return tf.train.exponential_decay(
  67. learning_rate,
  68. global_step,
  69. decay_steps=decay_steps,
  70. decay_rate=training_config.learning_rate_decay_factor,
  71. staircase=True)
  72. learning_rate_decay_fn = _learning_rate_decay_fn
  73. # Set up the training ops.
  74. train_op = tf.contrib.layers.optimize_loss(
  75. loss=model.total_loss,
  76. global_step=model.global_step,
  77. learning_rate=learning_rate,
  78. optimizer=training_config.optimizer,
  79. clip_gradients=training_config.clip_gradients,
  80. learning_rate_decay_fn=learning_rate_decay_fn)
  81. # Run training.
  82. tf.contrib.slim.learning.train(
  83. train_op,
  84. train_dir,
  85. log_every_n_steps=FLAGS.log_every_n_steps,
  86. graph=g,
  87. global_step=model.global_step,
  88. number_of_steps=FLAGS.number_of_steps,
  89. init_fn=model.init_fn,
  90. saver=model.saver)
  91. if __name__ == "__main__":
  92. tf.app.run()