評價此頁

torch.Tensor.index_add_#

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

累加 alphasource 的元素到 self 張量中,透過按照 index 中給定的順序進行索引相加。例如,如果 dim == 0index[i] == j,並且 alpha=-1,那麼 source 的第 i 行將被減去 self 的第 j 行。

sourcedim 維的大小必須與 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 中選擇的索引,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.]])