0
0
PyTorchml~20 mins

Reshaping (view, reshape, squeeze, unsqueeze) in PyTorch - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Reshaping Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
What is the shape of tensor after view operation?
Given the following PyTorch code, what will be the shape of tensor `b` after the `view` operation?
PyTorch
import torch
a = torch.randn(2, 3, 4)
b = a.view(3, 8)
Atorch.Size([4, 6])
Btorch.Size([6, 4])
Ctorch.Size([2, 12])
Dtorch.Size([3, 8])
Attempts:
2 left
💡 Hint
Remember that view reshapes the tensor without changing the total number of elements.
Predict Output
intermediate
2:00remaining
What is the output shape after squeeze operation?
What will be the shape of tensor `b` after applying `squeeze` on tensor `a`?
PyTorch
import torch
a = torch.randn(1, 5, 1, 3)
b = a.squeeze()
Atorch.Size([5, 3])
Btorch.Size([1, 5, 3])
Ctorch.Size([5, 1, 3])
Dtorch.Size([1, 5, 1, 3])
Attempts:
2 left
💡 Hint
Squeeze removes all dimensions of size 1.
Model Choice
advanced
2:00remaining
Which operation correctly adds a new dimension at position 2?
You have a tensor `a` with shape (4, 5). Which PyTorch operation will add a new dimension at position 2 (0-based index), resulting in shape (4, 5, 1)?
PyTorch
import torch
a = torch.randn(4, 5)
Aa.unsqueeze(1)
Ba.unsqueeze(2)
Ca.unsqueeze(0)
Da.unsqueeze(-2)
Attempts:
2 left
💡 Hint
Remember that unsqueeze adds a dimension at the specified index.
Hyperparameter
advanced
2:00remaining
Choosing correct reshape parameters for a tensor
You have a tensor `a` with shape (2, 3, 4). You want to reshape it to a 2D tensor with 6 rows. Which of the following reshape calls achieves this without raising an error?
PyTorch
import torch
a = torch.randn(2, 3, 4)
Aa.reshape(3, 8)
Ba.reshape(4, 6)
Ca.reshape(6, -1)
Da.reshape(6, 5)
Attempts:
2 left
💡 Hint
The total number of elements must remain the same after reshape. Use -1 to infer a dimension.
🔧 Debug
expert
2:00remaining
Why does this reshape code raise an error?
Consider the following code snippet. Why does it raise an error?
PyTorch
import torch
a = torch.randn(2, 3, 4)
b = a.view(4, 3, 3)
AThe total number of elements does not match between original and new shape.
Bview cannot change the order of dimensions, only reshape.
CThe new shape must have a dimension of size 1.
Dview requires the tensor to be contiguous, and this tensor is not.
Attempts:
2 left
💡 Hint
Check the total number of elements in both shapes.