Build a leading batch dimension
Combine several same-shaped feature vectors into one batch-like tensor.
TensorFlow · Function
Stacks equally shaped tensors along a new axis, producing a tensor whose rank is one greater than each input. The axis determines where the new dimension is inserted.
tf.stack takes tensors with matching shapes and combines them along a selected axis. The result gains one rank: stacking N inputs of rank R produces a rank R+1 tensor, while the axis determines where the new dimension appears.
tf.stack(values, axis=0, name='stack')| Name | Type | Description |
|---|---|---|
values | list of Tensor | A list of Tensor objects with identical shape and type. |
axis | int | Dimension along which to stack; defaults to the first dimension. Negative values are supported within the valid output-rank range. |
name | string | Optional name for the operation. |
A stacked Tensor with the same type as values.
import tensorflow as tf
x = tf.constant([1, 4])
y = tf.constant([2, 5])
z = tf.constant([3, 6])
result = tf.stack([x, y, z], axis=1)
print(result)Creates a rank-2 tensor by inserting a new axis at position 1.
Combine several same-shaped feature vectors into one batch-like tensor.
Arrange corresponding tensor slices in a chosen position within a multidimensional result.
Convert a sequence of compatible intermediate tensors into one tensor for later computation.
tf.stack combines a list of equally shaped tensors into one tensor whose rank is one greater than the inputs. It inserts a new dimension at the requested axis, with axis 0 placing the input list dimension first.
Follow-up: How does axis 1 differ from axis 0 for rank-3 inputs? Axis 0 produces shape (N, A, B, C), whereas axis 1 produces (A, N, B, C).
values is the input tensor list, axis selects the new dimension and defaults to 0, and name optionally names the operation. The inputs must share shape and type.
Follow-up: What constraint applies to axis? For input rank R, valid values are from -(R+1) through R inclusive.
For N inputs shaped (A, B, C), stacking on axis 0 creates (N, A, B, C), while stacking on axis 1 creates (A, N, B, C). Thus, axis controls the position of the inserted dimension.
Follow-up: What is the NumPy counterpart? The documentation identifies np.stack as the equivalent operation.
tf.parallel_stacktf.concattf.unstacktf.ragged.stacknp.stack