Skip to main content

Posts

Featured

Selecting Elements from a Tensor

Selecting Elements from a Tensor in PyTorch In PyTorch, selecting elements from a tensor works a lot like slicing arrays in NumPy—but with a few extra tricks. Whether you need a single value, a whole row/column, or specific elements based on conditions, PyTorch has you covered. 1. Selecting with Indexing ( [] ) If you’ve used NumPy before, this will feel familiar. Let’s say we have a 2D tensor: import torch tensor = torch.tensor([ [10, 20, 30], [40, 50, 60], [70, 80, 90] ]) print(tensor[2, 1]) # Single value → 80 print(tensor[:, 1]) # Second column → tensor([20, 50, 80]) print(tensor[1, :]) # Second row → tensor([40, 50, 60]) For higher dimensions, the logic is the same: tensor[:, 2, :] # Select all rows, 3rd column, all depth slices 2. Selecting with index_select Sometimes, you want to grab specific rows or columns by index. That’s where index_select comes in. a = torch.tensor([[1, 2], [3, 4], [5, 6]]) # Indices must be a LongTensor indices = torch.t...

Latest Posts

Tensor Types

Tensorflow Metadata