0
0
TensorFlowml~5 mins

Tensor shapes and reshaping in TensorFlow

Choose your learning style9 modes available
Introduction

Tensors are like boxes holding numbers. Knowing their shape helps us organize data. Reshaping changes the box size without changing the numbers inside.

When you want to change data layout to fit a model input.
When you need to flatten images into a list for simple models.
When combining or splitting batches of data.
When preparing data for matrix operations like multiplication.
When debugging to check if tensor shapes match expected sizes.
Syntax
TensorFlow
tensor.shape
reshaped_tensor = tf.reshape(tensor, new_shape)

tensor.shape shows the size of each dimension.

tf.reshape changes the shape but keeps the same data.

Examples
This prints the shape of the tensor: (2, 3).
TensorFlow
import tensorflow as tf

# Create a tensor of shape (2, 3)
t = tf.constant([[1, 2, 3], [4, 5, 6]])
print(t.shape)
Reshape the tensor to shape (3, 2). The numbers stay the same but arranged differently.
TensorFlow
reshaped = tf.reshape(t, (3, 2))
print(reshaped)
Flatten the tensor to a 1D list. -1 means 'figure out this size automatically.'
TensorFlow
flattened = tf.reshape(t, [-1])
print(flattened)
Sample Model

This program shows how to check a tensor's shape, reshape it to a new shape, and flatten it to 1D. The numbers inside stay the same, only the shape changes.

TensorFlow
import tensorflow as tf

# Original tensor: 2 rows, 3 columns
t = tf.constant([[10, 20, 30], [40, 50, 60]])
print(f"Original shape: {t.shape}")
print(f"Original tensor:\n{t.numpy()}")

# Reshape to 3 rows, 2 columns
reshaped = tf.reshape(t, (3, 2))
print(f"\nReshaped shape: {reshaped.shape}")
print(f"Reshaped tensor:\n{reshaped.numpy()}")

# Flatten to 1D
flattened = tf.reshape(t, [-1])
print(f"\nFlattened shape: {flattened.shape}")
print(f"Flattened tensor:\n{flattened.numpy()}")
OutputSuccess
Important Notes

When reshaping, the total number of elements must stay the same.

Use -1 in tf.reshape to let TensorFlow calculate that dimension automatically.

Checking shapes helps avoid errors when feeding data to models.

Summary

Tensors have shapes that describe their size in each dimension.

Reshaping changes the shape but keeps the same data.

Use tensor.shape to see shape and tf.reshape to change it.