Cosine distance computation between two arrays in Python

There are several methods to compute the cosine distance between two arrays in Python. Here are three common approaches.

Methods:

1.NumPy: NumPy is used for quick array operations and provides an extensive level of functionality which is utilized in Scientific computing. You can use the builtin NumPy functions that take in arrays for example, dot and linalg. normalized for the cosine distance

2.Via SciPy: SciPy, a very capable library for scientific computing, offers a cosine function in the scipy. spatial. cosine distance distance module, so you can directly implement the cosine distance conflict;

3.Manually: If you do not wish to use libraries and you are just using simple Python operations to… This means basically computing the dot product and the norms of the vectors and calculating using the formula.

These can be useful as they each have their own purpose for computing cosine distance between arrays in Python, and you can choose the method according to your needs and requirements as you see fit.

This script defines a function cosine_distance which takes two NumPy arrays as input and returns their cosine distance. It finds the Dot product between the two arrays. via np. dot and then calculates the norms of all arrays with np. linalg. norm. Last but not least, it calculates the cosine distance by the simple formula 1 – dot_product / (norm_a, norm_b)

                Method 1: Using NumPy

import numpy as np

def cosine_distance(array1, array2):
    dot_product = np.dot(array1, array2)
    norm_a = np.linalg.norm(array1)
    norm_b = np.linalg.norm(array2)
    return 1.0 - (dot_product / (norm_a * norm_b))

# Example arrays
array1 = np.array([1, 2, 3])
array2 = np.array([4, 5, 6])

# Compute cosine distance
distance = cosine_distance(array1, array2)
print("Cosine distance:", distance)
output :Cosine distance: 0.01973210116738971

Method 2: Using SciPy

from scipy.spatial.distance import cosine

# Example arrays
array1 = [1, 2, 3]
array2 = [4, 5, 6]

# Compute cosine distance
distance = cosine(array1, array2)
print("Cosine distance:", distance)
   output: Cosine distance: 0.01973210116738971

      Method 3: Manual Calculation

import math

def cosine_distance_manual(array1, array2):
    dot_product = sum(a * b for a, b in zip(array1, array2))
    norm_a = math.sqrt(sum(a * a for a in array1))
    norm_b = math.sqrt(sum(b * b for b in array2))
    return 1.0 - (dot_product / (norm_a * norm_b))

# Example arrays
array1 = [1, 2, 3]
array2 = [4, 5, 6]

# Compute cosine distance
distance = cosine_distance_manual(array1, array2)
print("Cosine distance:", distance)
OUTPUT :Cosine distance: 0.02538843760430669

Leave a Reply

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