<jupyter_start><jupyter_text>Copyright 2019 The TensorFlow Authors.<jupyter_code>#@title 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
#
# https://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.<jupyter_output><empty_output><jupyter_text>Load images with tf.data       View on TensorFlow.org        Run in Google Colab        View source on GitHub        Download notebook   This tutorial provides a simple example of how to load an image dataset using `tf.data`.The dataset used in this example is distributed as directories of images, with one class of image per directory.  Setup<jupyter_code>from __future__ import absolute_import, division, print_function, unicode_literals

!pip install tensorflow==2.0.0-beta1
import tensorflow as tf
AUTOTUNE = tf.data.experimental.AUTOTUNE<jupyter_output><empty_output><jupyter_text>Download and inspect the dataset  Retrieve the imagesBefore you start any training, you will need a set of images to teach the network about the new classes you want to recognize. You have already created an archive of creative-commons licensed flower photos to use initially:<jupyter_code>import pathlib
data_root_orig = tf.keras.utils.get_file(origin='https://storage.googleapis.com/download.tensorflow.org/example_images/flower_photos.tgz',
                                         fname='flower_photos', untar=True)
data_root = pathlib.Path(data_root_orig)
print(data_root)<jupyter_output><empty_output><jupyter_text>After downloading 218MB, you should now have a copy of the flower photos available:<jupyter_code>for item in data_root.iterdir():
  print(item)
import random
all_image_paths = list(data_root.glob('*/*'))
all_image_paths = [str(path) for path in all_image_paths]
random.shuffle(all_image_paths)

image_count = len(all_image_paths)
image_count
all_image_paths[:10]<jupyter_output><empty_output><jupyter_text>Inspect the imagesNow let's have a quick look at a couple of the images, so you know what you are dealing with:<jupyter_code>import os
attributions = (data_root/"LICENSE.txt").open(encoding='utf-8').readlines()[4:]
attributions = [line.split(' CC-BY') for line in attributions]
attributions = dict(attributions)
import IPython.display as display

def caption_image(image_path):
    image_rel = pathlib.Path(image_path).relative_to(data_root)
    return "Image (CC BY 2.0) " + ' - '.join(attributions[str(image_rel)].split(' - ')[:-1])

for n in range(3):
  image_path = random.choice(all_image_paths)
  display.display(display.Image(image_path))
  print(caption_image(image_path))
  print()<jupyter_output><empty_output><jupyter_text>Determine the label for each image List the available labels:<jupyter_code>label_names = sorted(item.name for item in data_root.glob('*/') if item.is_dir())
label_names<jupyter_output><empty_output><jupyter_text>Assign an index to each label:<jupyter_code>label_to_index = dict((name, index) for index, name in enumerate(label_names))
label_to_index<jupyter_output><empty_output><jupyter_text>Create a list of every file, and its label index:<jupyter_code>all_image_labels = [label_to_index[pathlib.Path(path).parent.name]
                    for path in all_image_paths]

print("First 10 labels indices: ", all_image_labels[:10])<jupyter_output><empty_output><jupyter_text>Load and format the images TensorFlow includes all the tools you need to load and process images:<jupyter_code>img_path = all_image_paths[0]
img_path<jupyter_output><empty_output><jupyter_text>Here is the raw data:<jupyter_code>img_raw = tf.io.read_file(img_path)
print(repr(img_raw)[:100]+"...")<jupyter_output><empty_output><jupyter_text>Decode it into an image tensor:<jupyter_code>img_tensor = tf.image.decode_image(img_raw)

print(img_tensor.shape)
print(img_tensor.dtype)<jupyter_output><empty_output><jupyter_text>Resize it for your model:<jupyter_code>img_final = tf.image.resize(img_tensor, [192, 192])
img_final = img_final/255.0
print(img_final.shape)
print(img_final.numpy().min())
print(img_final.numpy().max())<jupyter_output><empty_output><jupyter_text>Wrap up these up in simple functions for later.<jupyter_code>def preprocess_image(image):
  image = tf.image.decode_jpeg(image, channels=3)
  image = tf.image.resize(image, [192, 192])
  image /= 255.0  # normalize to [0,1] range

  return image
def load_and_preprocess_image(path):
  image = tf.io.read_file(path)
  return preprocess_image(image)
import matplotlib.pyplot as plt

image_path = all_image_paths[0]
label = all_image_labels[0]

plt.imshow(load_and_preprocess_image(img_path))
plt.grid(False)
plt.xlabel(caption_image(img_path))
plt.title(label_names[label].title())
print()<jupyter_output><empty_output><jupyter_text>Build a `tf.data.Dataset`  A dataset of images The easiest way to build a `tf.data.Dataset` is using the `from_tensor_slices` method.Slicing the array of strings, results in a dataset of strings:<jupyter_code>path_ds = tf.data.Dataset.from_tensor_slices(all_image_paths)<jupyter_output><empty_output><jupyter_text>The `shapes` and `types` describe the content of each item in the dataset. In this case it is a set of scalar binary-strings<jupyter_code>print(path_ds)<jupyter_output><empty_output><jupyter_text>Now create a new dataset that loads and formats images on the fly by mapping `preprocess_image` over the dataset of paths.<jupyter_code>image_ds = path_ds.map(load_and_preprocess_image, num_parallel_calls=AUTOTUNE)
import matplotlib.pyplot as plt

plt.figure(figsize=(8,8))
for n, image in enumerate(image_ds.take(4)):
  plt.subplot(2,2,n+1)
  plt.imshow(image)
  plt.grid(False)
  plt.xticks([])
  plt.yticks([])
  plt.xlabel(caption_image(all_image_paths[n]))
  plt.show()<jupyter_output><empty_output><jupyter_text>A dataset of `(image, label)` pairs Using the same `from_tensor_slices` method you can build a dataset of labels:<jupyter_code>label_ds = tf.data.Dataset.from_tensor_slices(tf.cast(all_image_labels, tf.int64))
for label in label_ds.take(10):
  print(label_names[label.numpy()])<jupyter_output><empty_output><jupyter_text>Since the datasets are in the same order you can just zip them together to get a dataset of `(image, label)` pairs:<jupyter_code>image_label_ds = tf.data.Dataset.zip((image_ds, label_ds))<jupyter_output><empty_output><jupyter_text>The new dataset's `shapes` and `types` are tuples of shapes and types as well, describing each field:<jupyter_code>print(image_label_ds)<jupyter_output><empty_output><jupyter_text>Note: When you have arrays like `all_image_labels` and `all_image_paths` an alternative to `tf.data.dataset.Dataset.zip` is to slice the pair of arrays.<jupyter_code>ds = tf.data.Dataset.from_tensor_slices((all_image_paths, all_image_labels))

# The tuples are unpacked into the positional arguments of the mapped function
def load_and_preprocess_from_path_label(path, label):
  return load_and_preprocess_image(path), label

image_label_ds = ds.map(load_and_preprocess_from_path_label)
image_label_ds<jupyter_output><empty_output><jupyter_text>Basic methods for training To train a model with this dataset you will want the data:* To be well shuffled.* To be batched.* To repeat forever.* Batches to be available as soon as possible.These features can be easily added using the `tf.data` api.<jupyter_code>BATCH_SIZE = 32

# Setting a shuffle buffer size as large as the dataset ensures that the data is
# completely shuffled.
ds = image_label_ds.shuffle(buffer_size=image_count)
ds = ds.repeat()
ds = ds.batch(BATCH_SIZE)
# `prefetch` lets the dataset fetch batches in the background while the model is training.
ds = ds.prefetch(buffer_size=AUTOTUNE)
ds<jupyter_output><empty_output><jupyter_text>There are a few things to note here:1. The order is important.  * A `.shuffle` after a `.repeat` would shuffle items across epoch boundaries (some items will be seen twice before others are seen at all).  * A `.shuffle` after a `.batch` would shuffle the order of the batches, but not shuffle the items across batches.1. You use a `buffer_size` the same size as the dataset for a full shuffle. Up to the dataset size, large values provide better randomization, but use more memory.1. The shuffle buffer is filled before any elements are pulled from it. So a large `buffer_size` may cause a delay when your `Dataset` is starting.1. The shuffeled dataset doesn't report the end of a dataset until the shuffle-buffer is completely empty. The `Dataset` is restarted by `.repeat`, causing another wait for the shuffle-buffer to be filled.This last point can be addressed by using the `tf.data.Dataset.apply` method with the fused `tf.data.experimental.shuffle_and_repeat` function:<jupyter_code>ds = image_label_ds.apply(
  tf.data.experimental.shuffle_and_repeat(buffer_size=image_count))
ds = ds.batch(BATCH_SIZE)
ds = ds.prefetch(buffer_size=AUTOTUNE)
ds<jupyter_output><empty_output><jupyter_text>Pipe the dataset to a modelFetch a copy of MobileNet v2 from `tf.keras.applications`.This will be used for a simple transfer learning example.Set the MobileNet weights to be non-trainable:<jupyter_code>mobile_net = tf.keras.applications.MobileNetV2(input_shape=(192, 192, 3), include_top=False)
mobile_net.trainable=False<jupyter_output><empty_output><jupyter_text>This model expects its input to be normalized to the `[-1,1]` range:```help(keras_applications.mobilenet_v2.preprocess_input)```...This function applies the "Inception" preprocessing which convertsthe RGB values from [0, 255] to [-1, 1]... Before you pass the input to the MobilNet model, you need to convert it from a range of `[0,1]` to `[-1,1]`:<jupyter_code>def change_range(image,label):
  return 2*image-1, label

keras_ds = ds.map(change_range)<jupyter_output><empty_output><jupyter_text>The MobileNet returns a `6x6` spatial grid of features for each image.Pass it a batch of images to see:<jupyter_code># The dataset may take a few seconds to start, as it fills its shuffle buffer.
image_batch, label_batch = next(iter(keras_ds))
feature_map_batch = mobile_net(image_batch)
print(feature_map_batch.shape)<jupyter_output><empty_output><jupyter_text>Build a model wrapped around MobileNet and use `tf.keras.layers.GlobalAveragePooling2D` to average over those space dimensions before the output `tf.keras.layers.Dense` layer:<jupyter_code>model = tf.keras.Sequential([
  mobile_net,
  tf.keras.layers.GlobalAveragePooling2D(),
  tf.keras.layers.Dense(len(label_names))])<jupyter_output><empty_output><jupyter_text>Now it produces outputs of the expected shape:<jupyter_code>logit_batch = model(image_batch).numpy()

print("min logit:", logit_batch.min())
print("max logit:", logit_batch.max())
print()

print("Shape:", logit_batch.shape)<jupyter_output><empty_output><jupyter_text>Compile the model to describe the training procedure:<jupyter_code>model.compile(optimizer=tf.keras.optimizers.Adam(),
              loss='sparse_categorical_crossentropy',
              metrics=["accuracy"])<jupyter_output><empty_output><jupyter_text>There are 2 trainable variables - the Dense `weights` and `bias`:<jupyter_code>len(model.trainable_variables)
model.summary()<jupyter_output><empty_output><jupyter_text>You are ready to train the model.Note that for demonstration purposes you will only run 3 steps per epoch, but normally you would specify the real number of steps, as defined below, before passing it to `model.fit()`:<jupyter_code>steps_per_epoch=tf.math.ceil(len(all_image_paths)/BATCH_SIZE).numpy()
steps_per_epoch
model.fit(ds, epochs=1, steps_per_epoch=3)<jupyter_output><empty_output><jupyter_text>PerformanceNote: This section just shows a couple of easy tricks that may help performance. For an in depth guide see [Input Pipeline Performance](https://www.tensorflow.org/guide/performance/datasets).The simple pipeline used above reads each file individually, on each epoch. This is fine for local training on CPU, but may not be sufficient for GPU training and is totally inappropriate for any sort of distributed training. To investigate, first build a simple function to check the performance of our datasets:<jupyter_code>import time
default_timeit_steps = 2*steps_per_epoch+1

def timeit(ds, steps=default_timeit_steps):
  overall_start = time.time()
  # Fetch a single batch to prime the pipeline (fill the shuffle buffer),
  # before starting the timer
  it = iter(ds.take(steps+1))
  next(it)

  start = time.time()
  for i,(images,labels) in enumerate(it):
    if i%10 == 0:
      print('.',end='')
  print()
  end = time.time()

  duration = end-start
  print("{} batches: {} s".format(steps, duration))
  print("{:0.5f} Images/s".format(BATCH_SIZE*steps/duration))
  print("Total time: {}s".format(end-overall_start))<jupyter_output><empty_output><jupyter_text>The performance of the current dataset is:<jupyter_code>ds = image_label_ds.apply(
  tf.data.experimental.shuffle_and_repeat(buffer_size=image_count))
ds = ds.batch(BATCH_SIZE).prefetch(buffer_size=AUTOTUNE)
ds
timeit(ds)<jupyter_output><empty_output><jupyter_text>Cache Use `tf.data.Dataset.cache` to easily cache calculations across epochs. This is very efficient, especially when the data fits in memory.Here the images are cached, after being pre-precessed (decoded and resized):<jupyter_code>ds = image_label_ds.cache()
ds = ds.apply(
  tf.data.experimental.shuffle_and_repeat(buffer_size=image_count))
ds = ds.batch(BATCH_SIZE).prefetch(buffer_size=AUTOTUNE)
ds
timeit(ds)<jupyter_output><empty_output><jupyter_text>One disadvantage to using an in memory cache is that the cache must be rebuilt on each run, giving the same startup delay each time the dataset is started:<jupyter_code>timeit(ds)<jupyter_output><empty_output><jupyter_text>If the data doesn't fit in memory, use a cache file:<jupyter_code>ds = image_label_ds.cache(filename='./cache.tf-data')
ds = ds.apply(
  tf.data.experimental.shuffle_and_repeat(buffer_size=image_count))
ds = ds.batch(BATCH_SIZE).prefetch(1)
ds
timeit(ds)<jupyter_output><empty_output><jupyter_text>The cache file also has the advantage that it can be used to quickly restart the dataset without rebuilding the cache. Note how much faster it is the second time:<jupyter_code>timeit(ds)<jupyter_output><empty_output><jupyter_text>TFRecord File  Raw image dataTFRecord files are a simple format to store a sequence of binary blobs. By packing multiple examples into the same file, TensorFlow is able to read multiple examples at once, which is especially important for performance when using a remote storage service such as GCS.First, build a TFRecord file from the raw image data:<jupyter_code>image_ds = tf.data.Dataset.from_tensor_slices(all_image_paths).map(tf.io.read_file)
tfrec = tf.data.experimental.TFRecordWriter('images.tfrec')
tfrec.write(image_ds)<jupyter_output><empty_output><jupyter_text>Next, build a dataset that reads from the TFRecord file and decodes/reformats the images using the `preprocess_image` function you defined earlier:<jupyter_code>image_ds = tf.data.TFRecordDataset('images.tfrec').map(preprocess_image)<jupyter_output><empty_output><jupyter_text>Zip that dataset with the labels dataset you defined earlier to get the expected `(image,label)` pairs:<jupyter_code>ds = tf.data.Dataset.zip((image_ds, label_ds))
ds = ds.apply(
  tf.data.experimental.shuffle_and_repeat(buffer_size=image_count))
ds=ds.batch(BATCH_SIZE).prefetch(AUTOTUNE)
ds
timeit(ds)<jupyter_output><empty_output><jupyter_text>This is slower than the `cache` version because you have not cached the preprocessing.  Serialized Tensors To save some preprocessing to the TFRecord file, first make a dataset of the processed images, as before:<jupyter_code>paths_ds = tf.data.Dataset.from_tensor_slices(all_image_paths)
image_ds = paths_ds.map(load_and_preprocess_image)
image_ds<jupyter_output><empty_output><jupyter_text>Now instead of a dataset of `.jpeg` strings, you have a dataset of tensors.To serialize this to a TFRecord file you first convert the dataset of tensors to a dataset of strings:<jupyter_code>ds = image_ds.map(tf.io.serialize_tensor)
ds
tfrec = tf.data.experimental.TFRecordWriter('images.tfrec')
tfrec.write(ds)<jupyter_output><empty_output><jupyter_text>With the preprocessing cached, data can be loaded from the TFrecord file quite efficiently - just remember to de-serialize tensor before using it:<jupyter_code>ds = tf.data.TFRecordDataset('images.tfrec')

def parse(x):
  result = tf.io.parse_tensor(x, out_type=tf.float32)
  result = tf.reshape(result, [192, 192, 3])
  return result

ds = ds.map(parse, num_parallel_calls=AUTOTUNE)
ds<jupyter_output><empty_output><jupyter_text>Now, add the labels and apply the same standard operations, as before:<jupyter_code>ds = tf.data.Dataset.zip((ds, label_ds))
ds = ds.apply(
  tf.data.experimental.shuffle_and_repeat(buffer_size=image_count))
ds=ds.batch(BATCH_SIZE).prefetch(AUTOTUNE)
ds
timeit(ds)<jupyter_output><empty_output>