0
0
TensorFlowml~20 mins

Indexing and slicing tensors in TensorFlow - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Tensor Slicing Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
1: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)
A(2, 1)
B(1, 1)
C(1, 2)
D(2, 2)
Attempts:
2 left
💡 Hint
Remember that ':' means selecting all elements along that axis.
Model Choice
intermediate
1: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?
Atensor[:, 2:3]
Btensor[2, :]
Ctensor[:, 2]
Dtensor[2]
Attempts:
2 left
💡 Hint
Remember that the first index is for rows and the second for columns.
Hyperparameter
advanced
1: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]?
A(64, 28, 28, 3)
B(32, 28, 28, 3)
C(32, 28, 28)
D(28, 28, 3)
Attempts:
2 left
💡 Hint
Slicing with :32 selects the first 32 elements along the first dimension.
🔧 Debug
advanced
1: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)
AIndexError: index 3 is out of bounds for axis 1 with size 3
BTypeError: unsupported operand type(s) for slicing
CValueError: cannot slice tensor with ':'
DNo error, prints a tensor
Attempts:
2 left
💡 Hint
Check the size of the second dimension and the index used.
🧠 Conceptual
expert
2: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)
A[20 40]
B[20 30 40 50]
C[30 50]
D[10 30 50]
Attempts:
2 left
💡 Hint
Remember slicing syntax: start:stop:step selects elements from start up to but not including stop, stepping by step.