Calculate Euclidean Distance in TensorFlow: A Step Guide – TensorFlow Tutorial

By | May 18, 2020

Euclidean Distance is common used to be a loss function in deep learning. It is defined as:

Euclidean distance in tensorflow

In this tutorial, we will introduce how to calculate euclidean distance of two tensors.

Create two tensors

We will create two tensors, then we will compute their euclidean distance.

Here is an example:

import tensorflow as tf
import numpy as np

x = tf.Variable(np.array([[1, 2, 2, 1],[2, 1, 3, 4], [4, 3, 1, 1]]), dtype = tf.float32)

xs = tf.Variable(np.array([[1, 3, 2, 1],[2, 2, 5, 4], [4, 1, 3, 1]]), dtype = tf.float32)

You should notice tensors x and xs are 2 dims.

Create a function to calculate euclidean distance

We have created a function to compute euclidean distance of two tensors in tensorflow. Here is an example:

#x and y are 2 dims
def euclideanDistance(x, y):
    dist = tf.sqrt(tf.reduce_sum(tf.square(x - y), 1))
    return dist

Calculate euclidean distance

Finally, we will calculate euclidean distance.

d = euclideanDistance(x, xs)
init = tf.global_variables_initializer() 
init_local = tf.local_variables_initializer()

with tf.Session() as sess:[init, init_local])

Run this code, you will get the distance is:

[1.       2.236068 2.828427]

In order to calculate the average euclidean distance, we can create a new function.

def euclideanMeanDistance(x, y):
    dist = tf.sqrt(tf.reduce_sum(tf.square(x - y), 1))
    return tf.reduce_mean(dist)

Then we will get the average euclidean distance is:

d = euclideanMeanDistance(x, xs)

Run the code again, we will get the result:


However, tf.sqrt() may output NaN value, to fix this error, you can read:

Fix TensorFlow tf.sqrt() NaN Error: A Beginner Guide – TensorFlow Tutorial

There is another way to compute euclidean distance in tensorflow, we can use tf.norm().

Calculate euclidean distance using tf.norm()

Here is an example:

def euclideanMeanDistance(self, x, y):
    dist = tf.reduce_mean(tf.norm(x - y, axis=1, ord='euclidean'))
    return dist

Where x and y is 2 dims, run this code, you also can get the result: