評價此頁

torch.Tensor.scatter_#

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

src 張量中的所有值寫入 self 中,索引由 index 張量指定。對於 src 中的每個值,其輸出索引由其在 src 中的索引(對於 dimension != dim)和 index 中的相應值(對於 dimension = dim)指定。

對於一個 3 維張量,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() 方法所述操作的逆過程。

同時要求 index.size(d) <= src.size(d) 對於所有維度 d,以及 index.size(d) <= self.size(d) 對於所有維度 d != dim。請注意,對於 NPU,inputindex 不會相互廣播,因此在 NPU 上執行時,inputindex 必須具有相同數量的維度。在所有其他情況下,會發生標準廣播。

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

警告

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

注意

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

此外,它還接受一個可選的 reduce 引數,該引數允許指定一個可選的歸約操作,該操作將應用於 src 張量中的所有值,寫入 self 中由 index 指定的索引處。對於 src 中的每個值,歸約操作將應用於 self 中的一個索引,該索引由其在 src 中的索引(對於 dimension != dim)和 index 中的相應值(對於 dimension = dim)指定。

給定一個 3 維張量並使用乘法進行歸約,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_()

警告

帶有張量 srcreduce 引數已被棄用,並將在未來的 PyTorch 版本中移除。請使用 scatter_reduce_() 以獲得更多歸約選項。

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

  • index (LongTensor) – 要散佈的元素的索引,可以是空的,也可以與 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) – 要散佈的元素的索引,可以是空的,也可以與 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.]])