PyTorch torch.cdist function
PyTorch torch reference manual
torch.cdist is a function in PyTorch used to compute the matrix of Euclidean distances between two sets of points. It computes the Euclidean distance between each point in the first input and each point in the second input, returning a distance matrix.
Function definition
torch.cdist(input1, input2, p=2.0, compute_mode='use_mm_for_euclidean_dist')
Usage examples
Example
import
torch
Compute the Euclidean distance between two sets of points
x
=
torch.
tensor
(
[
[
0
,
0
]
,
[
1
,
1
]
,
[
2
,
2
]
]
)
3 2D points
y
=
torch.
tensor
(
[
[
0
,
0
]
,
[
1
,
0
]
,
[
2
,
0
]
]
)
3 2D points
Distance matrix shape: (3, 3)
distances
=
torch.
cdist
(
x
,
y
)
(
"Point x:"
)
(
x
)
(
"Point y:"
)
(
y
)
(
"Euclidean distance matrix:"
)
(
distances
)
Use different values of p (Manhattan distance p=1)
dist_l1
=
torch.
cdist
(
x
,
y
,
p
=
1.0
)
(
"L1 distance (p=1):"
)
(
dist_l1
)
Use p=infinity (Chebyshev distance)
dist_inf
=
torch.
cdist
(
x
,
y
,
p
=
float
(
'inf'
)
)
(
"Chebyshev distance (p=inf):"
)
(
dist_inf
)