Prepare structured features
Convert a flat feature vector into a matrix or higher-rank tensor before subsequent layers.
TensorFlow · Class
tf.keras.layers.Reshape changes each input sample to a specified target shape while preserving the batch dimension. It requires fixed input dimensions and can infer one target dimension with -1.
Reshape changes the non-batch dimensions of each input sample to target_shape while preserving the batch axis. The input dimensions must be known and fixed, and the target shape must contain the same number of elements, with -1 optionally allowing shape inference.
tf.keras.layers.Reshape(target_shape, **kwargs)| Name | Type | Description |
|---|---|---|
target_shape | tuple of integers | Target shape for each sample, represented as integers and excluding the samples or batch dimension. |
A tensor with shape (batch_size, *target_shape).
import tensorflow as tf
x = tf.keras.Input(shape=(12,))
y = tf.keras.layers.Reshape((3, 4))(x)
print(y.shape) # (None, 3, 4)This creates a symbolic 12-element input and reshapes each sample into three rows of four elements.
Convert a flat feature vector into a matrix or higher-rank tensor before subsequent layers.
Restore a decoder's flat output to the dimensions of an encoded image or other data representation.
Insert a symbolic shape transformation inside a Functional or Sequential Keras model.
Reshape changes each sample's layout without changing its number of elements, and it leaves the batch dimension untouched. For an input shaped (batch_size, 12) and target_shape (3, 4), the output is (batch_size, 3, 4).
Follow-up: What must be true for the reshape to be valid? The input dimensions must be known and fixed, and the target dimensions must represent the same element count, aside from one optionally inferred dimension.
target_shape is a tuple of integers describing the desired per-sample shape. It excludes the samples or batch axis, which Keras supplies and preserves separately.
Follow-up: How would you represent a batch of 12-element vectors becoming 2-by-6 tensors? Use target_shape=(2, 6), not (batch_size, 2, 6).
The output shape is (batch_size, *target_shape). Thus, Reshape((3, 4)) applied to an input with shape (12,) produces an output shape of (None, 3, 4) in a symbolic model.
Follow-up: Can a target dimension be inferred? Yes; the documentation demonstrates -1, as in (-1, 2, 2), when the element count allows that dimension to be determined.
tf.keras.layers.Layertf.keras.layers.Flattentf.keras.layers.Dense