Skip to content

Instantly share code, notes, and snippets.

@mkonicek
Created January 23, 2018 18:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mkonicek/76abcca12987247f8f6ee75b694e50ec to your computer and use it in GitHub Desktop.
Save mkonicek/76abcca12987247f8f6ee75b694e50ec to your computer and use it in GitHub Desktop.
def vector_len(v: Vector) -> float:
return math.sqrt(sum([x*x for x in v]))
def dot_product(v1: Vector, v2: Vector) -> float:
assert len(v1) == len(v2)
return sum([x*y for (x,y) in zip(v1, v2)])
def cosine_similarity(v1: Vector, v2: Vector) -> float:
"""
Returns the cosine of the angle between the two vectors.
Results range from -1 (very different) to 1 (very similar).
"""
return dot_product(v1, v2) / (vector_len(v1) * vector_len(v2))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment