I can't understand if torch.scatter
or torch.gather
could be used to reduce values of a tensor according to a reduction function over specified indices.
I've frequently used the torch_geometric.nn.aggr
` module's functions in order to perform aggregations over indices, and I want to reproduce these very useful functions using pure PyTorch operations.
I can't understand if torch.scatter
or torch.gather
could be used to reduce values of a tensor according to a reduction function over specified indices.
I've frequently used the torch_geometric.nn.aggr
` module's functions in order to perform aggregations over indices, and I want to reproduce these very useful functions using pure PyTorch operations.
1 Answer
Reset to default 1you could use the function scatter_reduce_ (is in beta): https://pytorch./docs/stable/generated/torch.Tensor.scatter_reduce_.html
however you have to specify an out tensor (which should have desired shape and initial values):
e.g. for sum aggregation:
out = torch.zeros((index.max() + 1.), dtype=torch.float)
out.scatter_reduce_(dim=0, index=index, src=x, reduce="sum")
or min aggregation:
out = torch.full((index.max() + 1,), torch.inf)
out.scatter_reduce_(dim=0, index=index, src=x, reduce="amin")