Skip to content

Instantly share code, notes, and snippets.

@paceaux
Last active April 20, 2026 03:18
Show Gist options
  • Select an option

  • Save paceaux/dceae7dc860280dc3ca12c68fd91da03 to your computer and use it in GitHub Desktop.

Select an option

Save paceaux/dceae7dc860280dc3ca12c68fd91da03 to your computer and use it in GitHub Desktop.
Cosine Similarity with numpy
import numpy as np
import math
def get_cosine_sim(a, b):
a = np.array(a)
b = np.array(b)
aq = np.square(np.abs(a))
bq =np.square(np.abs(b))
asum = np.sum(aq)
bsum = np.sum(bq)
asq = math.sqrt(np.sum(aq))
bsq = math.sqrt(np.sum(bq))
dot = a.dot(b)
similarity = (dot / (asq * bsq))
return similarity
import math
def get_cosine_sim(a, b):
assert len(a) == len(b)
dot = sum([v * b[i] for i,v in enumerate(a)])
asq = math.sqrt(sum([v**2.0 for v in a]))
bsq = math.sqrt(sum([v**2.0 for v in b]))
similarity = (dot / (asq * bsq))
return similarity
from typing import Sequence
import math
def euclidean_distance(vector1: Sequence[float], vector2: Sequence[float]):
assert len(vector1) == len(vector2)
squares = []
for index, el in enumerate(vector1):
subtraction = el - vector2[index]
square = subtraction ** 2
squares.append(square)
square_sum =sum(squares)
return math.sqrt(square_sum)
from typing import Sequence
import math
def l2_norm(vector: Sequence[float]) -> float:
squares = [el * el for el in vector]
square_sum = sum(squares)
square_root = math.sqrt(square_sum) if square_sum > 0.0 else 1.0
return square_root
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment