PyTorch torch.select_scatter function
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:
input(Tensor): Input tensor, i.e. the tensor to be modified.src(Tensor): source tensor, the values to scatter into input.dim(int): the dimension along which to scatter.index(int): the index of the scatter position.
Return Value:
torch.Tensor: Returns the modified tensor.
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
)
(
"Input tensor:"
)
(
input
)
(
"nSource tensor:"
)
(
src
)
(
"nScatter result at index 1:"
)
(
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
)
(
"Input shape:"
,
input
.
shape
)
(
"Source shape:"
,
src.
shape
)
(
"Result shape:"
,
output.
shape
)
(
"nResult (dim=1, index=2):"
)
(
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
)
(
"Original tensor:"
)
(
input
)
(
"nScatter to index -1:"
)
(
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.