Per-position tensor lookup
Select per-row or per-batch positions from a tensor when each output position has its own index.
PyTorch · Function
torch.gather selects values from input along a chosen dimension using an index tensor. The result has the same shape as index.
torch.gather selects elements from input along dim using the positions supplied by index. The result has index's shape, and selection occurs independently at each coordinate outside the chosen dimension.
torch.gather(input, dim, index, *, sparse_grad=False, out=None) → Tensor| Name | Type | Description |
|---|---|---|
input | Tensor | Source tensor containing the values to select. |
dim | int | Axis along which selection occurs. |
index | LongTensor | Tensor containing element indices. |
sparse_grad | bool, optional | If true, the gradient with respect to input is sparse. |
out | Tensor, optional | Destination tensor for the result. |
A Tensor containing the gathered values; its shape is the same as index.
import torch
t = torch.tensor([[1, 2], [3, 4]])
index = torch.tensor([[0, 0], [1, 0]])
result = torch.gather(t, 1, index)
print(result)
# tensor([[1, 1],
# [4, 3]])The index tensor selects values along dimension 1, producing one output value for every index entry.
Select per-row or per-batch positions from a tensor when each output position has its own index.
Choose action or class values using indices generated by another operation.
Request sparse input gradients when dense gradients are undesirable.
torch.gather takes input, an axis dim, and a LongTensor index. It returns values selected along that axis, with the output shaped like index.
Follow-up: How do input and index interact in shape checking? They must have the same number of dimensions, and index sizes cannot exceed input sizes in dimensions other than dim.
For a three-dimensional input, dim determines which coordinate is replaced by the corresponding index coordinate. For example, with dim equal to 1, the middle coordinate comes from index.
Follow-up: What shape does the result have? It always has the same shape as index, rather than necessarily preserving input's shape.
sparse_grad=True requests a sparse gradient with respect to input. The option is a keyword argument and defaults to False.
Follow-up: What other optional keyword argument is documented? out specifies a destination tensor for the result.
torch.scattertorch.index_select