評價此頁

torch.Tensor.scatter_reduce_#

Tensor.scatter_reduce_(dim, index, src, reduce, *, include_self=True) Tensor#

src 張量中的所有值,透過 reduce 引數定義的規約操作("sum", "prod", "mean", "amax", "amin"),規約到 self 張量中由 index 張量指定的索引位置。對於 src 中的每個值,它將被規約到 self 中的一個索引,該索引由其在 src 中的索引(對於 dimension != dim)和 index 中的對應值(對於 dimension = dim)指定。如果 include_self="True",則 self 張量中的值也將被包含在規約中。

selfindexsrc 都應具有相同的維度數。此外,對於所有維度 d,需要滿足 index.size(d) <= src.size(d),並且對於所有維度 d != dim,需要滿足 index.size(d) <= self.size(d)。請注意,indexsrc 不支援廣播。

對於一個 3D 張量,當 reduce="sum"include_self=True 時,輸出如下所示:

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

注意

當在 CUDA 裝置上使用張量時,此操作可能行為不確定。有關更多資訊,請參閱 隨機性

注意

反向傳播僅對 src.shape == index.shape 進行了實現。

警告

此函式處於 beta 階段,未來可能會發生更改。

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

  • index (LongTensor) – 要散佈和規約的元素的索引。

  • src (Tensor) – 要散佈和規約的源元素

  • reduce (str) – 應用於非唯一索引的規約操作("sum", "prod", "mean", "amax", "amin"

  • include_self (bool) – self 張量中的元素是否包含在規約中

示例

>>> src = torch.tensor([1., 2., 3., 4., 5., 6.])
>>> index = torch.tensor([0, 1, 0, 1, 2, 1])
>>> input = torch.tensor([1., 2., 3., 4.])
>>> input.scatter_reduce(0, index, src, reduce="sum")
tensor([5., 14., 8., 4.])
>>> input.scatter_reduce(0, index, src, reduce="sum", include_self=False)
tensor([4., 12., 5., 4.])
>>> input2 = torch.tensor([5., 4., 3., 2.])
>>> input2.scatter_reduce(0, index, src, reduce="amax")
tensor([5., 6., 5., 2.])
>>> input2.scatter_reduce(0, index, src, reduce="amax", include_self=False)
tensor([3., 6., 5., 2.])