0
0
PyTorchml~20 mins

Indexing and slicing in PyTorch - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Indexing and Slicing Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of slicing a 2D tensor
What is the output of the following PyTorch code snippet?
PyTorch
import torch
x = torch.tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
result = x[1:, :2]
print(result)
Atensor([[4, 5], [7, 8]])
Btensor([[5, 6], [8, 9]])
Ctensor([[1, 2], [4, 5]])
Dtensor([[2, 3], [5, 6]])
Attempts:
2 left
💡 Hint
Remember that x[1:, :2] means rows from index 1 to end, columns from index 0 up to but not including 2.
Model Choice
intermediate
1:30remaining
Choosing correct indexing for batch selection
You have a tensor `data` of shape (10, 3, 28, 28) representing 10 images with 3 color channels and 28x28 pixels. Which indexing expression correctly selects the first 5 images?
Adata[5:]
Bdata[:5]
Cdata[:, :5]
Ddata[0:5, 1]
Attempts:
2 left
💡 Hint
The first dimension is the batch size (number of images).
Metrics
advanced
1:30remaining
Effect of slicing on tensor shape
Given a tensor `t` of shape (8, 16, 32), what is the shape of `t[:, 4:10, 5:15]`?
A(8, 6, 10)
B(8, 6, 9)
C(8, 5, 10)
D(8, 7, 10)
Attempts:
2 left
💡 Hint
Subtract start index from end index for each sliced dimension.
🔧 Debug
advanced
1:30remaining
Identify the error in tensor indexing
What error does the following PyTorch code raise?
PyTorch
import torch
t = torch.randn(4, 5)
result = t[1:3, 5]
ANo error, returns a tensor
BTypeError: only integers, slices (`:`), ellipsis (`...`), None and long or byte Variables are valid indices
CValueError: too many indices for tensor of dimension 2
DIndexError: index 5 is out of bounds for dimension 1 with size 5
Attempts:
2 left
💡 Hint
Check the size of dimension 1 and the index used.
🧠 Conceptual
expert
2:30remaining
Understanding advanced slicing with steps
Given a tensor `x` of shape (12,), what is the output of `x[10:2:-3]`?
PyTorch
import torch
x = torch.arange(12)
result = x[10:2:-3]
print(result)
Atensor([10, 7, 1])
Btensor([10, 8, 5])
Ctensor([10, 7, 4])
Dtensor([10, 7, 3])
Attempts:
2 left
💡 Hint
Remember slicing with negative step goes backward, start index included, stop index excluded.