Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

PyTorch torch.narrow function

PyTorch torch.narrow function


PyTorch torch reference manual PyTorch torch reference manual

torch.narrow is a function in PyTorch used to return a slice of a tensor. It returns a view of the slice along the specified dimension, from the starting position to the given length.

Function definition

torch.narrow(input, dim, start, length)

Parameters:

Return Value:


Usage examples

Example

import

torch

Create a tensor

x

=

torch.

tensor

(

[

[

1

,

2

,

3

,

4

]

,

                 

[

5

,

6

,

7

,

8

]

,

                 

[

9

,

10

,

11

,

12

]

]

)

Along the first dimension (rows), take 2 rows starting from index 0

y

=

torch.

narrow

(

x

,

dim

=

0

,

start

=

0

,

length

=

2

)

print

(

"Original tensor:"

)

print

(

x

)

print

(

"nSlice result:"

)

print

(

y

)

The output is:

原始张量:

tensor([[ 1,  2,  3,  4],

        [ 5,  6,  7,  8],

        [ 9, 10, 11, 12]])



Slice result:

tensor([[1, 2, 3, 4],

        [5, 6, 7, 8]])

Example

import

torch

Create a tensor

x

=

torch.

tensor

(

[

[

1

,

2

,

3

,

4

]

,

                 

[

5

,

6

,

7

,

8

]

,

                 

[

9

,

10

,

11

,

12

]

]

)

Along the second dimension (columns), take 2 columns starting from index 1

y

=

torch.

narrow

(

x

,

dim

=

1

,

start

=

1

,

length

=

2

)

print

(

"Original tensor:"

)

print

(

x

)

print

(

"nSlice result:"

)

print

(

y

)

The output is:

原始张量:

tensor([[ 1,  2,  3,  4],

        [ 5,  6,  7,  8],

        [ 9, 10, 11, 12]])



Slice result:

tensor([[ 2,  3],

        [ 6,  7],

        [10, 11]])

Example

import

torch

Create a 3D tensor

x

=

torch.

randn

(

5

,

6

,

7

)

Along the first dimension, take 3 elements starting from index 2

y

=

torch.

narrow

(

x

,

dim

=

0

,

start

=

2

,

length

=

3

)

print

(

"Original shape:"

,

x.

shape

)

print

(

"Shape after slicing:"

,

y.

shape

)

The output is:

原始形状: torch.Size([5, 6, 7])

切片后形状: torch.Size([3, 6, 7])


Note:torch.narrow What is returned is a view of the original tensor, not a copy. If you need a copy, you can use torch.narrow_copy.


PyTorch torch reference manual PyTorch torch reference manual