Add a batch axis
Prepare a single example for a model that expects a batch dimension.
TensorFlow · Function
Inserts a length-1 axis into a tensor at a chosen position. It uses zero-based Python indexing, with negative axes counted from the end.
tf.expand_dims creates a new axis of length 1 at the requested position while preserving the input values. The position uses zero-based Python indexing, and negative positions count backward from the end.
tf.expand_dims(input, axis, name=None)| Name | Type | Description |
|---|---|---|
input | Tensor | A Tensor. |
axis | int | Integer specifying the dimension index at which to expand the shape of input. For an input of D dimensions, it must be in [-(D+1), D], inclusive. |
name | string | Optional string naming the output Tensor. |
A tensor with the same data as input, with an additional dimension inserted at the index specified by axis.
axis must be within the input-rank-dependent valid range; an out-of-range value raises an error.-(D+1) through D, inclusive.import tensorflow as tf
image = tf.zeros([10, 10, 3])
batched = tf.expand_dims(image, axis=0)
print(batched.shape) # (1, 10, 10, 3)Adds a leading batch dimension to a single image tensor.
Prepare a single example for a model that expects a batch dimension.
Make tensor ranks or axis positions compatible for elementwise broadcasting.
Represent scalar values with an explicit final vector-length dimension.
tf.expand_dims do?It inserts a dimension whose length is 1 at the specified axis and returns a tensor with the same data as the input. The axis follows zero-based Python indexing, including negative indices.
Follow-up: How would you add a batch dimension to an image shaped [10, 10, 3]? Use tf.expand_dims(image, axis=0), producing shape [1, 10, 10, 3].
For an input with rank D, axis may be any integer from -(D+1) to D, inclusive. Negative axes count backward from the end, so axis=-1 inserts the innermost dimension.
Follow-up: What shape results from expanding a [10, 10, 3] tensor with axis=-1? The result is [10, 10, 3, 1].
The operation is useful for adding an outer batch dimension, aligning axes for broadcasting, or adding an inner vector-length axis to scalar tensors. It changes shape but does not alter the tensor's data.
Follow-up: When would an inner axis be useful? It can make tensor shapes compatible with an operation that expects a final singleton feature or vector-length dimension.
tf.squeezetf.reshapetf.sparse.expand_dims