Introduction
Indexing and slicing help you pick parts of data from tensors easily, like choosing pieces from a big cake.
tensor[start:stop:step] tensor[index] tensor[start:stop] tensor[:, column_index] tensor[row_index, :]
x = torch.tensor([10, 20, 30, 40, 50]) print(x[1])
x = torch.tensor([10, 20, 30, 40, 50]) print(x[1:4])
x = torch.tensor([[1, 2, 3], [4, 5, 6]]) print(x[:, 1])
x = torch.tensor([[1, 2, 3], [4, 5, 6]]) print(x[0, :2])
import torch # Create a 2D tensor x = torch.tensor([[10, 20, 30], [40, 50, 60], [70, 80, 90]]) # Get the element at row 1, column 2 elem = x[1, 2] # Get the first row first_row = x[0, :] # Get the last column last_col = x[:, 2] # Get a sub-tensor of first two rows and first two columns sub_tensor = x[:2, :2] print(f"Element at (1, 2): {elem}") print(f"First row: {first_row}") print(f"Last column: {last_col}") print(f"Sub-tensor (2x2):\n{sub_tensor}")
tensor[2] do in PyTorch when tensor is a 1D tensor?[2] picks the element at position 2 (0-based index).tensor[2] returns the third element.t to get elements from index 1 to 4 (excluding 4)?start:stop inside square brackets to select elements from start index up to but not including stop index.t[1:4] uses correct slicing syntax t[1:4]. Options A, B, and C use invalid syntax for slicing.t = torch.tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]]), what is the output of t[1:, :2]?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).import torch t = torch.tensor([1, 2, 3, 4, 5]) print(t[::2, 1])
t is 1D with shape (5,). It has only one dimension.t[::2, 1] which tries to index two dimensions (rows and columns). This causes an error because t is 1D.t with shape (4, 5, 6). Which indexing expression extracts all elements from the second dimension at index 3, across all batches and features?: to select all in first and third dims, and 3 to select index 3 in second dim, so t[:, 3, :].Pass the test and this pattern moves unknown