Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

PyTorch torch.cdist function

PyTorch torch.cdist function


PyTorch torch reference manual 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

)

print

(

"Point x:"

)

print

(

x

)

print

(

"Point y:"

)

print

(

y

)

print

(

"Euclidean distance matrix:"

)

print

(

distances

)

Use different values of p (Manhattan distance p=1)

dist_l1

=

torch.

cdist

(

x

,

y

,

p

=

1.0

)

print

(

"L1 distance (p=1):"

)

print

(

dist_l1

)

Use p=infinity (Chebyshev distance)

dist_inf

=

torch.

cdist

(

x

,

y

,

p

=

float

(

'inf'

)

)

print

(

"Chebyshev distance (p=inf):"

)

print

(

dist_inf

)


PyTorch torch reference manual PyTorch torch reference manual