expand_dims() is commonly needed to add a batch dimension to a single example before feeding it into a model that expects a batch of inputs, since models typically expect a leading batch dimension even when processing just one example, or to add a channel dimension to grayscale image data that otherwise lacks the channel axis color images naturally have. The axis parameter specifies exactly where the new size-1 dimension is inserted — axis=0 adds it at the very front, while other values insert it elsewhere in the shape.
1Understanding tf.expand_dims()
expand_dims() is commonly needed to add a batch dimension to a single example before feeding it into a model that expects a batch of inputs, since models typically expect a leading batch dimension even when processing just one example, or to add a channel dimension to grayscale image data that otherwise lacks the channel axis color images naturally have. The axis parameter specifies exactly where the new size-1 dimension is inserted — axis=0 adds it at the very front, while other values insert it elsewhere in the shape.
Use tf.expand_dims(tensor, axis=0) to add a batch dimension of size 1 to a single example before passing it to a model that expects batched input — most Keras models expect a leading batch axis even when predicting on just one example at a time.
import tensorflow as tf
x = tf.constant([1, 2, 3])
expanded = tf.expand_dims(x, axis=0)
print(expanded.shape)2Practical Example
Here is a real-world application of tf.expand_dims() showing how it is used in production TensorFlow code.
import tensorflow as tf
image = tf.ones([28, 28])
with_channel = tf.expand_dims(image, axis=-1)
print(with_channel.shape)3Best Practices
Follow these guidelines when working with tf.expand_dims():
1. Use expand_dims() to add a batch dimension to a single example before calling model.predict() or similar, since models typically expect batched input even for one example
2. Use expand_dims() to add a missing channel dimension to grayscale image data, matching the shape convention color image data naturally has
3. Use tf.squeeze() as the inverse operation to remove size-1 dimensions you no longer need, rather than manually reshaping them away
Tip: Use tf.expand_dims(tensor, axis=0) to add a batch dimension of size 1 to a single example before passing it to a model that expects batched input — most Keras models expect a leading batch axis even when predicting on just one example at a time.
import tensorflow as tf
x = tf.constant([1, 2, 3])
expanded = tf.expand_dims(x, axis=0)
print(expanded.shape)