torch.Tensor.index_reduce_¶
- Tensor.index_reduce_(dim, index, source, reduce, *, include_self=True) Tensor¶
透過按照
index中給定的順序,使用reduce引數指定的歸約操作,將source的元素累加到self張量中。例如,如果dim == 0,index[i] == j,reduce == prod且include_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 階段,在不久的將來可能會發生變化。
- 引數
- 關鍵字引數
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.]])