How to calculate Canberra distance in Python

In this tutorial, we will be looking into How to calculate Canberra distance in Python.

What is Canberra distance?

It is a variation of Manhattan distance. It is used to find the measure the absolute distance between two vectors in space. That is, the measure of how dissimilar two vectors are from each other.

It is very useful in various domains in today’s world. To name a few we have – clustering, data analysis, classification algorithms like K-Nearest Neighbors (KNN), K-Means and many more.

The formula to find the distance is:

calculate Canberra distance in Python

That is the sum of all absolute differences between the two vectors divided by the sum of the absolute value of the vector.

This is a little tedious to find out. Isn’t it?!!!

Python has an inbuilt function to calculate the Canberra distance.

The ‘SciPy‘ package of Python has ‘canberra()‘ function to calculate the distance.

Let’s dive into the code part.

Python Implementation: calculate Canberra distance

First, we will install the necessary library.

!pip install scipy

Next, we will import the necessary libraries.

from scipy.spatial import distance

Now, we will create two vectors. Vectors can be represented using single-dimensional error. So, we have:

vector1 = [1, 2, 3]
vector2 = [4, 5, 6]

Now we will find the passing of the vectors to the canberra function. Here is how we can do this:

canberra_distance = distance.canberra(vector1, vector2)

print(f"Canberra distance: {canberra_distance}")

Output:

Canberra distance in Python

You can read more related posts:

How to compute Manhattan Distance between two points in C++

Special sub-package of Scipy module in Python

Linear algebra with Scipy module in Python

Leave a Reply

Your email address will not be published. Required fields are marked *