torch.Tensor.scatter_
- Tensor.scatter_(dim, index, src, *, reduce=None) → Tensor
-
将张量
src
中的所有值写入self
,位置由index
张量指定。对于src
中的每个值,其输出索引在维度不等于dim
时由src
中该值的位置确定,在维度等于dim
时由index
张量中的对应值确定。对于一个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
参数,该参数允许指定一个可选的缩减操作。此操作应用于张量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_()
。警告
带有 Tensor
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 (标量) - 需要散列的值。
-
- 关键字参数
-
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.]])