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

PyTorch torch.narrow_copy function

PyTorch torch.narrow_copy function


PyTorch torch reference manual PyTorch torch reference manual

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

The difference between this function and torch.narrow Similar in functionality, but torch.narrow returns a view, while torch.narrow_copy returns a copy.

Function definition

torch.narrow_copy(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_copy

(

x

,

dim

=

0

,

start

=

0

,

length

=

2

)

print

(

"Original tensor:"

)

print

(

x

)

print

(

"nSlice copy:"

)

print

(

y

)

Modifying the copy does not affect the original tensor

y

[

0

,

0

]

=

100

print

(

"nAfter modifying the copy, original tensor:"

,

x

[

0

,

0

]

)

print

(

"After modifying the copy, slice copy:"

,

y

[

0

,

0

]

)

The output is:

原始张量:

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

        [ 5,  6,  7,  8],

        [ 9, 10, 11, 12]])



Slice copy:

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

        [5, 6, 7, 8]])



修改副本后,原始张量: tensor(1)

修改副本后,切片副本: tensor(100)

Example

import

torch

Create a 3D tensor

x

=

torch.

randn

(

5

,

6

,

7

)

Along the second dimension, take 4 elements starting from index 2

y

=

torch.

narrow_copy

(

x

,

dim

=

1

,

start

=

2

,

length

=

4

)

print

(

"Original shape:"

,

x.

shape

)

print

(

"Slice copy shape:"

,

y.

shape

)

The output is:

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

切片副本形状: torch.Size([5, 4, 7])


Note:torch.narrow_copy What is returned is a copy, not a view. This means modifying the returned tensor does not affect the original tensor, but it uses extra memory. If you do not need an independent copy, you can use torch.narrow to save memory.


PyTorch torch reference manual PyTorch torch reference manual