快捷方式

torch.Tensor.index_add_

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

通过将 alpha 倍的 source 元素累加到 self 张量中,添加到 index 中给出的顺序的索引处。 例如,如果 dim == 0index[i] == j,且 alpha=-1,则从 self 的第 j 行中减去 source 的第 i 行。

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

对于 3-D 张量,输出给出为

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 的索引,应具有 dtype 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.]])

文档

访问 PyTorch 的全面开发者文档

查看文档

教程

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

查看教程

资源

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

查看资源