捷徑

torch.Tensor.index_add_

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

alpha 乘以 source 的元素,按照 index 中給定的順序,累加到 self 張量的索引中。例如,如果 dim == 0, index[i] == j,且 alpha=-1,那麼 source 的第 i 列會從 self 的第 j 列中減去。

dimth 維度的 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 的完整開發者文件

檢視文件

教學

取得針對初學者和進階開發者的深入教學

檢視教學

資源

尋找開發資源並取得您問題的解答

檢視資源