torch.Tensor.scatter_reduce_

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

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

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

对于一个具有 reduce="sum"include_self=True 属性的3-D张量,其输出为:

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时,才实施反向传播。

警告

此功能尚处测试阶段,未来可能有所更改。

参数
  • 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.])
本页目录