Jeremiah_

cifar_input.py

Feb 21st, 2020
161
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.15 KB | None | 0 0
  1. # Copyright 2015 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.  
  16. """Routine for decoding the CIFAR-10 binary file format."""
  17.  
  18. from __future__ import absolute_import
  19. from __future__ import division
  20. from __future__ import print_function
  21.  
  22. import tensorflow as tf
  23. import tensorflow_datasets as tfds
  24.  
  25. # Process images of this size. Note that this differs from the original CIFAR
  26. # image size of 32 x 32. If one alters this number, then the entire model
  27. # architecture will change and any model would need to be retrained.
  28. IMAGE_SIZE = 24
  29.  
  30. # Global constants describing the CIFAR-10 data set.
  31. NUM_CLASSES = 10
  32. NUM_EXAMPLES_PER_EPOCH_FOR_TRAIN = 50000
  33. NUM_EXAMPLES_PER_EPOCH_FOR_EVAL = 10000
  34.  
  35.  
  36. def _get_images_labels(batch_size, split, distords=False):
  37.   """Returns Dataset for given split."""
  38.   dataset = tfds.load(name='cifar10', split=split)
  39.   scope = 'data_augmentation' if distords else 'input'
  40.   with tf.name_scope(scope):
  41.     dataset = dataset.map(DataPreprocessor(distords), num_parallel_calls=10)
  42.   # Dataset is small enough to be fully loaded on memory:
  43.   dataset = dataset.prefetch(-1)
  44.   dataset = dataset.repeat().batch(batch_size)
  45.   iterator = tf.compat.v1.data.make_one_shot_iterator(dataset)
  46.   images_labels = iterator.get_next()
  47.   images, labels = images_labels['input'], images_labels['target']
  48.   tf.summary.image('images', images)
  49.   return images, labels
  50.  
  51.  
  52. class DataPreprocessor(object):
  53.   """Applies transformations to dataset record."""
  54.  
  55.   def __init__(self, distords):
  56.     self._distords = distords
  57.  
  58.   def __call__(self, record):
  59.     """Process img for training or eval."""
  60.     img = record['image']
  61.     img = tf.cast(img, tf.float32)
  62.     if self._distords:  # training
  63.       # Randomly crop a [height, width] section of the image.
  64.       img = tf.image.random_crop(img, [IMAGE_SIZE, IMAGE_SIZE, 3])
  65.       # Randomly flip the image horizontally.
  66.       img = tf.image.random_flip_left_right(img)
  67.       # Because these operations are not commutative, consider randomizing
  68.       # the order their operation.
  69.       # NOTE: since per_image_standardization zeros the mean and makes
  70.       # the stddev unit, this likely has no effect see tensorflow#1458.
  71.       img = tf.image.random_brightness(img, max_delta=63)
  72.       img = tf.image.random_contrast(img, lower=0.2, upper=1.8)
  73.     else:  # Image processing for evaluation.
  74.       # Crop the central [height, width] of the image.
  75.       img = tf.image.resize_image_with_crop_or_pad(img, IMAGE_SIZE, IMAGE_SIZE)
  76.     # Subtract off the mean and divide by the variance of the pixels.
  77.     img = tf.image.per_image_standardization(img)
  78.     return dict(input=img, target=record['label'])
  79.  
  80.  
  81. def distorted_inputs(batch_size):
  82.   """Construct distorted input for CIFAR training using the Reader ops.
  83.  
  84.  Args:
  85.    batch_size: Number of images per batch.
  86.  
  87.  Returns:
  88.    images: Images. 4D tensor of [batch_size, IMAGE_SIZE, IMAGE_SIZE, 3] size.
  89.    labels: Labels. 1D tensor of [batch_size] size.
  90.  """
  91.   return _get_images_labels(batch_size, tfds.Split.TRAIN, distords=True)
  92.  
  93.  
  94. def inputs(eval_data, batch_size):
  95.   """Construct input for CIFAR evaluation using the Reader ops.
  96.  
  97.  Args:
  98.    eval_data: bool, indicating if one should use the train or eval data set.
  99.    batch_size: Number of images per batch.
  100.  
  101.  Returns:
  102.    images: Images. 4D tensor of [batch_size, IMAGE_SIZE, IMAGE_SIZE, 3] size.
  103.    labels: Labels. 1D tensor of [batch_size] size.
  104.  """
  105.   split = tfds.Split.TEST if eval_data == 'test' else tfds.Split.TRAIN
  106.   return _get_images_labels(batch_size, split)
Advertisement
Add Comment
Please, Sign In to add comment