How to calculate Canberra distance in Python?

By Shivang Yadav Last updated : November 21, 2023

Canberra Distance

The Canberra distance is a measure of dissimilarity between two vectors. It is often used when dealing with data that contains outliers or extreme values. The formula for Canberra distance between two vectors X and Y of length n is given by:

Canberra Distance

Calculation of Canberra Distance

One direct method to calculate the Canberra distance is by using the mathematical formula which is a complex way and might take more time and space for computation. But the Python provides a built-in method to perform the task. The distance.Canberra() method of the scipy library performs the task in a more optimized way.

Python program to calculate Canberra distance

# Python program to calculate
# Canberra distance

import numpy as np
from scipy.spatial import distance

# Creating Arrays
vecA = np.array([1, 5, 2, 6, 7])
vecB = np.array([4, 8, 1, 3, 5])

print("Vector A", vecA)
print("Vector B", vecB)

# calculate and print Canberra distance
canberraDist = distance.canberra(vecA, vecB)

print("Canberra Distance between vectors", canberraDist)

Output

The output of the above program is:

Vector A [1 5 2 6 7]
Vector B [4 8 1 3 5]
Canberra Distance between vectors 1.664102564102564

Python SciPy Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.