Compute Euclidean Distance Between Two Tensors in PyTorch – PyTorch Tutorial

By | January 30, 2023

In this tutorial, we will introduce how to compute the euclidean distance between two tensors in PyTorch. It is very easy.

Step 1: create two tensors

import torch

x = torch.randn([5, 20])
y = torch.randn([5, 20])

Step 2: compute the euclidean distance

dist = ((x-y)**2).sum(axis=1)
print(dist)

Run this code, we will see:

tensor([36.2746, 53.1081, 20.6923, 53.4271, 32.0512])

Here we should notice we compute sum on axis = 1.