torch.Tensor.scatter_¶
- Tensor.scatter_(dim, index, src, *, reduce=None) Tensor ¶
将张量
src
中的所有值写入到self
中,索引由index
张量指定。对于src
中的每个值,其输出索引由其在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
这是
gather()
中描述的方式的反向操作。self
、index
和src
(如果它是张量)都应具有相同的维度数。还需要index.size(d) <= src.size(d)
对于所有维度d
,以及index.size(d) <= self.size(d)
对于所有维度d != dim
。请注意,index
和src
不会广播。此外,与
gather()
一样,index
的值必须介于0
和self.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_()
相同。警告
带有张量
src
的 reduce 参数已弃用,将在未来的 PyTorch 版本中删除。请改用scatter_reduce_()
以获得更多归约选项。- 参数
- 关键字参数
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 (int) – 沿其索引的轴
index (LongTensor) – 要分散的元素的索引,可以为空或与
src
具有相同的维度。当为空时,操作返回未更改的self
。value (Scalar) – 要分散的值。
- 关键字参数
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.]])