torch.Tensor.index_reduce_¶
- Tensor.index_reduce_(dim, index, source, reduce, *, include_self=True) Tensor ¶
通过按照
index
中给定的顺序,使用reduce
参数指定的归约操作,将source
的元素累加到self
张量中。例如,如果dim == 0
,index[i] == j
,reduce == prod
且include_self == True
,则source
的第i
行乘以self
的第j
行。如果include_self="True"
,则self
张量中的值包含在归约中;否则,累加到的self
张量中的行将被视为填充了对应归约操作的单位元。source
的第dim
维度的尺寸必须与index
的长度(index
必须是一个向量)相同,并且所有其他维度必须与self
匹配,否则将引发错误。对于一个使用
reduce="prod"
且include_self=True
的 3-D 张量,其输出如下所示:self[index[i], :, :] *= src[i, :, :] # if dim == 0 self[:, index[i], :] *= src[:, i, :] # if dim == 1 self[:, :, index[i]] *= src[:, :, i] # if dim == 2
注意
当输入张量位于 CUDA 设备上时,此操作的行为可能不确定。有关更多信息,请参阅 可复现性。
注意
此函数仅支持浮点张量。
警告
此函数处于 Beta 阶段,在不久的将来可能会发生变化。
- 参数
- 关键字参数
include_self (bool) – 是否将
self
张量中的元素包含在归约中
示例
>>> x = torch.empty(5, 3).fill_(2) >>> t = torch.tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]], dtype=torch.float) >>> index = torch.tensor([0, 4, 2, 0]) >>> x.index_reduce_(0, index, t, 'prod') tensor([[20., 44., 72.], [ 2., 2., 2.], [14., 16., 18.], [ 2., 2., 2.], [ 8., 10., 12.]]) >>> x = torch.empty(5, 3).fill_(2) >>> x.index_reduce_(0, index, t, 'prod', include_self=False) tensor([[10., 22., 36.], [ 2., 2., 2.], [ 7., 8., 9.], [ 2., 2., 2.], [ 4., 5., 6.]])