Vito
Vito

Reputation: 728

Get Euclidian and infinite distance in Pytorch

I'm trying to get the Euclidian Distance in Pytorch, using torch.dist, as shown below:

torch.dist(vector1, vector2, 1)

If I use "1" as the third Parameter, I'm getting the Manhattan distance, and the result is correct, but I'm trying to get the Euclidian and Infinite distances and the result is not right. I tried with a lot of different numbers on the third parameter, but I'm not able to get the desired distances.

How can I get the Euclidian and Infinite distances using Pytorch?

Upvotes: 1

Views: 4547

Answers (3)

smonsays
smonsays

Reputation: 420

torch.norm is now deprecated and it is recommended to use torch.linalg.norm() instead. The documentation can be found here.

The euclidian and infinity distance can be computed with

vector1 = torch.FloatTensor([3, 4, 5])
vector2 = torch.FloatTensor([1, 1, 1])
dist_euclidian = torch.linalg.norm(vector1 - vector2)  # tensor(5.3852)
dist_infinity = torch.linalg.norm(vector1 - vector2, float("inf"))  # tensor(4.)

Upvotes: 0

Wasi Ahmad
Wasi Ahmad

Reputation: 37741

You should use the .norm() instead of .dist().

vector1 = torch.FloatTensor([3, 4, 5])
vector2 = torch.FloatTensor([1, 1, 1])

dist = torch.norm(vector1 - vector2, 1)
print(dist) # tensor(9.)
dist = torch.norm(vector1 - vector2, 2)
print(dist) # tensor(5.3852)
dist = torch.norm(vector1 - vector2, float("inf"))
print(dist) # tensor(4.)

dist = torch.dist(vector1, vector2, 1)
print(dist) # tensor(9.)
dist = torch.dist(vector1, vector2, 2)
print(dist) # tensor(5.3852)
dist = torch.dist(vector1, vector2, float("inf"))
print(dist) # tensor(1.)

As we can see for the infinity distance, .norm() returns the correct answer.

Upvotes: 6

Chaitanya Shivade
Chaitanya Shivade

Reputation: 859

Euclidean distance is the L2 norm: torch.dist(vector1, vector2, 2)
Inifnity norm: torch.dist(vector1, vector2, float("inf"))

Upvotes: 0

Related Questions