tf.data pipeline
Quick answer
A tf.data pipeline describes a stream of examples and transformations. Batching groups samples, shuffling changes their order, and prefetching overlaps input preparation with consumption. Construct the train, validation and test streams only after splitting original examples. Native TensorFlow examples are unexecuted; local Keras uses Torch. ByteMind execution is unverified.
TensorFlow dataset batching
import tensorflow as tfds=tf.data.Dataset.from_tensor_slices(([1,2,3,4,5],[10,20,30,40,50])).batch(2)print([(x.numpy().tolist(),y.numpy().tolist()) for x,y in ds])Expected output (NOT RUN): [([1, 2], [10, 20]), ([3, 4], [30, 40]), ([5], [50])]. Paired samples stay aligned; expected output is not locally executed.
How it works
from_tensor_slices((X,y)) emits aligned pairs along the leading axis. map transforms each element; batch(B,drop_remainder=False) retains a short final batch. shuffle(buffer_size,seed,reshuffle_each_iteration=True) samples from a finite buffer, not necessarily a full permutation of the entire dataset at once. repeat() may create an infinite stream, so set steps_per_epoch when needed. Cache after deterministic expensive transforms when appropriate; caching after randomized augmentation can freeze the first realization. prefetch(tf.data.AUTOTUNE) may improve throughput, not correctness. Fit normalization or vocabulary on training only, and do not shuffle evaluation data when predictions must align with identifiers. Keras fit also accepts NumPy arrays and Torch DataLoader in supported configurations. A seed does not ensure reproducibility across device and library versions.
Inspect a portable input alternative
import torchfrom torch.utils.data import TensorDataset,DataLoaderds=TensorDataset(torch.arange(5),torch.arange(5)*10)print([len(x) for x,y in DataLoader(ds,batch_size=2)])Expected output (locally tested): [2, 2, 1]. A Torch DataLoader is not tf.data, but illustrates the same batch boundary.
Common mistakes
Do not repeat validation indefinitely without a bound, drop evaluation tails accidentally, or split after duplicating/augmenting examples. A batch of one is still a batch.
Practice and next steps
Check the number of batches and the order of paired IDs for seven examples. Use native tf.data only in a compatible TensorFlow environment.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
tf.data pipeline — knowledge check
Apply tf.data pipeline to small examples and debugging scenarios.
What does from_tensor_slices((X,y)) preserve?
What does drop_remainder=True do?
When fit normalization statistics?
What does prefetch primarily improve?
What risk does repeat() without a count create?