torch.Tensor.scatter_

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

将张量 src 中的所有值写入 self,位置由 index 张量指定。对于 src 中的每个值,其输出索引在维度不等于 dim 时由 src 中该值的位置确定,在维度等于 dim 时由 index 张量中的对应值确定。

对于一个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(如果它是张量)必须具有相同的维度数量。此外,对于所有维度 d,需要满足 index.size(d) <= src.size(d),并且对于所有维度 d != dim,需要满足 index.size(d) <= self.size(d)。需要注意的是,indexsrc 不会进行广播操作。

此外,对于gather()而言,index的值必须在0self.size(dim) - 1之间(包括边界)。

警告

当索引不唯一时,行为是不确定的(会从src中随机选择一个值),而且计算出的梯度也是错误的(它会被传播到源中所有对应相同索引的位置)!

注意

只有当src.shape == index.shape时,才实施反向传播。

此外,还接受一个可选的 reduce 参数,该参数允许指定一个可选的缩减操作。此操作应用于张量 src 中的所有值,并将结果合并到 self 中由 index 指定的位置。对于 src 中的每个值,缩减操作会应用到 self 中的一个索引:该索引由 src 中对应的索引指定(当 dimension != dim),或者由 index 中相应的值指定(当 dimension = dim)。

当给定一个3-D张量并使用乘法操作进行缩减时,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) – 元素要散列的索引,可以为空或与src具有相同的维度。如果为空,则操作返回不变的self

  • src (Tensor) – 需要进行散列操作的源张量。

关键字参数

reduce (str, 可选) – 化简操作,可以是 '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的值写入selfindex张量中指定的位置。此操作等同于之前的版本,其中src张量完全填充为value

参数
  • dim (int) - 需要进行索引的轴

  • index (LongTensor) – 元素要散列的索引,可以为空或与src具有相同的维度。如果为空,则操作返回不变的self

  • value (标量) - 需要散列的值。

关键字参数

reduce (str, 可选) – 化简操作,可以是 '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.]])
本页目录