评价此页

torch.Tensor.scatter_reduce_#

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

src张量中的所有值根据index张量指定的索引,在self张量中进行填充,并应用reduce参数定义的归约操作("sum""prod""mean""amax""amin")。对于src中的每个值,它被归约到self中的一个索引,该索引由其在src中的索引指定(对于dimension != dim),以及由index中的相应值指定(对于dimension = dim)。如果include_self="True",则self张量中的值也包含在归约中。

selfindexsrc 应该具有相同的维度数。此外,对于所有维度 d,要求 index.size(d) <= src.size(d),并且对于所有维度 d != dim,要求 index.size(d) <= self.size(d)。请注意,indexsrc 不会进行广播。

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

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

注意

当在 CUDA 设备上使用张量时,此操作可能行为不确定。有关更多信息,请参阅 随机性

注意

反向传播仅对 src.shape == index.shape 进行了实现。

警告

此功能处于 Beta 阶段,未来可能会发生更改。

参数
  • dim (int) – 要索引的轴

  • index (LongTensor) – 需要填充和归约的元素的索引。

  • src (Tensor) – 需要填充和归约的源元素

  • 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.])