torch.Tensor.index_reduce_¶
- Tensor.index_reduce_(dim, index, source, reduce, *, include_self=True) 张量¶
将
source的元素累积到self张量中,累积的索引顺序由index给出, 使用由reduce参数指定的归约方式。例如,如果dim == 0,index[i] == j,reduce == prod并且include_self == True,那么source的第i行 将与self的第j行相乘。如果include_self="True",self张量中的值将包含在归约中,否则, 累积到的self张量中的行将被视为填充了归约标识。dim维度中的source必须与index的长度(必须是一个向量)相同,并且所有其他维度必须与self匹配,否则将引发错误。对于一个3维张量,使用
reduce="prod"和include_self=True时,输出如下:self[index[i], :, :] *= src[i, :, :] # 如果 dim == 0 self[:, index[i], :] *= src[:, i, :] # 如果 dim == 1 self[:, :, index[i]] *= src[:, :, i] # 如果 dim == 2
注意
当在CUDA设备上使用张量时,此操作可能会表现出不确定性行为。更多信息请参见可重复性。
注意
此函数仅支持浮点型张量。
警告
此功能目前处于测试阶段,可能会在不久的将来进行更改。
- Parameters
- Keyword Arguments
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.]])