torch.Tensor.scatter_add_¶
- Tensor.scatter_add_(dim, index, src) Tensor ¶
在 `index` 张量指定的索引处,将来自张量
src
的所有值加到self
中,方式类似于scatter_()
。对于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
self
、index
和src
应具有相同的维度数。此外,要求对于所有维度d
,index.size(d) <= src.size(d)
;对于所有d != dim
的维度d
,要求index.size(d) <= self.size(d)
。请注意,index
和src
不进行广播。注意
当在 CUDA 设备上给定张量时,此操作可能表现出不确定性。有关更多信息,请参阅可复现性。
注意
反向传播仅在
src.shape == index.shape
时实现。- 参数
示例
>>> src = torch.ones((2, 5)) >>> index = torch.tensor([[0, 1, 2, 0, 0]]) >>> torch.zeros(3, 5, dtype=src.dtype).scatter_add_(0, index, src) tensor([[1., 0., 0., 1., 1.], [0., 1., 0., 0., 0.], [0., 0., 1., 0., 0.]]) >>> index = torch.tensor([[0, 1, 2, 0, 0], [0, 1, 2, 2, 2]]) >>> torch.zeros(3, 5, dtype=src.dtype).scatter_add_(0, index, src) tensor([[2., 0., 0., 1., 1.], [0., 2., 0., 0., 0.], [0., 0., 2., 1., 1.]])