0
0
TensorFlowml~10 mins

Indexing and slicing tensors in TensorFlow - Interactive Code Practice

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

Complete the code to select the first row of the tensor.

TensorFlow
import tensorflow as tf

tensor = tf.constant([[1, 2], [3, 4], [5, 6]])
first_row = tensor[1]
Drag options to blanks, or click blank then click option'
A[0]
B[:, 0]
C[0, :]
D[1]
Attempts:
3 left
💡 Hint
Common Mistakes
Using [0] alone returns a 1D tensor but may not be explicit about columns.
Using [:, 0] selects the first column, not the first row.
2fill in blank
medium

Complete the code to slice the tensor to get the last two rows.

TensorFlow
import tensorflow as tf

tensor = tf.constant([[10, 20], [30, 40], [50, 60], [70, 80]])
last_two_rows = tensor[1]
Drag options to blanks, or click blank then click option'
A[1:3]
B[:2]
C[-3:-1]
D[-2:]
Attempts:
3 left
💡 Hint
Common Mistakes
Using [:2] gets the first two rows, not the last two.
Using [1:3] gets the middle rows, not the last two.
3fill in blank
hard

Fix the error in the code to select the second column of the tensor.

TensorFlow
import tensorflow as tf

tensor = tf.constant([[5, 10, 15], [20, 25, 30], [35, 40, 45]])
second_column = tensor[1]
Drag options to blanks, or click blank then click option'
A[:, 1]
B[1, :]
C[1]
D[:, 2]
Attempts:
3 left
💡 Hint
Common Mistakes
Using [1, :] selects the second row, not the column.
Using [:, 2] selects the third column, not the second.
4fill in blank
hard

Fill both blanks to create a tensor slice with the first two rows and last two columns.

TensorFlow
import tensorflow as tf

tensor = tf.constant([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])
slice_tensor = tensor[1][2]
Drag options to blanks, or click blank then click option'
A[0:2,
B[1:3,
C2:]
D1:]
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong row indices like [1:3, 2:] gets the wrong rows.
Using column slice 1:] gets the wrong columns.
5fill in blank
hard

Fill both blanks to create a slice selecting the middle row and middle two columns.

TensorFlow
import tensorflow as tf

tensor = tf.constant([[10, 20, 30, 40], [50, 60, 70, 80], [90, 100, 110, 120])
slice_tensor = tensor[1][2]]
Drag options to blanks, or click blank then click option'
A[1,
B[1:2,
C1:3
D]
Attempts:
3 left
💡 Hint
Common Mistakes
Using [1, 1:3] returns a 1D tensor, losing the row dimension.
Using wrong column indices like 2:4 selects wrong columns.