0
0
PyTorchml~10 mins

Reshaping (view, reshape, squeeze, unsqueeze) in PyTorch - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to reshape a tensor of shape (4, 3) into (2, 6) using PyTorch.

PyTorch
import torch
x = torch.randn(4, 3)
y = x.[1](2, 6)
print(y.shape)
Drag options to blanks, or click blank then click option'
Aview
Breshape
Csqueeze
Dunsqueeze
Attempts:
3 left
💡 Hint
Common Mistakes
Using squeeze or unsqueeze which add or remove dimensions instead of reshaping.
Using reshape without understanding the difference with view.
2fill in blank
medium

Complete the code to add a new dimension at position 1 to a tensor of shape (3, 4).

PyTorch
import torch
x = torch.randn(3, 4)
y = x.[1](1)
print(y.shape)
Drag options to blanks, or click blank then click option'
Aview
Bsqueeze
Cunsqueeze
Dreshape
Attempts:
3 left
💡 Hint
Common Mistakes
Using squeeze which removes dimensions instead of adding.
Using view or reshape which change shape but do not add singleton dimensions.
3fill in blank
hard

Fix the error in the code to remove all dimensions of size 1 from the tensor.

PyTorch
import torch
x = torch.randn(1, 3, 1, 5)
y = x.[1]()
print(y.shape)
Drag options to blanks, or click blank then click option'
Areshape
Bsqueeze
Cview
Dunsqueeze
Attempts:
3 left
💡 Hint
Common Mistakes
Using unsqueeze which adds dimensions instead of removing.
Using view or reshape which do not remove singleton dimensions automatically.
4fill in blank
hard

Fill both blanks to reshape a tensor and then add a new dimension at the end.

PyTorch
import torch
x = torch.randn(6, 4)
y = x.[1](3, 8).[2](-1)
print(y.shape)
Drag options to blanks, or click blank then click option'
Areshape
Bunsqueeze
Csqueeze
Dview
Attempts:
3 left
💡 Hint
Common Mistakes
Using squeeze instead of unsqueeze to add a dimension.
Using view instead of reshape which may fail if tensor is not contiguous.
5fill in blank
hard

Fill all three blanks to create a dictionary with keys as the tensor's dimension sizes and values as the dimension indices, but only for dimensions larger than 1.

PyTorch
import torch
x = torch.randn(1, 5, 1, 7)
result = {x.shape[[1]]: [2] for [3] in range(len(x.shape)) if x.shape[[1]] > 1}
print(result)
Drag options to blanks, or click blank then click option'
Ai
Dj
Attempts:
3 left
💡 Hint
Common Mistakes
Using different variables for indexing and looping causing errors.
Using a variable not defined in the loop.