快捷方式

torch.Tensor.index_reduce_

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

透過按照 index 中給定的順序,使用 reduce 引數指定的歸約操作,將 source 的元素累加到 self 張量中。例如,如果 dim == 0index[i] == jreduce == prodinclude_self == True,則 source 的第 i 行乘以 self 的第 j 行。如果 include_self="True",則 self 張量中的值包含在歸約中;否則,累加到的 self 張量中的行將被視為填充了對應歸約操作的單位元。

source 的第 dim 維度的尺寸必須與 index 的長度(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 裝置上時,此操作的行為可能不確定。有關更多資訊,請參閱 可復現性

注意

此函式僅支援浮點張量。

警告

此函式處於 Beta 階段,在不久的將來可能會發生變化。

引數
  • 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.]])

文件

訪問 PyTorch 的完整開發者文件

檢視文件

教程

獲取面向初學者和高階開發者的深入教程

檢視教程

資源

查詢開發資源並獲得問題解答

檢視資源