PyTorch torch.narrow function
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:
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 view 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
(
x
,
dim
=
0
,
start
=
0
,
length
=
2
)
(
"Original tensor:"
)
(
x
)
(
"nSlice result:"
)
(
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
)
(
"Original tensor:"
)
(
x
)
(
"nSlice result:"
)
(
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
)
(
"Original shape:"
,
x.
shape
)
(
"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.