torch.Tensor.scatter_#
- Tensor.scatter_(dim, index, src, *, reduce=None) Tensor #
将
src
张量中的所有值写入self
中,索引由index
张量指定。对于src
中的每个值,其输出索引由其在src
中的索引(对于dimension != dim
)和index
中的相应值(对于dimension = dim
)指定。对于一个 3 维张量,
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()
方法所述操作的逆过程。同时要求
index.size(d) <= src.size(d)
对于所有维度d
,以及index.size(d) <= self.size(d)
对于所有维度d != dim
。请注意,对于 NPU,input
和index
不会相互广播,因此在 NPU 上运行时,input
和index
必须具有相同数量的维度。在所有其他情况下,会发生标准广播。此外,与
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 维张量并使用乘法进行归约,
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, 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) – 要散布的元素的索引,可以是空的,也可以与
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.]])