Input Pipelines with tf.data & TFRecord
|
This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production. |
A tf.data.Dataset is a lazy, re-iterable description of a stream of elements, plus a chain of transformations applied to it. It is how data reaches model.fit() and custom loops without a Python for loop doing the work, and it is the shared currency of the Keras data loaders (see Loading Images, Text & Audio from Disk) and of TensorFlow Datasets (see TensorFlow Datasets). This page covers creating datasets, the main transformations, and the TFRecord file format. Making the pipeline fast is on tf.data Performance, and preprocessing that lives inside the model is on Keras Preprocessing Layers.
It targets Python 3.13, TensorFlow 2.21 with Keras 3.15 (TensorFlow 2.22 is upcoming, and PyTorch 2.15 and scikit-learn 1.9 are mentioned for comparison) and was checked against the official documentation on 2026-10-30. Examples were run on Python 3.13 with TensorFlow 2.21 and Keras 3.15 (CPU) on 2026-10-31; the text-file example was run on small generated files. For the PyTorch equivalent see Datasets and DataLoader, and for the NumPy side of the data see NumPy file I/O.
The mental model
A dataset is a pipeline of three stages: a source (in-memory tensors, a generator, text lines, TFRecord files), a chain of transformations (map, filter, shuffle, batch and others), and a consumer (an iterator in a loop, or fit). Each transformation returns a new dataset; nothing runs until something iterates. Every element has a structure (a tensor, a tuple, or a dict of tensors) described by dataset.element_spec, a nested structure of tf.TensorSpec objects giving shape and dtype.
import tensorflow as tf
ds = tf.data.Dataset.from_tensor_slices(([1.0, 2.0, 3.0, 4.0], [0, 1, 0, 1]))
print(ds.element_spec)
# (TensorSpec(shape=(), dtype=tf.float32, name=None),
# TensorSpec(shape=(), dtype=tf.int32, name=None))
for x, y in ds.take(2):
print(x.numpy(), y.numpy()) # 1.0 0 / 2.0 1
print(len(ds), ds.cardinality().numpy()) # 4 4
len(ds) raises when the cardinality is unknown or infinite (after repeat() or filter); ds.cardinality() returns tf.data.UNKNOWN_CARDINALITY or tf.data.INFINITE_CARDINALITY in those cases. Python for over a dataset works in eager code, and inside tf.function it is converted to a graph loop by AutoGraph (see Graphs, tf.function, AutoGraph & Retracing).
Creating datasets
| Source | Use |
|---|---|
|
slice along the first axis of a tensor, NumPy array, or nested structure of them; every component must share the first dimension |
|
one element containing the whole structure |
|
integers, mainly for tests and for |
|
wrap a Python generator |
|
one element per text line |
|
serialized records from TFRecord files |
|
file paths matching a glob, shuffled by default |
|
combine datasets |
From arrays: pass a tuple or a dict so features and labels stay together. A dict gives named features that Keras functional models can consume by input name.
import numpy as np
import tensorflow as tf
features = np.random.rand(1000, 8).astype("float32")
labels = np.random.randint(0, 3, size=(1000,))
ds = tf.data.Dataset.from_tensor_slices((features, labels))
named = tf.data.Dataset.from_tensor_slices(
{"age": [30, 40, 50], "income": [1.0, 2.5, 3.0]}
)
for row in named.take(1):
print({k: v.numpy() for k, v in row.items()}) # {'age': np.int32(30), 'income': np.float32(1.0)}
from_tensor_slices embeds the arrays in the graph as constants when used inside tf.function, which can bloat the graph and hit the 2 GB protobuf limit for large arrays. For arrays that fit in memory this is fine in eager code; for very large data use files or a generator.
Generators
def sample_stream():
rng = np.random.default_rng(0)
for _ in range(100):
n = rng.integers(3, 8)
yield rng.random(n).astype("float32"), int(rng.integers(0, 2))
ds = tf.data.Dataset.from_generator(
sample_stream,
output_signature=(
tf.TensorSpec(shape=(None,), dtype=tf.float32),
tf.TensorSpec(shape=(), dtype=tf.int32),
),
)
batched = ds.padded_batch(8) # variable-length vectors are padded with zeros
for x, y in batched.take(1):
print(x.shape, y.shape) # (8, 7) (8,): 7 is the longest vector in the batch
Pass the generator function itself (a callable returning an iterator), not an already created generator, so the dataset can restart it every epoch. output_signature replaced the older output_types and output_shapes arguments, which are deprecated. A generator runs Python code under the GIL, so it is the slowest source; it is fine for prototypes and for data that is hard to express otherwise. Use args= to pass parameters, and tf.py_function or tf.numpy_function inside map for the same escape hatch with the same cost.
Text and files
files = tf.data.Dataset.list_files("data/train/*.txt", shuffle=True, seed=1)
lines = tf.data.TextLineDataset(["a.txt", "b.txt"])
lines = lines.skip(1) # skip a CSV header
lines = lines.filter(lambda s: tf.strings.length(s) > 0)
defaults = [0.0, 0.0, 0]
def parse_csv(line):
f1, f2, label = tf.io.decode_csv(line, record_defaults=defaults)
return tf.stack([f1, f2]), label
ds = lines.map(parse_csv)
For a whole CSV there is also tf.data.experimental.make_csv_dataset, but the experimental namespace changes more often than the core API; for tabular data that fits in memory, loading with pandas (see pandas CSV I/O) and from_tensor_slices is simpler.
Core transformations
ds = tf.data.Dataset.range(10)
ds.map(lambda x: x * x) # element-wise, traced into a graph
ds.filter(lambda x: x % 2 == 0) # keep matching elements
ds.shuffle(buffer_size=10, seed=42, reshuffle_each_iteration=True)
ds.batch(4, drop_remainder=False) # last batch may be smaller
ds.repeat(3) # three epochs; repeat() is infinite
ds.take(5); ds.skip(5) # head and tail
ds.window(3, shift=1) # sliding windows, each a nested dataset
ds.flat_map(lambda x: tf.data.Dataset.from_tensors(x).repeat(2))
ds.enumerate(start=0) # adds an index
ds.scan(tf.constant(0, tf.int64), lambda s, x: (s + x, s + x)) # running sum; the state dtype must match range's int64
Guidance for the ones that cause most mistakes:
-
maptraces your Python function once with symbolic tensors, so ordinary Pythonif,printand NumPy calls do not behave per element. Use TensorFlow operations (tf.cond,tf.print) ortf.py_function. The usual retracing and AutoGraph rules apply. -
shuffle(buffer_size)keeps a buffer of that many elements and draws randomly from it. A buffer smaller than the dataset is only a local shuffle; ideal uniform shuffling needsbuffer_size >= dataset size. With files, shuffle the file list first and then use a modest element buffer. Callshufflebeforebatchso batches mix examples, and beforerepeatif you want every epoch to be a complete pass;reshuffle_each_iteration=True(the default) reorders every epoch. -
batchstacks elements, which requires equal shapes; usepadded_batchfor variable-length sequences orragged_batchto keep them ragged (see Ragged & Sparse Tensors).drop_remainder=Truegives a static batch dimension, which TPUs and some compiled paths require. -
repeat()without a count makes the dataset infinite, sofitthen needssteps_per_epoch. With a finite dataset, Kerasfitsimply restarts it every epoch and you need norepeat. -
windowreturns a dataset of datasets; flatten it withflat_map(lambda w: w.batch(3)). For time-series windows from arrays, seetimeseries_dataset_from_arrayon Loading Images, Text & Audio from Disk. -
interleaveandmapacceptnum_parallel_calls, covered withprefetchandcacheon tf.data Performance.
A typical training pipeline
def preprocess(x, y):
x = tf.cast(x, tf.float32) / 255.0
return x, y
(x_train, y_train), _ = tf.keras.datasets.mnist.load_data() # Keras datasets API
train = (
tf.data.Dataset.from_tensor_slices((x_train, y_train))
.shuffle(10_000, seed=0)
.map(preprocess, num_parallel_calls=tf.data.AUTOTUNE)
.batch(128)
.prefetch(tf.data.AUTOTUNE)
)
# model.fit(train, epochs=3)
keras.datasets.mnist.load_data() is the Keras 3 spelling of the same call; with the keras package imported as keras, the dataset can be passed straight to model.fit. A tuple (inputs, labels) is the contract fit, evaluate and predict understand (see compile, fit, evaluate & predict); a dataset of dicts is matched to named model inputs. Datasets that yield (x, y, sample_weight) triples carry per-sample weights.
Data and the Keras backend
Keras 3 can run on JAX, PyTorch or TensorFlow backends. A tf.data.Dataset is accepted by fit on every backend (Keras converts batches to the active backend’s tensors), so the pipeline code on this page is backend independent as long as TensorFlow is installed for tf.data. Details are in Keras Multi-Backend. Preprocessing written with tf.* operations inside map runs in the tf.data runtime on the CPU and is separate from the model; preprocessing done with Keras preprocessing layers inside the dataset’s map is also fine, but placed inside the model it travels with the exported model.
TFRecord
TFRecord is TensorFlow’s simple binary container: a sequence of records, each a byte string with a length and CRC checksums. It is suited to large datasets stored on network or cloud storage: sequential reads, easy sharding into many files, and no per-file open overhead for millions of small files. The records are opaque bytes; by convention each holds a serialized tf.train.Example protocol buffer, a map from feature names to one of three list types: BytesList, FloatList or Int64List.
Writing
import numpy as np
import tensorflow as tf
def _bytes(value):
if isinstance(value, type(tf.constant(0))):
value = value.numpy()
return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))
def _float(values):
return tf.train.Feature(float_list=tf.train.FloatList(value=values))
def _int64(values):
return tf.train.Feature(int64_list=tf.train.Int64List(value=values))
def to_example(image_bytes, label, embedding):
feature = {
"image": _bytes(image_bytes), # encoded JPEG or PNG bytes
"label": _int64([label]),
"embedding": _float(embedding),
}
return tf.train.Example(features=tf.train.Features(feature=feature))
image = tf.io.encode_jpeg(tf.cast(tf.random.uniform((32, 32, 3), 0, 255), tf.uint8))
with tf.io.TFRecordWriter("train-00000-of-00001.tfrecord") as writer:
for i in range(100):
example = to_example(image, i % 3, np.random.rand(4).astype("float32"))
writer.write(example.SerializeToString())
Only three value types exist, so smaller integer types, booleans and enums go in Int64List, and strings and encoded images go in BytesList. Store images as encoded JPEG or PNG bytes to keep files small, or serialize any tensor with tf.io.serialize_tensor and restore it with tf.io.parse_tensor. tf.io.TFRecordWriter accepts tf.io.TFRecordOptions(compression_type="GZIP") for compressed files; the reader must be told the same compression type.
For large corpora, write many shards (tens to hundreds of megabytes each, for example train-00017-of-00128.tfrecord) so that reading can be parallelized and files can be spread across workers.
Reading and parsing
feature_description = {
"image": tf.io.FixedLenFeature([], tf.string),
"label": tf.io.FixedLenFeature([], tf.int64),
"embedding": tf.io.FixedLenFeature([4], tf.float32),
}
def parse(record):
parsed = tf.io.parse_single_example(record, feature_description)
image = tf.io.decode_jpeg(parsed["image"], channels=3)
image = tf.image.convert_image_dtype(image, tf.float32)
return (image, parsed["embedding"]), parsed["label"]
files = tf.data.Dataset.list_files("train-*.tfrecord")
ds = (
files.interleave(
tf.data.TFRecordDataset,
cycle_length=4,
num_parallel_calls=tf.data.AUTOTUNE,
)
.map(parse, num_parallel_calls=tf.data.AUTOTUNE)
.shuffle(1000)
.batch(32)
.prefetch(tf.data.AUTOTUNE)
)
FixedLenFeature(shape, dtype, default_value=None) requires the feature in every example; FixedLenSequenceFeature and VarLenFeature (returned as a SparseTensor) cover variable lengths, and tf.io.parse_example parses a whole batch at once, which is faster than parse_single_example per record: batch the raw records first, then map parse_example. Pass the same types as written; a mismatch between tf.float32 and an Int64List raises an error at parse time, not at write time.
Reading an Example without a pipeline is useful for debugging:
for raw in tf.data.TFRecordDataset("train-00000-of-00001.tfrecord").take(1):
example = tf.train.Example()
example.ParseFromString(raw.numpy())
print(list(example.features.feature.keys())) # ['image', 'label', 'embedding']
Checkpointing and saving a dataset
ds.save(path) and tf.data.Dataset.load(path) write and read a dataset snapshot in TensorFlow’s own sharded format (they replace tf.data.experimental.save and load), useful for caching an expensive preprocessing result across runs. Iterator state can be saved with tf.train.Checkpoint(iterator=iter(ds)) to resume mid-epoch (see Training Checkpoints). The method signatures can change, so check the API page before relying on options such as compression and shard_func.
Common mistakes
-
Shuffling after batching, which only reorders whole batches.
-
A shuffle buffer of 1 to 100 on large, ordered data (for example sorted by class), which leaves the data effectively unshuffled.
-
Forgetting
.batch()and getting shape errors because Keras expects a leading batch dimension. -
Using Python state,
printor NumPy insidemapand expecting per-element behaviour; the function is traced. -
Creating a generator object instead of passing the generator function to
from_generator, so the second epoch is empty. -
Using
from_generatorwithoutput_types/output_shapes, deprecated in favour ofoutput_signature. -
Parsing TFRecords one record at a time at scale when batching raw bytes and
parse_examplewould be faster. -
Mixing up a dataset’s
repeat()withsteps_per_epoch; an infinite dataset needs it, a finite one does not. -
Assuming the pipeline is cheap: measure it with the guidance on tf.data Performance and the profiler (see Performance, XLA & Profiling).
The general ideas of epochs, batches and shuffling are in Training Deep Networks.