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 行中减去。

代码中的 source 的第 dim 维度大小必须与 index(必须是向量)的长度相同,同时其他所有维度必须与 self 匹配,否则会引发错误。

对于一个3D张量,其输出形式为:

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

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