PyTorch torch.diagonal_scatter function
PyTorch torch reference manual
torch.diagonal_scatter is a PyTorch function for scattering values into diagonal positions of a tensor. It scatters src values into the input specified diagonal of .
Function definition
torch.diagonal_scatter(input, src, offset=0, dim1=0, dim2=1)
Parameters:
input(Tensor): Input tensor, i.e. the tensor to be modified.src(Tensor): Source tensor, the values to scatter into diagonal positions.offset(int, optional): Diagonal offset. Positive values mean upper diagonals, negative values mean lower diagonals, and 0 means the main diagonal.dim1(int, optional): First dimension, defaults to 0.dim2(int, optional): Second dimension, defaults to 1.
Return Value:
torch.Tensor: Returns the modified tensor.
Usage examples
Example
import
torch
Create an input tensor
input
=
torch.
zeros
(
4
,
4
)
src
=
torch.
tensor
(
[
1
,
2
,
3
,
4
]
)
Scatter values into the main diagonal
output
=
torch.
diagonal_scatter
(
input
,
src
)
(
"Input tensor:"
)
(
input
)
(
"nSource tensor:"
)
(
src
)
(
"nScatter to the main diagonal:"
)
(
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, 2, 3, 4])
Scatter to the main diagonal:
tensor([[1., 0., 0., 0.],
[0., 2., 0., 0.],
[0., 0., 3., 0.],
[0., 0., 0., 4.]])
Example
import
torch
Create an input tensor
input
=
torch.
zeros
(
4
,
4
)
src
=
torch.
tensor
(
[
1
,
2
,
3
]
)
Scatter values into the upper diagonal (offset=1)
output
=
torch.
diagonal_scatter
(
input
,
src
,
offset
=
1
)
(
"Scatter into the upper diagonal (offset=1):"
)
(
output
)
Scatter values into the lower diagonal (offset=-1)
output2
=
torch.
diagonal_scatter
(
input
,
src
,
offset
=
1
)
(
"nScatter into the lower diagonal (offset=-1):"
)
(
output2
)
The output is:
散布到上对角线 (offset=1):
tensor([[0., 1., 0., 0.],
[0., 0., 2., 0.],
[0., 0., 0., 3.],
[0., 0., 0., 0.]])
散布到下对角线 (offset=-1):
tensor([[0., 0., 0., 0.],
[1., 0., 0., 0.],
[0., 2., 0., 0.],
[0., 0., 3., 0.]])
Example
import
torch
Using diagonals in a 3D tensor
input
=
torch.
zeros
(
3
,
4
,
4
)
src
=
torch.
tensor
(
[
10
,
20
,
30
]
)
Scatter along the specified two dimensions
output
=
torch.
diagonal_scatter
(
input
,
src
,
dim1
=
1
,
dim2
=
2
)
(
"Input shape:"
,
input
.
shape
)
(
"Source shape:"
,
src.
shape
)
(
"Result shape:"
,
output.
shape
)
View the first batch
(
"nResult of the first batch:"
)
(
output
[
0
]
)
The output is:
输入形状: torch.Size([3, 4, 4])
源形状: torch.Size([3])
结果形状: torch.Size([3, 4, 4])
Result of the first batch:
tensor([[10., 0., 0., 0.],
[0., 20., 0., 0.],
[0., 0., 30., 0.],
[0., 0., 0., 0.]])
Note:torch.diagonal_scatter The original input tensor is not modified; instead, a new tensor is returned.src Its size must match the number of diagonal elements.