快捷方式

torch.Tensor.scatter_reduce_

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

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

selfindexsrc 都应该具有相同的维度数。此外,要求对于所有维度 dindex.size(d) <= src.size(d);对于所有维度 d != dim,要求 index.size(d) <= self.size(d)。注意 indexsrc 不支持广播。

对于一个 3-D 张量,当 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.])

文档

查阅 PyTorch 全面的开发者文档

查看文档

教程

获取面向初学者和高级开发者的深度教程

查看教程

资源

查找开发资源并获得解答

查看资源