PyTorch torch.tensordot function
PyTorch torch reference manual
torch.tensordot is a function in PyTorch used to compute the dot product of two tensors along specified dimensions. It is a Tensor Contraction operation.
Function definition
torch.tensordot(input, other, dims=2)
Parameter Description:
input: The first input tensorother: The second input tensordims: The number of dimensions to contract or a list of dimension pairs
Usage examples
Example
import
torch
Create two one-dimensional tensors
a
=
torch.
tensor
(
[
1
,
2
,
3
]
)
b
=
torch.
tensor
(
[
4
,
5
,
6
]
)
Compute the dot product
y
=
torch.
tensordot
(
a
,
b
,
dims
=
1
)
(
y
)
The output is:
tensor(32)
Example
import
torch
Create two 2D tensors
a
=
torch.
tensor
(
[
[
1
,
2
]
,
[
3
,
4
]
]
)
b
=
torch.
tensor
(
[
[
5
,
6
]
,
[
7
,
8
]
]
)
Compute matrix multiplication (contracting two dimensions)
y
=
torch.
tensordot
(
a
,
b
,
dims
=
2
)
(
y
)
The output is:
tensor(70)
Example
import
torch
Create a 3D tensor
a
=
torch.
randn
(
2
,
3
,
4
)
b
=
torch.
randn
(
3
,
4
,
5
)
Specify the pairs of dimensions to contract
y
=
torch.
tensordot
(
a
,
b
,
dims
=
[
[
1
,
2
]
,
[
0
,
1
]
]
)
(
y.
shape
)
The output is:
torch.Size([2, 5])