batch() combines batch_size consecutive elements of a Dataset into one element, stacking them along a new leading batch dimension — a Dataset of individual (feature, label) pairs becomes, after batch(32), a Dataset of (feature_batch, label_batch) pairs where each batch contains 32 examples. If the total number of elements isn't evenly divisible by batch_size, the final batch is smaller by default, unless drop_remainder=True is set, which discards that final partial batch entirely instead.
1Understanding dataset.batch()
batch() combines batch_size consecutive elements of a Dataset into one element, stacking them along a new leading batch dimension — a Dataset of individual (feature, label) pairs becomes, after batch(32), a Dataset of (feature_batch, label_batch) pairs where each batch contains 32 examples. If the total number of elements isn't evenly divisible by batch_size, the final batch is smaller by default, unless drop_remainder=True is set, which discards that final partial batch entirely instead.
Set drop_remainder=True when training with certain model architectures or distributed training setups that require every batch to have exactly the same, fixed size — otherwise, the smaller final batch each epoch is silently allowed by default.
import tensorflow as tf
dataset = tf.data.Dataset.from_tensor_slices([1, 2, 3, 4, 5])
batched = dataset.batch(2)
for element in batched:
print(element.numpy())2Practical Example
Here is a real-world application of dataset.batch() showing how it is used in production TensorFlow code.
import tensorflow as tf
dataset = tf.data.Dataset.from_tensor_slices([1, 2, 3, 4, 5])
batched = dataset.batch(2, drop_remainder=True)
for element in batched:
print(element.numpy())3Best Practices
Follow these guidelines when working with dataset.batch():
1. Call batch() after shuffle() in a pipeline, not before, so each batch is drawn from a properly shuffled ordering rather than shuffling pre-formed batches as whole units
2. Set drop_remainder=True when a fixed batch size is required, such as for certain distributed training strategies
3. Choose a batch_size that fits comfortably in available memory, especially GPU memory, since it directly multiplies the memory needed for one forward/backward pass
Tip: Set drop_remainder=True when training with certain model architectures or distributed training setups that require every batch to have exactly the same, fixed size — otherwise, the smaller final batch each epoch is silently allowed by default.
import tensorflow as tf
dataset = tf.data.Dataset.from_tensor_slices([1, 2, 3, 4, 5])
batched = dataset.batch(2)
for element in batched:
print(element.numpy())