Shortcuts

torch.Tensor.index_reduce_

Tensor.index_reduce_(dim, index, source, reduce, *, include_self=True) 张量

source 的元素累积到 self 张量中,累积的索引顺序由 index 给出, 使用由 reduce 参数指定的归约方式。例如,如果 dim == 0index[i] == jreduce == 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
  • dim (int) – 沿此维度进行索引

  • 索引 (张量) – 用于从 source 中选择的索引, 应具有 torch.int64torch.int32 的数据类型

  • (FloatTensor) – 包含要累积的值的张量

  • reduce (str) – 要应用的归约操作 ("prod", "mean", "amax", "amin")

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.]])
优云智算