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

Karmel Allison's avatar
Karmel Allison committed
26
import resnet
27
28
import vgg_preprocessing

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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
def _parse_example_proto(example_serialized):
  """Parses an Example proto containing a training example of an image.

  The dataset contains serialized Example protocol buffers.
  The Example proto is expected to contain features named
  image/encoded (a JPEG-encoded string) and image/class/label (int)

  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.
    label: Tensor tf.int64 containing the label.
  """
  # 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,
                                              default_value=-1)
78
79
  }

80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
  features = tf.parse_single_example(example_serialized, feature_map)

  return features['image/encoded'], features['image/class/label']


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.
95

96
97
98
99
  Returns:
    Tuple with processed image tensor and one-hot-encoded label tensor.
"""
  image, label = _parse_example_proto(raw_record)
100

101
102
103
104
  # Decode the string as an RGB JPEG.
  # Note that the resulting image contains an unknown height and width
  # that is set dynamically by decode_jpeg. In other words, the height
  # and width of image is unknown at compile-time.
Karmel Allison's avatar
Karmel Allison committed
105
106
  # Results in a 3-D int8 Tensor. This will be converted to a float later,
  # during resizing.
107
  image = tf.image.decode_jpeg(image, channels=_NUM_CHANNELS)
108

109
  image = vgg_preprocessing.preprocess_image(
110
      image=image,
111
112
      output_height=_DEFAULT_IMAGE_SIZE,
      output_width=_DEFAULT_IMAGE_SIZE,
113
114
      is_training=is_training)

115
116
  label = tf.cast(tf.reshape(label, shape=[]), dtype=tf.int32)
  label = tf.one_hot(label, _NUM_CLASSES)
117

118
  return image, label
119
120


121
def input_fn(is_training, data_dir, batch_size, num_epochs=1,
Karmel Allison's avatar
Karmel Allison committed
122
             num_parallel_calls=1, multi_gpu=False):
123
124
125
126
127
128
129
130
131
  """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
132
133
134
    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.
135
136
137
138
139
140

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

142
  if is_training:
143
144
    # Shuffle the input files
    dataset = dataset.shuffle(buffer_size=_NUM_TRAIN_FILES)
145

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

148
  # Convert to individual records
149
  dataset = dataset.flat_map(tf.data.TFRecordDataset)
150

151
  return resnet.process_record_dataset(dataset, is_training, batch_size,
Karmel Allison's avatar
Karmel Allison committed
152
153
      _SHUFFLE_BUFFER, parse_record, num_epochs, num_parallel_calls,
      examples_per_epoch=num_images, multi_gpu=multi_gpu)
154
155


156
157
158
###############################################################################
# Running the model
###############################################################################
Karmel Allison's avatar
Karmel Allison committed
159
class ImagenetModel(resnet.Model):
160
161

  def __init__(self, resnet_size, data_format=None, num_classes=_NUM_CLASSES):
Neal Wu's avatar
Neal Wu committed
162
163
164
165
166
167
168
    """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
169
        enables users to extend the same model to their own datasets.
Neal Wu's avatar
Neal Wu committed
170
    """
171
172
173

    # For bigger models, we want to use "bottleneck" layers
    if resnet_size < 50:
Karmel Allison's avatar
Karmel Allison committed
174
      block_fn = resnet.building_block
175
176
      final_size = 512
    else:
Karmel Allison's avatar
Karmel Allison committed
177
      block_fn = resnet.bottleneck_block
178
179
180
181
      final_size = 2048

    super(ImagenetModel, self).__init__(
        resnet_size=resnet_size,
182
        num_classes=num_classes,
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
        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_fn=block_fn,
        block_sizes=_get_block_sizes(resnet_size),
        block_strides=[1, 2, 2, 2],
        final_size=final_size,
        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]
209
210
  }

211
212
213
214
215
216
217
  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)
218
219


220
221
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
222
  learning_rate_fn = resnet.learning_rate_with_decay(
223
224
225
      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])
226

Karmel Allison's avatar
Karmel Allison committed
227
228
229
230
231
232
  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'],
Karmel Allison's avatar
Karmel Allison committed
233
234
                                loss_filter_fn=None,
                                multi_gpu=params['multi_gpu'])
235
236
237


def main(unused_argv):
Karmel Allison's avatar
Karmel Allison committed
238
  resnet.resnet_main(FLAGS, imagenet_model_fn, input_fn)
239
240
241
242


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

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