Bird
Raised Fist0
PyTorchml~20 mins

Tensor shapes and dimensions in PyTorch - ML Experiment: Train & Evaluate

Choose your learning style10 modes available
Experiment - Tensor shapes and dimensions
Problem:You are working with tensors in PyTorch and want to understand how their shapes and dimensions affect operations like matrix multiplication and reshaping.
Current Metrics:No model training metrics yet; the current challenge is understanding tensor shapes and how to manipulate them correctly.
Issue:You often get errors due to mismatched tensor shapes when performing operations like matrix multiplication or reshaping tensors incorrectly.
Your Task
Learn to correctly identify tensor shapes and dimensions, and perform basic tensor operations such as reshaping and matrix multiplication without errors.
Use PyTorch tensors only.
Do not use any external libraries for tensor operations.
Keep tensor dimensions compatible for operations.
Hint 1
Hint 2
Hint 3
Solution
PyTorch
import torch

# Create two tensors
# Tensor A: shape (2, 3)
A = torch.tensor([[1, 2, 3], [4, 5, 6]])
# Tensor B: shape (3, 2)
B = torch.tensor([[7, 8], [9, 10], [11, 12]])

print(f"Shape of A: {A.shape}")  # Output: torch.Size([2, 3])
print(f"Shape of B: {B.shape}")  # Output: torch.Size([3, 2])

# Matrix multiplication: (2,3) x (3,2) -> (2,2)
C = torch.matmul(A, B)
print(f"Result of A x B: {C}")
print(f"Shape of C: {C.shape}")  # Output: torch.Size([2, 2])

# Reshape tensor C from (2, 2) to (4,)
C_reshaped = C.view(4)
print(f"Reshaped C: {C_reshaped}")
print(f"Shape of reshaped C: {C_reshaped.shape}")

# Try an incorrect reshape (will raise error if uncommented)
# C.view(3)  # Cannot reshape 4 elements into shape (3,)

# Create a tensor D with shape (4, 1, 2)
D = torch.arange(8).view(4, 1, 2)
print(f"Tensor D: {D}")
print(f"Shape of D: {D.shape}")

# Squeeze removes dimensions of size 1
D_squeezed = D.squeeze()
print(f"Shape of D after squeeze: {D_squeezed.shape}")  # Output: torch.Size([4, 2])

# Unsqueeze adds a dimension at position 1
D_unsqueezed = D_squeezed.unsqueeze(1)
print(f"Shape of D after unsqueeze: {D_unsqueezed.shape}")  # Output: torch.Size([4, 1, 2])
Added tensor creation with specific shapes to demonstrate shape properties.
Performed matrix multiplication with compatible shapes to show correct operation.
Used view() to reshape tensors correctly and showed error example for incorrect reshape.
Demonstrated squeeze() and unsqueeze() to manipulate tensor dimensions.
Results Interpretation

Before: Frequent errors due to shape mismatches and confusion about tensor dimensions.
After: Clear understanding of tensor shapes, successful matrix multiplication, and reshaping without errors.

Understanding tensor shapes and dimensions is crucial for performing operations correctly in PyTorch. Checking shapes and using reshape functions carefully prevents errors and enables flexible tensor manipulation.
Bonus Experiment
Try performing batch matrix multiplication with tensors of shape (batch_size, n, m) and (batch_size, m, p).
💡 Hint
Use torch.bmm() for batch matrix multiplication and ensure batch sizes and inner dimensions match.

Practice

(1/5)
1. What does the shape of a PyTorch tensor represent?
easy
A. The number of elements in each dimension of the tensor
B. The data type of the tensor elements
C. The device where the tensor is stored
D. The memory size of the tensor in bytes

Solution

  1. Step 1: Understand tensor shape meaning

    The shape of a tensor tells how many elements are in each dimension, like rows and columns in a matrix.
  2. Step 2: Differentiate from other properties

    Data type, device, and memory size are different properties and not related to shape.
  3. Final Answer:

    The number of elements in each dimension of the tensor -> Option A
  4. Quick Check:

    Tensor shape = elements per dimension [OK]
Hint: Shape = counts of elements per dimension [OK]
Common Mistakes:
  • Confusing shape with data type
  • Thinking shape shows memory size
  • Mixing shape with device location
2. Which of the following is the correct way to get the shape of a tensor t in PyTorch?
easy
A. shape(t)
B. t.shape()
C. t.size()
D. t.get_shape()

Solution

  1. Step 1: Recall PyTorch shape methods

    In PyTorch, t.size() returns the shape of the tensor as a tuple-like object.
  2. Step 2: Check other options

    t.shape is an attribute, not a method, so t.shape() is incorrect. shape(t) and t.get_shape() are not valid PyTorch syntax.
  3. Final Answer:

    t.size() -> Option C
  4. Quick Check:

    Use t.size() to get shape [OK]
Hint: Use t.size() method to get shape [OK]
Common Mistakes:
  • Calling t.shape() as a method
  • Using non-existent functions like shape(t)
  • Trying t.get_shape() which is invalid
3. What is the shape of the tensor created by torch.randn(3, 4, 5)?
medium
A. (3, 5, 4)
B. (3, 4, 5)
C. (5, 3, 4)
D. (4, 5, 3)

Solution

  1. Step 1: Understand torch.randn arguments

    The arguments (3, 4, 5) specify the size of each dimension in order: first dimension 3, second 4, third 5.
  2. Step 2: Confirm shape matches arguments

    The tensor shape matches exactly the arguments given, so the shape is (3, 4, 5).
  3. Final Answer:

    (3, 4, 5) -> Option B
  4. Quick Check:

    Shape matches input sizes (3,4,5) [OK]
Hint: Shape matches torch.randn arguments order [OK]
Common Mistakes:
  • Mixing up dimension order
  • Assuming shape is reversed
  • Confusing shape with total elements
4. Consider this code snippet:
import torch
t = torch.randn(2, 3)
print(t.shape())

What error will this code produce?
medium
A. TypeError: 'torch.Size' object is not callable
B. AttributeError: 'Tensor' object has no attribute 'shape'
C. SyntaxError: invalid syntax
D. No error, prints (2, 3)

Solution

  1. Step 1: Identify usage of t.shape()

    In PyTorch, t.shape is an attribute, not a method, so calling t.shape() tries to call a non-callable object.
  2. Step 2: Understand error type

    This causes a TypeError saying the 'torch.Size' object is not callable.
  3. Final Answer:

    TypeError: 'torch.Size' object is not callable -> Option A
  4. Quick Check:

    t.shape is attribute, not method [OK]
Hint: t.shape is attribute, don't add () [OK]
Common Mistakes:
  • Calling t.shape() instead of t.shape
  • Expecting no error from t.shape()
  • Confusing AttributeError with TypeError
5. You have a tensor x with shape (10, 5, 3). You want to reshape it to a 2D tensor with 5 rows and keep the total number of elements the same. Which of the following shapes is valid for the reshaped tensor?
hard
A. (5, 15)
B. (5, 10, 3)
C. (5, 5, 6)
D. (5, 30)

Solution

  1. Step 1: Calculate total elements in original tensor

    Original shape is (10, 5, 3), so total elements = 10 * 5 * 3 = 150.
  2. Step 2: Check which new shape keeps total elements and has 5 rows

    We want 5 rows, so first dimension = 5. The second dimension must satisfy 5 * ? = 150, so ? = 30. Check options:
    - A: (5, 15) -> 5*15=75 invalid total elements
    - B: (5, 10, 3) -> 5*10*3=150 valid but has 3 dims, not 2
    - C: (5, 30) -> 5*30=150 valid
    - D: (5, 5, 6) -> 5*5*6=150 valid but 3 dims
  3. Step 3: Confirm valid shape with 5 rows and total elements

    (5, 30) is (5, 30) which matches 5 rows and total elements 150. (5, 15) is incorrect because 5*15=75, less than 150.
  4. Final Answer:

    (5, 30) -> Option D
  5. Quick Check:

    5 * 30 = 150 elements [OK]
Hint: Total elements must stay same; multiply dims to check [OK]
Common Mistakes:
  • Ignoring total element count when reshaping
  • Choosing shape with wrong total elements
  • Confusing number of dimensions required
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard