PyTorch torch.einsum function
PyTorch torch reference manual
torch.einsum is a PyTorch function for the Einstein summation convention, which can concisely express various tensor operations.
Function definition
torch.einsum(equation, *operands)
Usage examples
Example
import
torch
Matrix transposition
A
=
torch.
randn
(
2
,
3
)
AT
=
torch.
einsum
(
'ij->ji'
,
A
)
(
"Transposed shape:"
,
AT.
shape
)
Matrix multiplication
B
=
torch.
randn
(
3
,
4
)
C
=
torch.
einsum
(
'ij,jk->ik'
,
A
,
B
)
(
"Multiplication shape:"
,
C.
shape
)
Dot product
a
=
torch.
randn
(
3
)
b
=
torch.
randn
(
3
)
dot
=
torch.
einsum
(
'i,i->'
,
a
,
b
)
(
"Dot product:"
,
dot.
item
(
)
)