评价此页

torch.take_along_dim#

torch.take_along_dim(input, indices, dim=None, *, out=None) Tensor#

input 中,沿指定的 dim 维度,选取 indices 中的一维索引对应的值。

如果 dim 为 None,则输入数组将被视为已展平成一维。

torch.argmax()torch.argsort() 这样返回沿维度的索引的函数,可以与此函数配合使用。请参阅下面的示例。

注意

此函数类似于 NumPy 的 take_along_axis。另请参阅 torch.gather()

参数
  • input (Tensor) – 输入张量。

  • indices (LongTensor) – input 的索引。必须是 long 类型。

  • dim (int, optional) – 选择的维度。默认为 0。

关键字参数

out (Tensor, optional) – 输出张量。

示例

>>> t = torch.tensor([[10, 30, 20], [60, 40, 50]])
>>> max_idx = torch.argmax(t)
>>> torch.take_along_dim(t, max_idx)
tensor([60])
>>> sorted_idx = torch.argsort(t, dim=1)
>>> torch.take_along_dim(t, sorted_idx, dim=1)
tensor([[10, 20, 30],
        [40, 50, 60]])