快捷方式

torch.Tensor.scatter_

Tensor.scatter_(dim, index, src, *, reduce=None) Tensor

將張量 src 中的所有值寫入到張量 self 中由 index 張量指定的索引位置。對於 src 中的每個值,其輸出索引由其在 src 中(對於 dimension != dim 的維度)的索引以及在 index 中(對於 dimension = dim 的維度)的對應值指定。

對於一個 3D 張量,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

這與 gather() 中描述的操作方式相反。

selfindexsrc(如果它是張量)應具有相同的維度數。此外,要求對於所有維度 dindex.size(d) <= src.size(d);對於所有維度 d != dimindex.size(d) <= self.size(d)。請注意,indexsrc 不會進行廣播。

此外,與 gather() 一樣,index 中的值必須在 0self.size(dim) - 1(包含)之間。

警告

當索引不唯一時,行為是非確定性的(將任意選擇 src 中的一個值),並且梯度將是不正確的(它將傳播到源中對應於相同索引的所有位置)!

注意

反向傳播僅在 src.shape == index.shape 時實現。

此外,接受一個可選的 reduce 引數,該引數允許指定一個可選的歸約(reduction)操作,該操作應用於張量 src 中的所有值,並將結果放入 self 中由 index 指定的索引位置。對於 src 中的每個值,歸約操作應用於 self 中的一個索引,該索引由其在 src 中(對於 dimension != dim 的維度)的索引以及在 index 中(對於 dimension = dim 的維度)的對應值指定。

給定一個 3D 張量並使用乘法操作進行歸約,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

使用加法操作進行歸約與使用 scatter_add_() 相同。

警告

使用 Tensor src 的 reduce 引數已被棄用,並將在未來的 PyTorch 版本中移除。請改用 scatter_reduce_() 以獲得更多歸約選項。

引數
  • dim (int) – 指定索引軸

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

  • src (Tensor) – 要分散的源元素。

關鍵字引數

reduce (str, optional) – 要應用的歸約操作,可以是 'add'(加法)或 'multiply'(乘法)。

示例

>>> src = torch.arange(1, 11).reshape((2, 5))
>>> src
tensor([[ 1,  2,  3,  4,  5],
        [ 6,  7,  8,  9, 10]])
>>> index = torch.tensor([[0, 1, 2, 0]])
>>> torch.zeros(3, 5, dtype=src.dtype).scatter_(0, index, src)
tensor([[1, 0, 0, 4, 0],
        [0, 2, 0, 0, 0],
        [0, 0, 3, 0, 0]])
>>> index = torch.tensor([[0, 1, 2], [0, 1, 4]])
>>> torch.zeros(3, 5, dtype=src.dtype).scatter_(1, index, src)
tensor([[1, 2, 3, 0, 0],
        [6, 7, 0, 0, 8],
        [0, 0, 0, 0, 0]])

>>> torch.full((2, 4), 2.).scatter_(1, torch.tensor([[2], [3]]),
...            1.23, reduce='multiply')
tensor([[2.0000, 2.0000, 2.4600, 2.0000],
        [2.0000, 2.0000, 2.0000, 2.4600]])
>>> torch.full((2, 4), 2.).scatter_(1, torch.tensor([[2], [3]]),
...            1.23, reduce='add')
tensor([[2.0000, 2.0000, 3.2300, 2.0000],
        [2.0000, 2.0000, 2.0000, 3.2300]])
scatter_(dim, index, value, *, reduce=None) Tensor:

value 中的值寫入到 self 中由 index 張量指定的索引位置。此操作等效於上一個版本,但 src 張量完全填充了 value

引數
  • dim (int) – 指定索引軸

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

  • value (Scalar) – 要分散的值。

關鍵字引數

reduce (str, optional) – 要應用的歸約操作,可以是 'add'(加法)或 'multiply'(乘法)。

示例

>>> index = torch.tensor([[0, 1]])
>>> value = 2
>>> torch.zeros(3, 5).scatter_(0, index, value)
tensor([[2., 0., 0., 0., 0.],
        [0., 2., 0., 0., 0.],
        [0., 0., 0., 0., 0.]])

文件

查閱 PyTorch 的全面開發者文件

檢視文件

教程

獲取面向初學者和高階開發者的深入教程

檢視教程

資源

查詢開發資源並獲得問題解答

檢視資源