评价此页

torch.Tensor.index_add_#

Tensor.index_add_(dim, index, source, *, alpha=1) Tensor#

alpha 乘以 source 的元素,并按照 index 中给出的顺序,累加到 self 张量中。例如,如果 dim == 0index[i] == j,且 alpha=-1,则 source 的第 i 行将被减去 self 的第 j 行。

sourcedim 维的大小必须与 index 的长度(必须是一个向量)相同,并且所有其他维度必须与 self 匹配,否则会引发错误。

对于一个 3 维张量,输出如下

self[index[i], :, :] += alpha * src[i, :, :]  # if dim == 0
self[:, index[i], :] += alpha * src[:, i, :]  # if dim == 1
self[:, :, index[i]] += alpha * src[:, :, i]  # if dim == 2

注意

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

参数
  • dim (int) – 索引的维度

  • index (Tensor) – 从中选择 source 的索引,应具有 torch.int64torch.int32 的 dtype

  • source (Tensor) – 包含要添加的值的张量

关键字参数

alpha (Number) – source 的标量乘数

示例

>>> x = torch.ones(5, 3)
>>> t = torch.tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]], dtype=torch.float)
>>> index = torch.tensor([0, 4, 2])
>>> x.index_add_(0, index, t)
tensor([[  2.,   3.,   4.],
        [  1.,   1.,   1.],
        [  8.,   9.,  10.],
        [  1.,   1.,   1.],
        [  5.,   6.,   7.]])
>>> x.index_add_(0, index, t, alpha=-1)
tensor([[  1.,   1.,   1.],
        [  1.,   1.,   1.],
        [  1.,   1.,   1.],
        [  1.,   1.,   1.],
        [  1.,   1.,   1.]])