Shortcuts

torch.Tensor.scatter_add_

Tensor.scatter_add_(dim, index, src) 张量

将张量 src 中的所有值添加到 self 中,索引由 index 张量指定,类似于 scatter_()。对于 src 中的每个值,它被添加到 self 中的一个索引,该索引由 src 中的索引指定 对于 dimension != dim,并且由 index 中的相应值指定 对于 dimension = dim

对于一个3维张量,self 被更新为:

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

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

注意

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

注意

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

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

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

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

示例:

>>> 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.]])
优云智算