Skip to content

Instantly share code, notes, and snippets.

@winstxnhdw
Last active July 31, 2023 15:34
Show Gist options
  • Save winstxnhdw/eab98975f4b6852c23120c743e308d67 to your computer and use it in GitHub Desktop.
Save winstxnhdw/eab98975f4b6852c23120c743e308d67 to your computer and use it in GitHub Desktop.
Calculates the cosine similarity of a pair of 1D lists.
from numpy import float64, inner
from numpy.linalg import norm
from numpy.typing import NDArray
def calculate_1d_cosine_similarity(a: NDArray[float64], b: NDArray[float64]) -> float:
"""
Summary
-------
calculate the cosine similarity of two 1D vectors
Parameters
----------
a (NDArray[float64]): 1D array of arbitrary values
b (NDArray[float64]): 1D array of arbitrary values
Returns
-------
similarity (float): normalised similarity of a and b
"""
return inner(a, b) / (norm(a)*norm(b))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment