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()
中描述的操作方式相反。self
、index
和src
(如果它是张量)应具有相同的维度数。此外,要求对于所有维度d
,index.size(d) <= src.size(d)
;对于所有维度d != dim
,index.size(d) <= self.size(d)
。请注意,index
和src
不会进行广播。此外,与
gather()
一样,index
中的值必须在0
和self.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_()
以获得更多归约选项。- 参数
- 关键字参数
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.]])