torch.Tensor.scatter_add_
- Tensor.scatter_add_(dim, index, src) → Tensor
-
将张量
src
中的所有值以与scatter_()
类似的方式添加到self
在index
张量中指定的索引位置。对于src
中的每个值,它会被加到由其在src
中的索引和dimension != dim
指定的位置上,或者由index
张量中对应的值指定的位置上(当dimension == dim
时)。对于一个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
self
、index
和src
应该具有相同的维度数量。此外,对于所有维度d
,需要满足index.size(d) <= src.size(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.]])