Tensor Slicing and Indexing
Problem Statement
Given a 2D tensor, extract specific rows, columns, and sub-matrices using PyTorch indexing.
Background
PyTorch tensors support NumPy-style indexing and slicing, allowing you to extract arbitrary parts of a tensor.
Your Task
Write a function extract_parts(tensor) that takes a 4×4 tensor and returns a dictionary with its first row, last column, and center 2×2 sub-matrix.
Output Format
Return a dictionary with keys: "first_row", "last_column", "center".
Example:
torch.arange(16).reshape(4, 4)
{"first_row": [0, 1, 2, 3], "last_column": [3, 7, 11, 15], "center": [[5, 6], [9, 10]]}Use tensor[0], tensor[:, -1], and tensor[1:3, 1:3] for slicing
Constraints:
- Input tensor is always 4x4
- Values are integers
- Return a dictionary with the three required keys
1. Background Knowledge
PyTorch tensors are multi-dimensional arrays similar to NumPy arrays, supporting advanced indexing and slicing operations that enable efficient data extraction without copying data (views are returned when possible). Key concepts include:
- Basic Indexing: tensor[i, j] accesses element at row i, column j.
- Slicing: Uses Python slice notation start:stop:step.
- Rows: tensor (first row), tensor[-1] (last row).
- Columns: tensor[:, -1] (last column, : selects all rows).
- Sub-matrices: tensor[row_slice, col_slice].
- Tensor Shape: For a 4×4 tensor, shape = (4, 4). Center 2×2 is rows/cols [1:3, 1:3] (indices 1,2).
- Views vs. Copies: Slicing creates views (zero-copy), preserving gradients for autograd.
These operations are O(1) for view creation, essential for memory-efficient ML pipelines.
2. Algorithm Approach
This problem uses direct indexing/slicing, a fundamental tensor operation in PyTorch (NumPy-compatible). No complex algorithms needed:
- First row: Single-index slice on dimension 0.
- Last column: Full slice on dim 0, single index on dim 1.
- Center sub-matrix: 2D slice on both dimensions.
For fixed-size (4×4) tensors, compute indices statically:
- Last column index: tensor.size(1) - 1.
- Center: (n//2-1): (n//2+1) where n=4.
3. Step-by-Step Strategy
- Inspect input: Confirm tensor.shape == (4, 4) (per constraints).
- Extract first row: first_row = tensor.
- Extract last column: last_col = tensor[:, -1] (or tensor[:, 3]).
- Extract center 2×2: center = tensor[1:3, 1:3].
- Package results: Return {"first_row": first_row, "last_column": last_col, "center": center}.
Complete Solution:
import torch
def extract_parts(tensor):
"""
Extract specific parts from a 4x4 tensor.
Args:
tensor: 4x4 PyTorch tensor
Continue the full explanation
You're reading the free preview. Unlock the complete walkthrough, the code editor, test runner and reference solution with Premium.
Editor locked
The code editor is locked for Pro problems. It is only available for free problems. Please upgrade to gain access to the code editor for all problems.