PyTorch torch.select function
PyTorch torch reference manual
torch.select is a function in PyTorch used to select a slice corresponding to an index along a specified dimension. It returns a slice view at a specific index position along the specified dimension.
Function definition
torch.select(input, dim, index)
Parameters:
input(Tensor): the input tensor.dim(int): the dimension to select from.index(int): the index to select.
Return Value:
torch.Tensor: return the slice at the specified index position (dimension reduced by 1).
Usage examples
Example
import
torch
Create a 3x4 tensor
x
=
torch.
tensor
(
[
[
1
,
2
,
3
,
4
]
,
[
5
,
6
,
7
,
8
]
,
[
9
,
10
,
11
,
12
]
]
)
Select the row with index 1 along the first dimension (rows)
y
=
torch.
select
(
x
,
dim
=
0
,
index
=
1
)
(
"Original tensor:"
)
(
x
)
(
"nSelect the row with index 1:"
)
(
y
)
The output is:
原始张量:
tensor([[ 1, 2, 3, 4],
[ 5, 6, 7, 8],
[ 9, 10, 11, 12]])
Select the row with index 1:
tensor([5, 6, 7, 8])
Example
import
torch
Create a 3D tensor
x
=
torch.
arange
(
24
)
.
reshape
(
2
,
3
,
4
)
(
"Original 3D tensor:"
)
(
x
)
(
"Shape:"
,
x.
shape
)
Select the element with index 0 along the first dimension (batch)
y
=
torch.
select
(
x
,
dim
=
0
,
index
=
0
)
(
"nSelect dim=0, index=0:"
)
(
y
)
(
"Shape:"
,
y.
shape
)
The output is:
原始3D张量:
tensor([[[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]],
[[12, 13, 14, 15],
[16, 17, 18, 19],
[20, 21, 22, 23]]])
形状: torch.Size([2, 3, 4])
选择 dim=0, index=0:
tensor([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]])
形状: torch.Size([3, 4])
Example
import
torch
Use negative indices
x
=
torch.
tensor
(
[
[
1
,
2
,
3
]
,
[
4
,
5
,
6
]
,
[
7
,
8
,
9
]
]
)
An equivalent way to select the last row
y
=
torch.
select
(
x
,
dim
=
0
,
index
=
1
)
(
"Original tensor:"
)
(
x
)
(
"nSelect the last row (index=-1):"
)
(
y
)
The output is:
原始张量:
tensor([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
选择最后一行 (index=-1):
tensor([7, 8, 9])
Note:torch.select What is returned is a view, not a copy, so the operation is efficient. Similar functionality can also be achieved with slicing operations, such as x[index] or x[index:index+1].