torch.Tensor.index_add_¶
- Tensor.index_add_(dim, index, source, *, alpha=1) Tensor ¶
将
alpha
乘以source
的元素累加到self
张量中,通过按index
中给定顺序添加到索引位置。例如,如果dim == 0
,index[i] == j
,且alpha=-1
,则source
的第i
行将从self
的第j
行中减去。source
的第dim
维度必须与index
的长度(index
必须是向量)具有相同的大小,所有其他维度必须与self
匹配,否则将引发错误。对于 3-D 张量,输出如下所示:
self[index[i], :, :] += alpha * src[i, :, :] # if dim == 0 self[:, index[i], :] += alpha * src[:, i, :] # if dim == 1 self[:, :, index[i]] += alpha * src[:, :, i] # if dim == 2
注意
在给定 CUDA 设备上的张量时,此操作可能表现出非确定性行为。更多信息请参见可复现性。
- 参数
- 关键字参数
alpha (Number) –
source
的标量乘数
示例
>>> x = torch.ones(5, 3) >>> t = torch.tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]], dtype=torch.float) >>> index = torch.tensor([0, 4, 2]) >>> x.index_add_(0, index, t) tensor([[ 2., 3., 4.], [ 1., 1., 1.], [ 8., 9., 10.], [ 1., 1., 1.], [ 5., 6., 7.]]) >>> x.index_add_(0, index, t, alpha=-1) tensor([[ 1., 1., 1.], [ 1., 1., 1.], [ 1., 1., 1.], [ 1., 1., 1.], [ 1., 1., 1.]])