## Gather() function in Python

Wooden calyx 2020-11-13 08:47:21
gather function python

First , Give links to official documents ：

https://pytorch.org/docs/stable/generated/torch.gather.html?highlight=gather#torch.gather

then , I translate the official documents in vernacular .

gather, seeing the name of a thing one thinks of its function , Gather 、 aggregate . It's a bit like military training , It's like waiting in line , Arrange the team in the order the instructor wants .

There is a more appropriate metaphor ：gather Its function is based on Indexes lookup , Then, the search results are returned in the form of tensor matrix .

### 1. Take a tensor ：

``````import torch
a = torch.arange(15).view(3, 5)
``````

a = tensor([

[ 0,  1,  2,  3,  4],
[ 5,  6,  7,  8,  9],
[10, 11, 12, 13, 14]])

### 2. Generate a search rule ：

( tensor b The elements of are all corresponding tensors a The index of )

``````b = torch.zeros_like(a)
b = 1
b = 1``````

b = tensor(

[[1, 0, 0, 0, 0],
[0, 0, 1, 0, 0],
[0, 0, 0, 0, 0]])

### 3. According to dimensions dim Start looking for ：

``````c = a.gather(0, b) # dim=0
d = a.gather(1, b) # dim=1``````

c= tensor([

[5, 1, 2, 3, 4],
[0, 1, 7, 3, 4],
[0, 1, 2, 3, 4]])

d=tensor([

[ 1,  0,  0,  0,  0],
[ 5,  5,  6,  5,  5],
[10, 10, 10, 10, 10]])

ok, It's going to be a bit hard to see here .

If dim=0, be b be relative to a, It's stored in sections 0 Index of dimensions ;

If dim=1, be b be relative to a, It's stored in sections 1 Index of dimensions ;

I'll give you a chestnut , When dim=0 when ,b The element is 1, So it wants to find a The elements in ;

When dim=1 when ,b The element is 1, So what it's looking for a The elements in ;

The final output can be seen as a response to a Query for , namely The elements are a The elements in , Query indexes exist b in . Output size and b Agreement .

Find a graph to describe , there index Corresponding b,src Corresponding a, All the numbers in the grid are minus 1, The left figure corresponds to dim=0, The picture on the right corresponds to dim=1. 