Normalize tensor rank
Convert a tensor with unnecessary batch or channel singleton dimensions into the expected rank for a downstream operation.
TensorFlow · Function
Removes dimensions of size 1 from a tensor. By default it removes every singleton dimension, or only the selected singleton dimensions when axis is supplied.
tf.squeeze returns the input data with dimensions whose size is 1 removed. By default it removes every such dimension; supplying axis limits removal to the listed positions, while name optionally labels the operation.
tf.squeeze(input, axis=None, name=None)| Name | Type | Description |
|---|---|---|
input | Tensor | A Tensor to squeeze. |
axis | list of ints, optional | Optional list of integer dimension indices. If provided, only those dimensions are squeezed; it defaults to all singleton dimensions. |
name | string, optional | Optional operation name. |
A Tensor with the same type and data as input, with one or more dimensions of size 1 removed.
import tensorflow as tf
t = tf.ones([1, 2, 1, 3, 1, 1])
print(tf.shape(tf.squeeze(t)).numpy())
print(tf.shape(tf.squeeze(t, axis=[2, 4])).numpy())Creates a tensor with singleton dimensions, then removes all singleton dimensions and selected singleton dimensions.
Convert a tensor with unnecessary batch or channel singleton dimensions into the expected rank for a downstream operation.
Remove only known singleton positions while preserving other dimensions.
Prepare tensor outputs for APIs that expect scalar-like or lower-rank values.
tf.squeeze removes dimensions of size 1 while preserving the tensor's element type and data. With axis omitted, all singleton dimensions are removed; with axis provided, only the listed singleton dimensions are removed.
Follow-up: What happens if an axis points to a non-singleton dimension? The operation raises ValueError because that dimension cannot be squeezed.
axis is an optional list of integer dimension indices, and its default is effectively an empty list that requests removal of all singleton dimensions. Indices start at zero and may be negative within the input rank.
Follow-up: Why pass axis explicitly in production code? It constrains the intended shape transformation and avoids accidentally removing an unrelated singleton dimension.
The result is a Tensor with the same type as input and the same data, but with one or more dimensions of size 1 removed. ValueError can occur when the input cannot be converted to a tensor or the selected axis cannot be squeezed.
Follow-up: How should a RaggedTensor be handled? Provide axis explicitly, because the documentation requires it for RaggedTensor input.
tf.expand_dimstf.reshape