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()
方法所述的逆向操作。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
参数,该参数允许指定一个可选的归约操作,该操作应用于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.]])