Prepare model inputs
Convert a flat batch or feature vector into the dimensions expected by a model layer.
TensorFlow · Function
tf.reshape returns a tensor with a requested shape while preserving all values and their order. The total number of elements must stay unchanged; one shape dimension may be inferred with -1.
tf.reshape creates a new tensor view with the requested shape while preserving the input values and their order. The requested dimensions must contain the same total number of elements; one dimension may be -1 so TensorFlow can infer it, and [] converts a one-element tensor to a scalar.
tf.reshape(tensor, shape, name=None)| Name | Type | Description |
|---|---|---|
tensor | Tensor | Input Tensor to reshape. |
shape | Tensor | Output shape; must use int32 or int64 values. |
name | string | Optional name for the operation. |
A Tensor with the same type as tensor.
import tensorflow as tf
x = tf.constant([[1, 2, 3], [4, 5, 6]])
y = tf.reshape(x, [3, 2])
print(y.numpy())
# [[1 2]
# [3 4]
# [5 6]]Creates a two-dimensional tensor with the same six values in their original order.
Convert a flat batch or feature vector into the dimensions expected by a model layer.
Collapse several compatible dimensions into one while retaining row-major value order.
Turn a tensor into a single vector for downstream processing or inspection.
Represent a one-element tensor as a scalar using an empty shape.
tf.reshape changes a tensor's shape without changing its values or their order. The output has the same element type as the input, and the total element count must remain constant.
Follow-up: How would you exchange two axes? Use tf.transpose; reshape itself does not rearrange axes.
The shape argument defines the output dimensions and may be an int32 or int64 tensor. One dimension can be -1, in which case TensorFlow computes it from the unchanged total size.
Follow-up: What does shape [-1] produce? It flattens the tensor into one dimension.
tf.reshape returns a Tensor with the same type as tensor. It can reuse the underlying data buffer because it preserves element order and count, making the operation fast regardless of tensor size.
Follow-up: Does that mean no tensor object is created? No; the operation returns a new Tensor while potentially reusing the underlying storage.
tf.shapetf.transposetf.expand_dimstf.squeeze