快捷方式

torch.Tensor.scatter_add_

Tensor.scatter_add_(dim, index, src) Tensor

以类似于 scatter_() 的方式,将张量 src 中的所有值加到 self 中,索引由 index 张量指定。对于 src 中的每个值,它都会被添加到 self 中的一个索引,该索引由其在 src 中的索引指定(当维度 != dim 时),以及由 index 中对应的值指定(当维度 = dim 时)。

对于 3-D 张量,self 的更新方式如下

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

selfindexsrc 应具有相同的维度数。还需要 index.size(d) <= src.size(d) 对所有维度 d 成立,以及 index.size(d) <= self.size(d) 对所有维度 d != dim 成立。请注意,indexsrc 不进行广播。

注意

当在 CUDA 设备上给定张量时,此操作可能表现出非确定性行为。有关更多信息,请参阅 可重复性

注意

反向传播仅针对 src.shape == index.shape 实现。

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

  • index (LongTensor) – 要分散和添加的元素的索引,可以为空或与 src 具有相同的维度。当为空时,操作返回未更改的 self

  • src (Tensor) – 要分散和添加的源元素

示例

>>> src = torch.ones((2, 5))
>>> index = torch.tensor([[0, 1, 2, 0, 0]])
>>> torch.zeros(3, 5, dtype=src.dtype).scatter_add_(0, index, src)
tensor([[1., 0., 0., 1., 1.],
        [0., 1., 0., 0., 0.],
        [0., 0., 1., 0., 0.]])
>>> index = torch.tensor([[0, 1, 2, 0, 0], [0, 1, 2, 2, 2]])
>>> torch.zeros(3, 5, dtype=src.dtype).scatter_add_(0, index, src)
tensor([[2., 0., 0., 1., 1.],
        [0., 2., 0., 0., 0.],
        [0., 0., 2., 1., 1.]])

文档

访问 PyTorch 的全面开发者文档

查看文档

教程

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

查看教程

资源

查找开发资源并获得问题解答

查看资源