评价此页

torch.Tensor.index_reduce_#

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

使用 reduce 参数给出的归约方法,将 source 的元素累加到 self 张量中,索引由 index 指定。例如,如果 dim == 0index[i] == jreduce == prod 并且 include_self == True,那么 source 的第 i 行将乘以 self 的第 j 行。如果 include_self="True",则 self 张量中的值会包含在归约中;否则,被累加的 self 张量中的行将被视为用归约的恒等式填充。

sourcedim 维度的长度必须与 index 的长度(必须是向量)相同,并且其他所有维度都必须与 self 匹配,否则将引发错误。

对于一个 3 维张量,当 reduce="prod"include_self=True 时,输出如下:

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 阶段,未来可能会有变动。

参数
  • dim (int) – 沿哪个维度进行索引

  • index (Tensor) – 从中选择 source 元素的索引,其 dtype 应为 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.]])