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

PyTorch torch.select function

PyTorch torch.select function


PyTorch torch reference manual 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:

Return Value:


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

)

print

(

"Original tensor:"

)

print

(

x

)

print

(

"nSelect the row with index 1:"

)

print

(

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

)

print

(

"Original 3D tensor:"

)

print

(

x

)

print

(

"Shape:"

,

x.

shape

)

Select the element with index 0 along the first dimension (batch)

y

=

torch.

select

(

x

,

dim

=

0

,

index

=

0

)

print

(

"nSelect dim=0, index=0:"

)

print

(

y

)

print

(

"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

)

print

(

"Original tensor:"

)

print

(

x

)

print

(

"nSelect the last row (index=-1):"

)

print

(

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].


PyTorch torch reference manual PyTorch torch reference manual