Introduction
Indexing and slicing let you pick parts of your data easily, like choosing pieces of a photo or words from a sentence.
Jump into concepts and practice - no test required
tensor[index] tensor[start:stop] tensor[start:stop:step] tensor[dim1_index, dim2_index, ...]
import tensorflow as tf x = tf.constant([10, 20, 30, 40, 50]) print(x[2])
x = tf.constant([10, 20, 30, 40, 50]) print(x[1:4])
x = tf.constant([[1, 2], [3, 4], [5, 6]]) print(x[1, 0])
x = tf.constant([10, 20, 30, 40, 50]) print(x[::-1])
import tensorflow as tf # Create a 2D tensor (3 rows, 4 columns) tensor = tf.constant([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]) # Get the element at row 0, column 2 elem = tensor[0, 2] # Slice rows 1 to 2 (inclusive start, exclusive end 3), columns 1 to 3 slice_part = tensor[1:3, 1:4] # Reverse the rows reversed_rows = tensor[::-1, :] print(f"Element at [0,2]: {elem.numpy()}") print("Slice rows 1-2, cols 1-3:") print(slice_part.numpy()) print("Tensor with rows reversed:") print(reversed_rows.numpy())
t from index 2 to 5 (exclusive) in TensorFlow?t[start:stop] to get elements from start up to but not including stop.t = tf.constant([[1, 2, 3], [4, 5, 6], [7, 8, 9]]), what is the output of t[1:, :2].numpy()?t[1:, :2]1: means rows from index 1 to end (rows 1 and 2). :2 means columns from start to index 2 (columns 0 and 1).t = tf.constant([10, 20, 30, 40, 50]) slice = t[1:6]
t has length 5, slicing 1:6 extracts elements from index 1 to end safely.t = tf.constant([[[1,2],[3,4]], [[5,6],[7,8]], [[9,10],[11,12]]]). How do you extract the second element from each 2D matrix (i.e., elements 2, 4, 6, 8, 10, 12) using indexing and slicing?t[:, :, 1] selects all matrices (:), all rows (:), and the second element (index 1) in the last dimension.