torch.narrow_copy

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

Tensor.narrow()相同,但这个方法返回一个副本而不是共享存储。这主要是为了稀疏张量,因为它们没有提供共享存储的窄化方法。

参数
  • input (Tensor) – 需要进行裁剪的张量

  • dim (int) - 需要减小的维度

  • start (int) – 指定缩小维度的起始索引。可以使用负数,表示从dim末尾开始计数。

  • length (int) – 窄化维度的长度,必须为正整数或零

关键字参数

out (Tensor, 可选) – 指定输出张量。

示例:

>>> 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() 用于非复制版本

本页目录