How to use the torch.gather () function in Pytorch
This article will explain in detail how to use the torch.gather () function in Pytorch. The editor thinks it is very practical, so I share it with you as a reference. I hope you can get something after reading this article.
Parameter description
To take the official description as an example, the gather () function takes three parameters, input input, dimension dim, and index index
Input must be of type Tensor
Dim is an int type, which represents the dimension from which to index
Index is of type LongTensor
An example is given to illustrate that input=torch.tensor ([[1jue 2 input,dim=0,index=index1 3], [4je 5je 6]]) # is used as an input index1=torch.tensor ([[0je 1J 1], [0je 1J 1]]) # as an index matrix # dim=0, when indexing print (torch.gather (input,dim=0,index=index1)) # dim=1 by column, indexing print by row (torch.gather (input,dim=1,index=index1)
The result is shown in the following figure:
# indexing tensor by column ([[1,5,6], [4,2,6]) # indexing tensor ([[1,2,2], [5,4,5]]) by row
Official document
Def gather (self, input, dim, index, * args * * kwargs): For a 3murD tensor the output is specified by:: out [I] [j] [k] = input [index [I] [j] [k]] [j] [k] # if dim = = 0 out [I] [j] [k] = input [I] [index [I] [j] [k]] [k] # if dim = = 1 out [I] [j] [k] = input [I] [j] [index [I] [j] [k]] # if dim = = 2 Args: input (Tensor): the source tensor dim (int): the axis along which to index index (LongTensor): the indices of elements to gather Example:: > > t = torch.tensor ([[1] 2], [3,4]) > torch.gather (t, 1, torch.tensor ([[0,0], [1,0]])) tensor ([[1,1], [4,3]]) about "how to use the torch.gather () function in Pytorch" ends here Hope that the above content can be helpful to you, so that you can learn more knowledge, if you think the article is good, please share it for more people to see.