快捷方式

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 的全面开发者文档

查看文档

教程

获取面向初学者和高级开发者的深入教程

查看教程

资源

查找开发资源并获得问题解答

查看资源