Challenge - 5 Problems
Tensor Slicing Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate1:30remaining
Output of slicing a 3D tensor
What is the output shape of the tensor after slicing in the code below?
TensorFlow
import tensorflow as tf x = tf.constant([[[1, 2], [3, 4]], [[5, 6], [7, 8]]]) sliced = x[:, 1, :] print(sliced.shape)
Attempts:
2 left
💡 Hint
Remember that ':' means selecting all elements along that axis.
✗ Incorrect
The original tensor x has shape (2, 2, 2). The slice x[:, 1, :] selects all elements in the first dimension, the second element (index 1) in the second dimension, and all elements in the third dimension. This results in a tensor of shape (2, 2).
❓ Model Choice
intermediate1:30remaining
Choosing correct slicing for extracting a column vector
Given a 2D tensor of shape (5, 4), which slicing extracts the third column as a 1D tensor?
Attempts:
2 left
💡 Hint
Remember that the first index is for rows and the second for columns.
✗ Incorrect
tensor[:, 2] selects all rows and the third column (index 2), resulting in a 1D tensor of shape (5,). tensor[:, 2:3] would keep the dimension and return shape (5, 1).
❓ Hyperparameter
advanced1:30remaining
Effect of slicing on batch size in training data
If you have a tensor representing a batch of images with shape (64, 28, 28, 3), what is the shape after slicing with tensor[:32]?
Attempts:
2 left
💡 Hint
Slicing with :32 selects the first 32 elements along the first dimension.
✗ Incorrect
The first dimension is the batch size. Slicing tensor[:32] selects the first 32 images, keeping the rest of the dimensions unchanged.
🔧 Debug
advanced1:30remaining
Identify the error in tensor slicing code
What error does the following code produce?
import tensorflow as tf
x = tf.constant([[1, 2, 3], [4, 5, 6]])
slice = x[:, 3]
print(slice)
TensorFlow
import tensorflow as tf x = tf.constant([[1, 2, 3], [4, 5, 6]]) slice = x[:, 3] print(slice)
Attempts:
2 left
💡 Hint
Check the size of the second dimension and the index used.
✗ Incorrect
The tensor has shape (2, 3), so valid column indices are 0, 1, 2. Index 3 is out of bounds, causing an IndexError.
🧠 Conceptual
expert2:00remaining
Understanding advanced tensor slicing with steps
Given a 1D tensor x = tf.constant([10, 20, 30, 40, 50, 60]), what is the output of x[1:5:2].numpy()?
TensorFlow
import tensorflow as tf x = tf.constant([10, 20, 30, 40, 50, 60]) result = x[1:5:2].numpy() print(result)
Attempts:
2 left
💡 Hint
Remember slicing syntax: start:stop:step selects elements from start up to but not including stop, stepping by step.
✗ Incorrect
x[1:5:2] selects elements at indices 1 and 3 (20 and 40).