評價此頁

torch.index_select#

torch.index_select(input, dim, index, *, out=None) Tensor#

使用 index(一個 LongTensor)中的條目,沿 dim 維度選擇 input 張量,並返回一個新的張量。

返回的張量具有與原始張量(input)相同的維數。 dim 維的大小與 index 的長度相同;其他維的大小與原始張量相同。

注意

返回的張量 **不** 使用與原始張量相同的儲存。如果 out 的形狀與預期不同,我們將悄悄地更改它以使其形狀正確,並在必要時重新分配底層儲存。

引數
  • input (Tensor) – 輸入張量。

  • dim (int) – 我們從中選擇的維度

  • index (IntTensorLongTensor) – 包含選擇索引的一維張量

關鍵字引數

out (Tensor, optional) – 輸出張量。

示例

>>> x = torch.randn(3, 4)
>>> x
tensor([[ 0.1427,  0.0231, -0.5414, -1.0009],
        [-0.4664,  0.2647, -0.1228, -1.1068],
        [-1.1734, -0.6571,  0.7230, -0.6004]])
>>> indices = torch.tensor([0, 2])
>>> torch.index_select(x, 0, indices)
tensor([[ 0.1427,  0.0231, -0.5414, -1.0009],
        [-1.1734, -0.6571,  0.7230, -0.6004]])
>>> torch.index_select(x, 1, indices)
tensor([[ 0.1427, -0.5414],
        [-0.4664, -0.1228],
        [-1.1734,  0.7230]])