Tensor Index Slicing
Much like in Numpy arrays, accessing elements in a tensor is achieved through index slicing. The example below demonstrates how to access tensor values at their individual location.
import torch
x = torch.arange(15).reshape((3,5))
x
Accessing Individual Elements
To access individual value by position we pass the index location of the row and column indeces respectively. For
example, accessing the second row and third column, we pass the indeces
x[1, 2]
Accessing Entire Rows
Similarly, we can access an entire row or a subset of a row using the slicing
For example, the code below returns the third row of the tensor.
x[2, :]
Accessing Entire Columns
Conversely, we can access an entire column or a subset of a column using the slicing
For example, the code below returns the fourth row of the tensor.
x[:, 3]
index_select()
Torch has an
The code below generates a set of indeces in a tensor. We then select the subset of the tensor
indices = torch.tensor([1, 0])
indices
subset = torch.index_select(x, dim=0, index=indices)
subset