Challenge - 5 Problems
Indexing and Slicing Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2: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)
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.
✗ Incorrect
The slice x[1:, :2] selects rows starting from index 1 (second row) to the end, and columns from index 0 up to 2 (first two columns). So it picks rows [[4,5,6],[7,8,9]] and columns [0,1], resulting in [[4,5],[7,8]].
❓ Model Choice
intermediate1: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?
Attempts:
2 left
💡 Hint
The first dimension is the batch size (number of images).
✗ Incorrect
The first dimension indexes images. data[:5] selects images from index 0 up to 5 (first 5 images). data[5:] selects images from index 5 to end. data[:, :5] selects all images but only first 5 channels (which is invalid since channels=3). data[0:5, 1] selects first 5 images but only channel 1, not the full image.
❓ Metrics
advanced1: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]`?
Attempts:
2 left
💡 Hint
Subtract start index from end index for each sliced dimension.
✗ Incorrect
For dimension 1: 4 to 10 means indices 4,5,6,7,8,9 → 6 elements. For dimension 2: 5 to 15 means indices 5 through 14 → 10 elements. The first dimension remains 8. So shape is (8, 6, 10).
🔧 Debug
advanced1: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]
Attempts:
2 left
💡 Hint
Check the size of dimension 1 and the index used.
✗ Incorrect
The tensor t has shape (4,5), so valid indices for dimension 1 are 0 to 4. Index 5 is out of bounds, causing IndexError.
🧠 Conceptual
expert2: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)
Attempts:
2 left
💡 Hint
Remember slicing with negative step goes backward, start index included, stop index excluded.
✗ Incorrect
x is [0,1,2,...,11]. Slicing x[10:2:-3] starts at index 10 (value 10), moves backward by 3 steps: indices 10,7,4. Values are 10,7,4.