torch.Tensor.index_reduce_#
- Tensor.index_reduce_(dim, index, source, reduce, *, include_self=True) Tensor#
使用
reduce引數給出的歸約方法,將source的元素累加到self張量中,索引由index指定。例如,如果dim == 0,index[i] == j,reduce == prod並且include_self == True,那麼source的第i行將乘以self的第j行。如果include_self="True",則self張量中的值會包含在歸約中;否則,被累加的self張量中的行將被視為用歸約的恆等式填充。source的dim維度的長度必須與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 階段,未來可能會有變動。
- 引數
- 關鍵字引數
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.]])