快捷键

torch.Tensor.scatter_

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

将张量 src 中的所有值写入到 self 中,索引由 index 张量指定。对于 src 中的每个值,其输出索引由其在 src 中的索引指定,以及由 dimension != dim 中的 index 对应的值指定。

对于一个三维张量, 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 参数,允许指定一个可选的降维操作,该操作应用于张量 src 中所有值,并在 index 指定的索引处将它们汇总到 self 。对于 src 中的每个值,降维操作应用于由其在 src 中的索引指定的 self 中的索引,以及由 index 中的对应值指定的 dimension = dim

给定一个三维张量以及乘法操作作为降维, 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(整数)- 指索引的轴

  • 索引(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 中的值写入 self ,索引由 index 张量指定。此操作与之前的版本等效,其中 src 张量完全填充了 value

参数:
  • dim(整数)- 指索引的轴

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

  • 值(标量)- 要散布的值。

关键字参数:

reduce(字符串,可选)- 要应用的重减操作,可以是 '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 贡献者。

使用 Sphinx 构建,并使用 Read the Docs 提供的主题。

文档

PyTorch 的全面开发者文档

查看文档

教程

深入了解初学者和高级开发者的教程

查看教程

资源

查找开发资源并获得您的疑问解答

查看资源