Why tf.data?
When datasets are big, the GPU often waits for data to be read and prepared. A tf.data pipeline prepares the next batch in the background while the model trains on the current one, so no time is wasted. It also handles data that does not fit in memory.
Creating a Dataset
python
import tensorflow as tf
import keras
(x_train, y_train), (x_test, y_test) = keras.datasets.mnist.load_data()
x_train = x_train.astype("float32") / 255.0
ds = tf.data.Dataset.from_tensor_slices((x_train, y_train))
print(ds.element_spec)
The Classic Pipeline
python
train_ds = (
tf.data.Dataset.from_tensor_slices((x_train, y_train))
.shuffle(buffer_size=10000)
.batch(64)
.prefetch(tf.data.AUTOTUNE)
)
model.fit(train_ds, epochs=5)
| Step | What it does |
shuffle | Mixes the samples so batches are different each epoch |
batch | Groups samples into batches |
prefetch | Prepares the next batch while the current one is training |
map | Applies a function to every element |
cache | Keeps data in memory after the first epoch |
take / skip | Take or skip a number of elements |
Order matters: Shuffle before batch, so that individual samples get mixed. Put prefetch last.
Preprocessing with map
python
def preprocess(image, label):
image = tf.cast(image, tf.float32) / 255.0
image = tf.expand_dims(image, -1) # (28, 28) -> (28, 28, 1)
return image, label
ds = (
tf.data.Dataset.from_tensor_slices(keras.datasets.mnist.load_data()[0])
)
# Or on raw data:
raw = tf.data.Dataset.from_tensor_slices((x_train * 255, y_train))
train_ds = (raw.map(preprocess, num_parallel_calls=tf.data.AUTOTUNE)
.cache()
.shuffle(10000)
.batch(64)
.prefetch(tf.data.AUTOTUNE))
Train, Validation and Test Datasets
python
full = tf.data.Dataset.from_tensor_slices((x_train, y_train)).shuffle(60000, seed=1)
val_ds = full.take(6000).batch(64)
train_ds = full.skip(6000).batch(64).prefetch(tf.data.AUTOTUNE)
model.fit(train_ds, validation_data=val_ds, epochs=5)
Reading Images from Folders
For real images we use keras.utils.image_dataset_from_directory, which creates a tf.data.Dataset for you. You will use it in the computer vision lessons.
Peek at a Batch
python
for images, labels in train_ds.take(1):
print(images.shape, labels.shape) # (64, 28, 28) (64,)
Tip: Keras 3 models can also train on PyTorch DataLoaders or NumPy arrays. tf.data is the best choice when you use the TensorFlow backend.
Conclusion
A good input pipeline keeps your GPU busy and your code clean. Remember the pattern: map, cache, shuffle, batch and prefetch.
Quick Summary: Use tf.data.Dataset with shuffle, batch and prefetch(AUTOTUNE), and pass the dataset directly to model.fit().