imagenet_main.py 10.4 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

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

import os
22
import sys
23
24
25

import tensorflow as tf

26
from official.resnet import resnet
27
from official.resnet import imagenet_preprocessing
28

29
_DEFAULT_IMAGE_SIZE = 224
30
_NUM_CHANNELS = 3
31
_NUM_CLASSES = 1001
32

33
34
35
36
_NUM_IMAGES = {
    'train': 1281167,
    'validation': 50000,
}
37

38
_NUM_TRAIN_FILES = 1024
39
_SHUFFLE_BUFFER = 1500
40

41

42
43
44
###############################################################################
# Data processing
###############################################################################
45
def get_filenames(is_training, data_dir):
46
47
48
  """Return filenames for dataset."""
  if is_training:
    return [
49
        os.path.join(data_dir, 'train-%05d-of-01024' % i)
50
        for i in range(_NUM_TRAIN_FILES)]
51
52
  else:
    return [
53
        os.path.join(data_dir, 'validation-%05d-of-00128' % i)
Neal Wu's avatar
Neal Wu committed
54
        for i in range(128)]
55
56


57
58
59
def _parse_example_proto(example_serialized):
  """Parses an Example proto containing a training example of an image.

60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
  The output of the build_image_data.py image preprocessing script is a dataset
  containing serialized Example protocol buffers. Each Example proto contains
  the following fields (values are included as examples):

    image/height: 462
    image/width: 581
    image/colorspace: 'RGB'
    image/channels: 3
    image/class/label: 615
    image/class/synset: 'n03623198'
    image/class/text: 'knee pad'
    image/object/bbox/xmin: 0.1
    image/object/bbox/xmax: 0.9
    image/object/bbox/ymin: 0.2
    image/object/bbox/ymax: 0.6
    image/object/bbox/label: 615
    image/format: 'JPEG'
    image/filename: 'ILSVRC2012_val_00041207.JPEG'
    image/encoded: <JPEG encoded string>
79
80
81
82
83
84
85

  Args:
    example_serialized: scalar Tensor tf.string containing a serialized
      Example protocol buffer.

  Returns:
    image_buffer: Tensor tf.string containing the contents of a JPEG file.
86
87
88
89
    label: Tensor tf.int32 containing the label.
    bbox: 3-D float Tensor of bounding boxes arranged [1, num_boxes, coords]
      where each coordinate is [0, 1) and the coordinates are arranged as
      [ymin, xmin, ymax, xmax].
90
91
92
93
94
95
  """
  # Dense features in Example proto.
  feature_map = {
      'image/encoded': tf.FixedLenFeature([], dtype=tf.string,
                                          default_value=''),
      'image/class/label': tf.FixedLenFeature([1], dtype=tf.int64,
96
97
98
                                              default_value=-1),
      'image/class/text': tf.FixedLenFeature([], dtype=tf.string,
                                             default_value=''),
99
  }
100
101
102
103
104
105
106
  sparse_float32 = tf.VarLenFeature(dtype=tf.float32)
  # Sparse features in Example proto.
  feature_map.update(
      {k: sparse_float32 for k in ['image/object/bbox/xmin',
                                   'image/object/bbox/ymin',
                                   'image/object/bbox/xmax',
                                   'image/object/bbox/ymax']})
107

108
  features = tf.parse_single_example(example_serialized, feature_map)
109
  label = tf.cast(features['image/class/label'], dtype=tf.int32)
110

111
112
113
114
115
116
117
118
119
120
121
122
123
124
  xmin = tf.expand_dims(features['image/object/bbox/xmin'].values, 0)
  ymin = tf.expand_dims(features['image/object/bbox/ymin'].values, 0)
  xmax = tf.expand_dims(features['image/object/bbox/xmax'].values, 0)
  ymax = tf.expand_dims(features['image/object/bbox/ymax'].values, 0)

  # Note that we impose an ordering of (y, x) just to make life difficult.
  bbox = tf.concat([ymin, xmin, ymax, xmax], 0)

  # Force the variable number of bounding boxes into the shape
  # [1, num_boxes, coords].
  bbox = tf.expand_dims(bbox, 0)
  bbox = tf.transpose(bbox, [0, 2, 1])

  return features['image/encoded'], label, bbox
125
126
127
128
129
130
131
132
133
134
135
136


def parse_record(raw_record, is_training):
  """Parses a record containing a training example of an image.

  The input record is parsed into a label and image, and the image is passed
  through preprocessing steps (cropping, flipping, and so on).

  Args:
    raw_record: scalar Tensor tf.string containing a serialized
      Example protocol buffer.
    is_training: A boolean denoting whether the input is for training.
137

138
139
  Returns:
    Tuple with processed image tensor and one-hot-encoded label tensor.
140
141
142
143
144
145
  """
  image_buffer, label, bbox = _parse_example_proto(raw_record)

  image = imagenet_preprocessing.preprocess_image(
      image_buffer=image_buffer,
      bbox=bbox,
146
147
      output_height=_DEFAULT_IMAGE_SIZE,
      output_width=_DEFAULT_IMAGE_SIZE,
148
      num_channels=_NUM_CHANNELS,
149
150
      is_training=is_training)

151
  label = tf.one_hot(tf.reshape(label, shape=[]), _NUM_CLASSES)
152

153
  return image, label
154
155


156
def input_fn(is_training, data_dir, batch_size, num_epochs=1,
Karmel Allison's avatar
Karmel Allison committed
157
             num_parallel_calls=1, multi_gpu=False):
158
159
160
161
162
163
164
165
166
  """Input function which provides batches for train or eval.
  Args:
    is_training: A boolean denoting whether the input is for training.
    data_dir: The directory containing the input data.
    batch_size: The number of samples per batch.
    num_epochs: The number of epochs to repeat the dataset.
    num_parallel_calls: The number of records that are processed in parallel.
      This can be optimized per data set but for generally homogeneous data
      sets, should be approximately the number of available CPU cores.
Karmel Allison's avatar
Karmel Allison committed
167
168
169
    multi_gpu: Whether this is run multi-GPU. Note that this is only required
      currently to handle the batch leftovers, and can be removed
      when that is handled directly by Estimator.
170
171
172
173
174
175

  Returns:
    A dataset that can be used for iteration.
  """
  filenames = get_filenames(is_training, data_dir)
  dataset = tf.data.Dataset.from_tensor_slices(filenames)
176

177
  if is_training:
178
179
    # Shuffle the input files
    dataset = dataset.shuffle(buffer_size=_NUM_TRAIN_FILES)
180

Karmel Allison's avatar
Karmel Allison committed
181
182
  num_images = is_training and _NUM_IMAGES['train'] or _NUM_IMAGES['validation']

183
  # Convert to individual records
184
  dataset = dataset.flat_map(tf.data.TFRecordDataset)
185

186
187
188
189
190
191
192
193
194
  return resnet.process_record_dataset(
      dataset, is_training, batch_size, _SHUFFLE_BUFFER, parse_record,
      num_epochs, num_parallel_calls, examples_per_epoch=num_images,
      multi_gpu=multi_gpu)


def get_synth_input_fn():
  return resnet.get_synth_input_fn(
        _DEFAULT_IMAGE_SIZE, _DEFAULT_IMAGE_SIZE, _NUM_CHANNELS, _NUM_CLASSES)
195
196


197
198
199
###############################################################################
# Running the model
###############################################################################
Karmel Allison's avatar
Karmel Allison committed
200
class ImagenetModel(resnet.Model):
201

202
203
  def __init__(self, resnet_size, data_format=None, num_classes=_NUM_CLASSES,
    version=resnet.DEFAULT_VERSION):
Neal Wu's avatar
Neal Wu committed
204
205
206
207
208
209
210
    """These are the parameters that work for Imagenet data.

    Args:
      resnet_size: The number of convolutional layers needed in the model.
      data_format: Either 'channels_first' or 'channels_last', specifying which
        data format to use when setting up the model.
      num_classes: The number of output classes needed from the model. This
211
        enables users to extend the same model to their own datasets.
212
213
      version: Integer representing which version of the ResNet network to use.
        See README for details. Valid values: [1, 2]
Neal Wu's avatar
Neal Wu committed
214
    """
215
216
217

    # For bigger models, we want to use "bottleneck" layers
    if resnet_size < 50:
218
      bottleneck = False
219
220
      final_size = 512
    else:
221
      bottleneck = True
222
223
224
225
      final_size = 2048

    super(ImagenetModel, self).__init__(
        resnet_size=resnet_size,
226
        bottleneck=bottleneck,
227
        num_classes=num_classes,
228
229
230
231
232
233
234
235
236
237
        num_filters=64,
        kernel_size=7,
        conv_stride=2,
        first_pool_size=3,
        first_pool_stride=2,
        second_pool_size=7,
        second_pool_stride=1,
        block_sizes=_get_block_sizes(resnet_size),
        block_strides=[1, 2, 2, 2],
        final_size=final_size,
238
        version=version,
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
        data_format=data_format)


def _get_block_sizes(resnet_size):
  """The number of block layers used for the Resnet model varies according
  to the size of the model. This helper grabs the layer set we want, throwing
  an error if a non-standard size has been selected.
  """
  choices = {
      18: [2, 2, 2, 2],
      34: [3, 4, 6, 3],
      50: [3, 4, 6, 3],
      101: [3, 4, 23, 3],
      152: [3, 8, 36, 3],
      200: [3, 24, 36, 3]
254
255
  }

256
257
258
259
260
261
262
  try:
    return choices[resnet_size]
  except KeyError:
    err = ('Could not find layers for selected Resnet size.\n'
           'Size received: {}; sizes allowed: {}.'.format(
               resnet_size, choices.keys()))
    raise ValueError(err)
263
264


265
266
def imagenet_model_fn(features, labels, mode, params):
  """Our model_fn for ResNet to be used with our Estimator."""
Karmel Allison's avatar
Karmel Allison committed
267
  learning_rate_fn = resnet.learning_rate_with_decay(
268
269
270
      batch_size=params['batch_size'], batch_denom=256,
      num_images=_NUM_IMAGES['train'], boundary_epochs=[30, 60, 80, 90],
      decay_rates=[1, 0.1, 0.01, 0.001, 1e-4])
271

Karmel Allison's avatar
Karmel Allison committed
272
273
274
275
276
277
  return resnet.resnet_model_fn(features, labels, mode, ImagenetModel,
                                resnet_size=params['resnet_size'],
                                weight_decay=1e-4,
                                learning_rate_fn=learning_rate_fn,
                                momentum=0.9,
                                data_format=params['data_format'],
278
                                version=params['version'],
Karmel Allison's avatar
Karmel Allison committed
279
280
                                loss_filter_fn=None,
                                multi_gpu=params['multi_gpu'])
281
282
283


def main(unused_argv):
284
285
  input_function = FLAGS.use_synthetic_data and get_synth_input_fn() or input_fn
  resnet.resnet_main(FLAGS, imagenet_model_fn, input_function)
286
287
288
289


if __name__ == '__main__':
  tf.logging.set_verbosity(tf.logging.INFO)
290

Karmel Allison's avatar
Karmel Allison committed
291
  parser = resnet.ResnetArgParser(
292
      resnet_size_choices=[18, 34, 50, 101, 152, 200])
293
294
  FLAGS, unparsed = parser.parse_known_args()
  tf.app.run(argv=[sys.argv[0]] + unparsed)