imagenet_main.py 9.26 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
# Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
15
"""Runs a ResNet model on the ImageNet dataset."""
16
17
18
19
20
21
22

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import argparse
import os
23
import sys
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44

import tensorflow as tf

import resnet_model
import vgg_preprocessing

parser = argparse.ArgumentParser()

parser.add_argument(
    '--data_dir', type=str, default='',
    help='The directory where the ImageNet input data is stored.')

parser.add_argument(
    '--model_dir', type=str, default='/tmp/resnet_model',
    help='The directory where the model will be stored.')

parser.add_argument(
    '--resnet_size', type=int, default=50, choices=[18, 34, 50, 101, 152, 200],
    help='The size of the ResNet model to use.')

parser.add_argument(
45
46
    '--train_epochs', type=int, default=100,
    help='The number of epochs to use for training.')
47
48

parser.add_argument(
49
50
    '--epochs_per_eval', type=int, default=1,
    help='The number of training epochs to run between evaluations.')
51
52

parser.add_argument(
53
54
    '--batch_size', type=int, default=32,
    help='Batch size for training and evaluation.')
55

56
57
58
59
60
61
62
63
parser.add_argument(
    '--data_format', type=str, default=None,
    choices=['channels_first', 'channels_last'],
    help='A flag to override the data format used in the model. channels_first '
         'provides a performance boost on GPU but is not always compatible '
         'with CPU. If left unspecified, the data format will be chosen '
         'automatically based on whether TensorFlow was built for CPU or GPU.')

64
_DEFAULT_IMAGE_SIZE = 224
65
66
_NUM_CHANNELS = 3
_LABEL_CLASSES = 1001
67
68
69
70

_MOMENTUM = 0.9
_WEIGHT_DECAY = 1e-4

71
72
73
74
_NUM_IMAGES = {
    'train': 1281167,
    'validation': 50000,
}
75

76
_SHUFFLE_BUFFER = 1500
77

78
79

def filenames(is_training, data_dir):
80
81
82
  """Return filenames for dataset."""
  if is_training:
    return [
83
        os.path.join(data_dir, 'train-%05d-of-01024' % i)
Amit Patankar's avatar
Amit Patankar committed
84
        for i in range(0, 1024)]
85
86
  else:
    return [
87
        os.path.join(data_dir, 'validation-%05d-of-00128' % i)
Amit Patankar's avatar
Amit Patankar committed
88
        for i in range(0, 128)]
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114


def dataset_parser(value, is_training):
  """Parse an Imagenet record from value."""
  keys_to_features = {
      'image/encoded':
          tf.FixedLenFeature((), tf.string, default_value=''),
      'image/format':
          tf.FixedLenFeature((), tf.string, default_value='jpeg'),
      'image/class/label':
          tf.FixedLenFeature([], dtype=tf.int64, default_value=-1),
      'image/class/text':
          tf.FixedLenFeature([], dtype=tf.string, default_value=''),
      'image/object/bbox/xmin':
          tf.VarLenFeature(dtype=tf.float32),
      'image/object/bbox/ymin':
          tf.VarLenFeature(dtype=tf.float32),
      'image/object/bbox/xmax':
          tf.VarLenFeature(dtype=tf.float32),
      'image/object/bbox/ymax':
          tf.VarLenFeature(dtype=tf.float32),
      'image/object/class/label':
          tf.VarLenFeature(dtype=tf.int64),
  }

  parsed = tf.parse_single_example(value, keys_to_features)
115

116
117
118
119
120
  image = tf.image.decode_image(
      tf.reshape(parsed['image/encoded'], shape=[]),
      _NUM_CHANNELS)
  image = tf.image.convert_image_dtype(image, dtype=tf.float32)

121
  image = vgg_preprocessing.preprocess_image(
122
      image=image,
123
124
      output_height=_DEFAULT_IMAGE_SIZE,
      output_width=_DEFAULT_IMAGE_SIZE,
125
126
127
128
129
130
131
      is_training=is_training)

  label = tf.cast(
      tf.reshape(parsed['image/class/label'], shape=[]),
      dtype=tf.int32)

  return image, tf.one_hot(label, _LABEL_CLASSES)
132
133


134
def input_fn(is_training, data_dir, batch_size, num_epochs=1):
135
  """Input function which provides batches for train or eval."""
136
137
138
  dataset = tf.contrib.data.Dataset.from_tensor_slices(
      filenames(is_training, data_dir))

139
140
141
142
143
  if is_training:
    dataset = dataset.shuffle(buffer_size=1024)
  dataset = dataset.flat_map(tf.contrib.data.TFRecordDataset)

  if is_training:
144
    dataset = dataset.repeat(num_epochs)
145
146

  dataset = dataset.map(lambda value: dataset_parser(value, is_training),
147
                        num_threads=5,
148
                        output_buffer_size=batch_size)
149
150

  if is_training:
151
152
153
    # When choosing shuffle buffer sizes, larger sizes result in better
    # randomness, while smaller sizes have better performance.
    dataset = dataset.shuffle(buffer_size=_SHUFFLE_BUFFER)
154

155
  iterator = dataset.batch(batch_size).make_one_shot_iterator()
156
  images, labels = iterator.get_next()
157
158
159
  return images, labels


160
def resnet_model_fn(features, labels, mode, params):
161
  """Our model_fn for ResNet to be used with our Estimator."""
162
163
  tf.summary.image('images', features, max_outputs=6)

164
  network = resnet_model.imagenet_resnet_v2(
165
      params['resnet_size'], _LABEL_CLASSES, params['data_format'])
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
  logits = network(
      inputs=features, is_training=(mode == tf.estimator.ModeKeys.TRAIN))

  predictions = {
      'classes': tf.argmax(logits, axis=1),
      'probabilities': tf.nn.softmax(logits, name='softmax_tensor')
  }

  if mode == tf.estimator.ModeKeys.PREDICT:
    return tf.estimator.EstimatorSpec(mode=mode, predictions=predictions)

  # Calculate loss, which includes softmax cross entropy and L2 regularization.
  cross_entropy = tf.losses.softmax_cross_entropy(
      logits=logits, onehot_labels=labels)

  # Create a tensor named cross_entropy for logging purposes.
  tf.identity(cross_entropy, name='cross_entropy')
  tf.summary.scalar('cross_entropy', cross_entropy)

  # Add weight decay to the loss. We perform weight decay on all trainable
  # variables, which includes batch norm beta and gamma variables.
  loss = cross_entropy + _WEIGHT_DECAY * tf.add_n(
      [tf.nn.l2_loss(v) for v in tf.trainable_variables()])

  if mode == tf.estimator.ModeKeys.TRAIN:
191
192
    # Scale the learning rate linearly with the batch size. When the batch size is
    # 256, the learning rate should be 0.1.
193
194
    initial_learning_rate = 0.1 * params['batch_size'] / 256
    batches_per_epoch = _NUM_IMAGES['train'] / params['batch_size']
195
196
    global_step = tf.train.get_or_create_global_step()

197
    # Multiply the learning rate by 0.1 at 30, 60, 80, and 90 epochs.
198
    boundaries = [
199
        int(batches_per_epoch * epoch) for epoch in [30, 60, 80, 90]]
200
    values = [
201
        initial_learning_rate * decay for decay in [1, 0.1, 0.01, 1e-3, 1e-4]]
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
    learning_rate = tf.train.piecewise_constant(
        tf.cast(global_step, tf.int32), boundaries, values)

    # Create a tensor named learning_rate for logging purposes.
    tf.identity(learning_rate, name='learning_rate')
    tf.summary.scalar('learning_rate', learning_rate)

    optimizer = tf.train.MomentumOptimizer(
        learning_rate=learning_rate,
        momentum=_MOMENTUM)

    # Batch norm requires update_ops to be added as a train_op dependency.
    update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)
    with tf.control_dependencies(update_ops):
      train_op = optimizer.minimize(loss, global_step)
  else:
    train_op = None

  accuracy = tf.metrics.accuracy(
      tf.argmax(labels, axis=1), predictions['classes'])
  metrics = {'accuracy': accuracy}

  # Create a tensor named train_accuracy for logging purposes.
  tf.identity(accuracy[1], name='train_accuracy')
  tf.summary.scalar('train_accuracy', accuracy[1])

  return tf.estimator.EstimatorSpec(
      mode=mode,
      predictions=predictions,
      loss=loss,
      train_op=train_op,
      eval_metric_ops=metrics)


def main(unused_argv):
  # Using the Winograd non-fused algorithms provides a small performance boost.
  os.environ['TF_ENABLE_WINOGRAD_NONFUSED'] = '1'

240
241
  # Set up a RunConfig to only save checkpoints once per training cycle.
  run_config = tf.estimator.RunConfig().replace(save_checkpoints_secs=1e9)
242
  resnet_classifier = tf.estimator.Estimator(
243
244
245
246
247
248
      model_fn=resnet_model_fn, model_dir=FLAGS.model_dir, config=run_config,
      params={
          'resnet_size': FLAGS.resnet_size,
          'data_format': FLAGS.data_format,
          'batch_size': FLAGS.batch_size,
      })
249

250
  for _ in range(FLAGS.train_epochs // FLAGS.epochs_per_eval):
251
252
253
254
255
256
257
258
259
260
261
    tensors_to_log = {
        'learning_rate': 'learning_rate',
        'cross_entropy': 'cross_entropy',
        'train_accuracy': 'train_accuracy'
    }

    logging_hook = tf.train.LoggingTensorHook(
        tensors=tensors_to_log, every_n_iter=100)

    print('Starting a training cycle.')
    resnet_classifier.train(
262
        input_fn=lambda: input_fn(
263
            True, FLAGS.data_dir, FLAGS.batch_size, FLAGS.epochs_per_eval),
264
265
266
        hooks=[logging_hook])

    print('Starting to evaluate.')
267
    eval_results = resnet_classifier.evaluate(
268
        input_fn=lambda: input_fn(False, FLAGS.data_dir, FLAGS.batch_size))
269
270
271
272
273
    print(eval_results)


if __name__ == '__main__':
  tf.logging.set_verbosity(tf.logging.INFO)
274
275
  FLAGS, unparsed = parser.parse_known_args()
  tf.app.run(argv=[sys.argv[0]] + unparsed)