捷徑

torch.Tensor.scatter_add_

Tensor.scatter_add_(dim, index, src) Tensor

將 tensor src 中的所有值,依照 index tensor 指定的索引位置,加到 self 中,其方式與 scatter_() 類似。 對於 src 中的每個值,它會被加到 self 中,其索引由 src 中該值的索引所指定(當 dimension != dim 時),以及由 index 中對應的值所指定(當 dimension = dim 時)。

對於一個 3 維 tensor,self 會被更新如下:

self[index[i][j][k]][j][k] += src[i][j][k]  # if dim == 0
self[i][index[i][j][k]][k] += src[i][j][k]  # if dim == 1
self[i][j][index[i][j][k]] += src[i][j][k]  # if dim == 2

selfindexsrc 應該具有相同的維度數量。 另外,對於所有維度 d,必須滿足 index.size(d) <= src.size(d),並且對於所有維度 d != dim,必須滿足 index.size(d) <= self.size(d)。 請注意,indexsrc 不會進行廣播 (broadcast)。

注意

當給定 CUDA 裝置上的 tensors 時,此操作可能表現出不確定性。 請參閱 再現性 以獲取更多資訊。

注意

反向傳播 (backward pass) 僅針對 src.shape == index.shape 實現。

參數
  • dim (int) – 要索引的軸

  • index (LongTensor) – 要分散 (scatter) 和相加的元素的索引,可以是空的,也可以與 src 具有相同的維度。 當為空時,操作會傳回未更改的 self

  • src (Tensor) – 要分散 (scatter) 和相加的來源元素

範例

>>> src = torch.ones((2, 5))
>>> index = torch.tensor([[0, 1, 2, 0, 0]])
>>> torch.zeros(3, 5, dtype=src.dtype).scatter_add_(0, index, src)
tensor([[1., 0., 0., 1., 1.],
        [0., 1., 0., 0., 0.],
        [0., 0., 1., 0., 0.]])
>>> index = torch.tensor([[0, 1, 2, 0, 0], [0, 1, 2, 2, 2]])
>>> torch.zeros(3, 5, dtype=src.dtype).scatter_add_(0, index, src)
tensor([[2., 0., 0., 1., 1.],
        [0., 2., 0., 0., 0.],
        [0., 0., 2., 1., 1.]])

文件

Access comprehensive developer documentation for PyTorch

View Docs

Tutorials

Get in-depth tutorials for beginners and advanced developers

View Tutorials

Resources

Find development resources and get your questions answered

View Resources