torch.Tensor.index_reduce_

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

根据index中给定的顺序,并使用reduce参数提供的规约方法,将source中的元素累积到self张量的相应索引位置。例如,如果dim == 0index[i] == jreduce == prodinclude_self == True,则source的第i行与self的第j行相乘。如果include_self=True,则在规约中包含self张量中的值;否则,在累积到的self张量的行被视为填充了规约标识符。

代码中的 source 的第 dim 维度大小必须与 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设备上时,此操作可能表现出非确定性行为。更多详情请参阅重现性

注意

此功能仅支持浮点张量。

警告

此功能尚处测试阶段,未来可能有所更改。

参数
  • dim (int) - 需要进行索引的维度

  • index (Tensor) – 用于选择 source 中元素的索引,数据类型应为torch.int64torch.int32

  • source (FloatTensor) – 包含需要累加的值的张量

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

关键字参数

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.]])
本页目录