評價此頁

torch.narrow_copy#

torch.narrow_copy(input, dim, start, length, *, out=None) Tensor#

Tensor.narrow() 相同,但返回的是副本而不是共享儲存。這主要用於稀疏張量,它們沒有共享儲存的 narrow 方法。

引數
  • input (Tensor) – 要進行切片的張量

  • dim (int) – 沿哪個維度進行切片

  • start (int) – 從哪個索引開始切片(相對於 dim)。可以是負數,表示從 dim 的末尾開始索引。

  • length (int) – 切片的長度,必須是弱正數。

關鍵字引數

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

示例

>>> x = torch.tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
>>> torch.narrow_copy(x, 0, 0, 2)
tensor([[ 1,  2,  3],
        [ 4,  5,  6]])
>>> torch.narrow_copy(x, 1, 1, 2)
tensor([[ 2,  3],
        [ 5,  6],
        [ 8,  9]])
>>> s = torch.arange(16).reshape(2, 2, 2, 2).to_sparse(2)
>>> torch.narrow_copy(s, 0, 0, 1)
tensor(indices=tensor([[0, 0],
                       [0, 1]]),
       values=tensor([[[0, 1],
                       [2, 3]],

                      [[4, 5],
                       [6, 7]]]),
       size=(1, 2, 2, 2), nnz=2, layout=torch.sparse_coo)

另請參閱

torch.narrow() 是非副本的變體。