評價此頁

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.]])