Last active
April 20, 2026 03:18
-
-
Save paceaux/dceae7dc860280dc3ca12c68fd91da03 to your computer and use it in GitHub Desktop.
Cosine Similarity with numpy
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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