Shortcuts

torch.Tensor.scatter_reduce_

Tensor.scatter_reduce_(dim, index, src, reduce, *, include_self=True) 张量

src张量中的所有值减少到self张量中在index张量中指定的索引,使用通过reduce参数定义的减少操作("sum""prod""mean""amax""amin")。对于src中的每个值,它被减少到self中的一个索引,该索引由其在src中的索引指定,对于dimension != dim,并且由index中的相应值指定,对于dimension = dim。如果include_self="True",则self张量中的值将包含在减少操作中。

self, indexsrc 应该都有相同的维度数量。还要求对于所有维度 dindex.size(d) <= src.size(d),并且对于所有维度 d != dimindex.size(d) <= self.size(d)。 注意 indexsrc 不会进行广播。

对于一个3维张量,当reduce="sum"include_self=True 时,输出如下:

self[index[i][j][k]][j][k] += src[i][j][k]  # 如果 dim == 0
self[i][index[i][j][k]][k] += src[i][j][k]  # 如果 dim == 1
self[i][j][index[i][j][k]] += src[i][j][k]  # 如果 dim == 2

注意

当在CUDA设备上使用张量时,此操作可能会表现出不确定性行为。更多信息请参见可重复性

注意

反向传播仅在 src.shape == index.shape 时实现。

警告

此功能目前处于测试阶段,可能会在不久的将来进行更改。

Parameters
  • dim (int) – 要沿其索引的轴

  • 索引 (LongTensor) – 要分散和减少的元素的索引。

  • src (张量) – 要分散和减少的源元素

  • reduce (str) – 应用于非唯一索引的归约操作 ("sum", "prod", "mean", "amax", "amin")

  • include_self (bool) – 是否将self张量中的元素包含在归约中

示例:

>>> src = torch.tensor([1., 2., 3., 4., 5., 6.])
>>> index = torch.tensor([0, 1, 0, 1, 2, 1])
>>> input = torch.tensor([1., 2., 3., 4.])
>>> input.scatter_reduce(0, index, src, reduce="sum")
tensor([5., 14., 8., 4.])
>>> input.scatter_reduce(0, index, src, reduce="sum", include_self=False)
tensor([4., 12., 5., 4.])
>>> input2 = torch.tensor([5., 4., 3., 2.])
>>> input2.scatter_reduce(0, index, src, reduce="amax")
tensor([5., 6., 5., 2.])
>>> input2.scatter_reduce(0, index, src, reduce="amax", include_self=False)
tensor([3., 6., 5., 2.])
优云智算