liveBook · Manning

Tf.data API

As explained in Deep Learning with Python, Third Edition

TensorFlow's input पाइപ്പ്-line API for building efficient data preprocessing and loading pipelines.

A training model needs its next batch ready when the current one finishes. The tf.data API builds input pipelines that load and preprocess data without making the CPU or disk a recurring bottleneck. Its core object, tf.data.Dataset, can be iterated over or passed directly to Keras model.fit(). It also works with Keras models using TensorFlow, JAX, or PyTorch backends. section 8.2.4 section 14.4.1

Start with samples, then make batches

Given a NumPy array with 1,000 vectors of length 16, tf.data.Dataset.from_tensor_slices(array) yields one vector at a time. Calling .batch(32) changes each full output batch to shape (32, 16). Calling .map(fn, num_parallel_calls=8) applies a transformation to dataset elements using parallel calls. section 8.2.4

Choose pipeline operations to match the job:

  • For images, map a file-reading, JPEG-decoding, preprocessing function over paths; zip the resulting images with labels, batch them, and prefetch. In the COCO example, prefetch(2) buffers two batches rather than loading every image tensor into memory at once. section 12.2.3
  • For text classification, map a TextVectorization layer over review datasets. Parallel preprocessing helps keep batches arriving while the accelerator trains. section 14.4.1
  • For translation, batch sentence pairs, map tokenization into inputs and next-token labels, then supply sample weights that exclude zero-padded labels. section 15.2.1
  • For large-scale text generation, interleave reads from file shards, tokenize, form fixed-length sequences, batch, and prefetch. Interleaving allows separate CPU workers to read and tokenize files simultaneously. section 16.2
Listing 12.9 Creating a dataset to train on
import tensorflow as tf

def load_image(path):                                               #1
    x = tf.io.read_file(path)
    x = tf.image.decode_jpeg(x, channels=3)
    return preprocessor(x)

images = tf.data.Dataset.from_tensor_slices([x["path"] for x in metadata])
images = images.map(load_image, num_parallel_calls=8)
labels = {"box": box_array, "class": class_array}
labels = tf.data.Dataset.from_tensor_slices(labels)

dataset = tf.data.Dataset.zip(images, labels).batch(16).prefetch(2)   #2
val_dataset, train_dataset = dataset.take(500), dataset.skip(500)     #3

Follow the complete image pipeline: file paths become decoded, preprocessed images; zipped labels become training pairs; batching and prefetching prepare them for training. section 12.2.3

A ready-made entry point is keras.utils.image_dataset_from_directory(): it indexes images in class subdirectories and returns a Dataset configured to read, shuffle, decode, resize, and batch them. Use that when its directory layout fits; build a pipeline from tensor slices or files when preprocessing and outputs need more control. Prefetch is a practical final step when batch preparation might interrupt training. section 8.2.4 section 16.2

How Deep Learning with Python, Third Edition covers it

How deep it goes
Defines Dataset and works through iteration, batching, mapping, interleaving, and prefetching; focuses on pipeline construction rather than implementation internals.
Examples
Uses batched NumPy vectors, COCO images, IMDb reviews, translation pairs, and sharded text for language-model pretraining.
What it assumes
Introduces Dataset iteration from a NumPy array before batching and mapping; later pipelines assume familiarity with image or text model inputs.
What you can do after
Build it from scratch with tf.data.Dataset operations, or apply Keras directory loaders to feed datasets into model.fit().
How it connects
Connects to Keras model.fit(), TextVectorization, parallel CPU preprocessing, and accelerator utilization.

Also explained in

Compare how 2 books explain tf.data API →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Deep Learning with Python, Third Edition. The section links point to the parts of the book it draws on.