cifar_input.py 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116
  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. """CIFAR dataset input module.
  16. """
  17. import tensorflow as tf
  18. def build_input(dataset, data_path, batch_size, mode):
  19. """Build CIFAR image and labels.
  20. Args:
  21. dataset: Either 'cifar10' or 'cifar100'.
  22. data_path: Filename for data.
  23. batch_size: Input batch size.
  24. mode: Either 'train' or 'eval'.
  25. Returns:
  26. images: Batches of images. [batch_size, image_size, image_size, 3]
  27. labels: Batches of labels. [batch_size, num_classes]
  28. Raises:
  29. ValueError: when the specified dataset is not supported.
  30. """
  31. image_size = 32
  32. if dataset == 'cifar10':
  33. label_bytes = 1
  34. label_offset = 0
  35. num_classes = 10
  36. elif dataset == 'cifar100':
  37. label_bytes = 1
  38. label_offset = 1
  39. num_classes = 100
  40. else:
  41. raise ValueError('Not supported dataset %s', dataset)
  42. depth = 3
  43. image_bytes = image_size * image_size * depth
  44. record_bytes = label_bytes + label_offset + image_bytes
  45. data_files = tf.gfile.Glob(data_path)
  46. file_queue = tf.train.string_input_producer(data_files, shuffle=True)
  47. # Read examples from files in the filename queue.
  48. reader = tf.FixedLengthRecordReader(record_bytes=record_bytes)
  49. _, value = reader.read(file_queue)
  50. # Convert these examples to dense labels and processed images.
  51. record = tf.reshape(tf.decode_raw(value, tf.uint8), [record_bytes])
  52. label = tf.cast(tf.slice(record, [label_offset], [label_bytes]), tf.int32)
  53. # Convert from string to [depth * height * width] to [depth, height, width].
  54. depth_major = tf.reshape(tf.slice(record, [label_bytes], [image_bytes]),
  55. [depth, image_size, image_size])
  56. # Convert from [depth, height, width] to [height, width, depth].
  57. image = tf.cast(tf.transpose(depth_major, [1, 2, 0]), tf.float32)
  58. if mode == 'train':
  59. image = tf.image.resize_image_with_crop_or_pad(
  60. image, image_size+4, image_size+4)
  61. image = tf.random_crop(image, [image_size, image_size, 3])
  62. image = tf.image.random_flip_left_right(image)
  63. # Brightness/saturation/constrast provides small gains .2%~.5% on cifar.
  64. # image = tf.image.random_brightness(image, max_delta=63. / 255.)
  65. # image = tf.image.random_saturation(image, lower=0.5, upper=1.5)
  66. # image = tf.image.random_contrast(image, lower=0.2, upper=1.8)
  67. image = tf.image.per_image_standardization(image)
  68. example_queue = tf.RandomShuffleQueue(
  69. capacity=16 * batch_size,
  70. min_after_dequeue=8 * batch_size,
  71. dtypes=[tf.float32, tf.int32],
  72. shapes=[[image_size, image_size, depth], [1]])
  73. num_threads = 16
  74. else:
  75. image = tf.image.resize_image_with_crop_or_pad(
  76. image, image_size, image_size)
  77. image = tf.image.per_image_standardization(image)
  78. example_queue = tf.FIFOQueue(
  79. 3 * batch_size,
  80. dtypes=[tf.float32, tf.int32],
  81. shapes=[[image_size, image_size, depth], [1]])
  82. num_threads = 1
  83. example_enqueue_op = example_queue.enqueue([image, label])
  84. tf.train.add_queue_runner(tf.train.queue_runner.QueueRunner(
  85. example_queue, [example_enqueue_op] * num_threads))
  86. # Read 'batch' labels + images from the example queue.
  87. images, labels = example_queue.dequeue_many(batch_size)
  88. labels = tf.reshape(labels, [batch_size, 1])
  89. indices = tf.reshape(tf.range(0, batch_size, 1), [batch_size, 1])
  90. labels = tf.sparse_to_dense(
  91. tf.concat(values=[indices, labels], axis=1),
  92. [batch_size, num_classes], 1.0, 0.0)
  93. assert len(images.get_shape()) == 4
  94. assert images.get_shape()[0] == batch_size
  95. assert images.get_shape()[-1] == 3
  96. assert len(labels.get_shape()) == 2
  97. assert labels.get_shape()[0] == batch_size
  98. assert labels.get_shape()[1] == num_classes
  99. # Display the training images in the visualizer.
  100. tf.summary.image('images', images)
  101. return images, labels