# Python Euclidean Distance

I'm working on some facial recognition scripts in python using the dlib library. dlib takes in a face and returns a tuple with floating point values representing the values for key points in the face. If the Euclidean distance between two faces data sets is less that .6 they are likely the same.

So, I had to implement the Euclidean distance calculation on my own. I found an SO post here that said to use numpy but I couldn't make the subtraction operation work between my tuples. Because this is facial recognition speed is important. If anyone can see a way to improve, please let me know.

Yes, it works :)

def euclidean_dist(data_x, data_y):
if len(data_x) != len(data_y):
raise Exception('Data sets must be the same dimension')
dimensions = len(data_x)
sum_dims = 0
for dim in range(0, dimensions):
sum_dims += (data_x[dim] - data_y[dim])**2

return sqrt(sum_dims)


You can collapse the summation using sum():

sum_dims = sum((data_x[dim] - data_y[dim]) ** 2
for dim in range(dimensions))


Or, what if you would "zip" the x and y:

sum_dims = sum((x - y) ** 2 for x, y in zip(data_x, data_y))

• Great solutions, I will research but do you have any idea which implementation would be faster? Nov 28, 2017 at 3:39
• @raykrow I would make a safe bet on the "numpy" one :) Nov 28, 2017 at 3:41
• Ha, ya I'm sure....I will use this for now and possibly open an SO question to figure out how to make numpy work with the tuples Nov 28, 2017 at 3:42