PyTorch torch.narrow_copy function
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:
input(Tensor): the input tensor.dim(int): The dimension to slice.start(int): The starting index.length(int): The length of the slice.
Return Value:
torch.Tensor: Returns a tensor copy of the specified slice.
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
)
(
"Original tensor:"
)
(
x
)
(
"nSlice copy:"
)
(
y
)
Modifying the copy does not affect the original tensor
y
[
0
,
0
]
=
100
(
"nAfter modifying the copy, original tensor:"
,
x
[
0
,
0
]
)
(
"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
)
(
"Original shape:"
,
x.
shape
)
(
"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.