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

PyTorch torch.select_scatter function

PyTorch torch.select_scatter function


PyTorch torch reference manual PyTorch torch reference manual

torch.select_scatter is a function in PyTorch used to scatter a source tensor to a specified index position. It src values into the input specified dimension of dim and index index position.

Function definition

torch.select_scatter(input, src, dim, index)

Parameters:

Return Value:


Usage examples

Example

import

torch

Create the input tensor and source tensor

input

=

torch.

zeros

(

4

,

4

)

src

=

torch.

ones

(

4

)

Scatter src at index 1 along the first dimension (rows)

output

=

torch.

select_scatter

(

input

,

src

,

dim

=

0

,

index

=

1

)

print

(

"Input tensor:"

)

print

(

input

)

print

(

"nSource tensor:"

)

print

(

src

)

print

(

"nScatter result at index 1:"

)

print

(

output

)

The output is:

输入张量:

tensor([[0., 0., 0., 0.],

        [0., 0., 0., 0.],

        [0., 0., 0., 0.],

        [0., 0., 0., 0.]])



Source Tensor:

tensor([1., 1., 1., 1.])



Scatter results at index 1:

tensor([[0., 0., 0., 0.],

        [1., 1., 1., 1.],

        [0., 0., 0., 0.],

        [0., 0., 0., 0.]])

Example

import

torch

Create a 3D tensor

input

=

torch.

zeros

(

3

,

4

,

5

)

src

=

torch.

ones

(

5

)

Scatter along the second dimension (index 2)

output

=

torch.

select_scatter

(

input

,

src

,

dim

=

1

,

index

=

2

)

print

(

"Input shape:"

,

input

.

shape

)

print

(

"Source shape:"

,

src.

shape

)

print

(

"Result shape:"

,

output.

shape

)

print

(

"nResult (dim=1, index=2):"

)

print

(

output

[

0

]

)

The output is:

输入形状: torch.Size([3, 4, 5])

源形状: torch.Size([5])

结果形状: torch.Size([3, 4, 5])



结果 (dim=1, index=2):

tensor([1., 1., 1., 1., 1.])

Example

import

torch

Use different values

input

=

torch.

arange

(

16

)

.

reshape

(

4

,

4

)

.

float

(

)

src

=

torch.

tensor

(

[

100

,

100

,

100

,

100

]

)

Scatter into the last row

output

=

torch.

select_scatter

(

input

,

src

,

dim

=

0

,

index

=

1

)

print

(

"Original tensor:"

)

print

(

input

)

print

(

"nScatter to index -1:"

)

print

(

output

)

The output is:

原始张量:

tensor([[ 0.,  1.,  2.,  3.],

        [ 4.,  5.,  6.,  7.],

        [ 8.,  9., 10., 11.],

        [12., 13., 14., 15.]])



Scatter to index -1 position:

tensor([[ 0.,  1.,  2.,  3.],

        [ 4.,  5.,  6.,  7.],

        [ 8.,  9., 10., 11.],

        [100., 100., 100., 100.]])


Note:torch.select_scatter The original input tensor is not modified; instead, a new tensor is returned.src dimensions must match the dimensions of the slice to be replaced.


PyTorch torch reference manual PyTorch torch reference manual