0
0
TensorFlowml~15 mins

Tensor shapes and reshaping in TensorFlow - ML Experiment: Train & Evaluate

Choose your learning style9 modes available
Experiment - Tensor shapes and reshaping
Problem:You have a 1D tensor of 12 elements representing pixel values of a small image. You want to reshape it into a 2D tensor to represent the image's height and width for further processing.
Current Metrics:Original tensor shape: (12,), after reshaping: (3, 4)
Issue:You want to reshape the tensor correctly without losing data or changing the total number of elements.
Your Task
Reshape the 1D tensor of shape (12,) into a 2D tensor of shape (4, 3) and verify the reshaping is correct by printing the new shape and contents.
Do not change the total number of elements in the tensor.
Use TensorFlow functions only.
Do not flatten or reorder elements manually.
Hint 1
Hint 2
Hint 3
Solution
TensorFlow
import tensorflow as tf

# Create a 1D tensor with 12 elements
original_tensor = tf.constant([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])
print(f"Original tensor shape: {original_tensor.shape}")
print(f"Original tensor contents: {original_tensor.numpy()}")

# Reshape to 2D tensor with shape (4, 3)
reshaped_tensor = tf.reshape(original_tensor, (4, 3))
print(f"Reshaped tensor shape: {reshaped_tensor.shape}")
print(f"Reshaped tensor contents:\n{reshaped_tensor.numpy()}")
Used tf.reshape() to change the tensor shape from (12,) to (4, 3).
Printed tensor shapes and contents before and after reshaping to verify correctness.
Results Interpretation

Before reshaping, the tensor is 1D with shape (12,). After reshaping, it becomes 2D with shape (4, 3). The total number of elements remains 12, confirming no data loss.

Original tensor: [1 2 3 4 5 6 7 8 9 10 11 12]

Reshaped tensor:
[[ 1 2 3]
[ 4 5 6]
[ 7 8 9]
[10 11 12]]

Reshaping tensors changes their shape without altering the data or total number of elements. This is useful to prepare data for models that expect specific input shapes.
Bonus Experiment
Try reshaping the original tensor into shape (2, 2, 3) and verify the new shape and contents.
💡 Hint
Use tf.reshape() with shape (2, 2, 3). The product 2*2*3 must equal 12.