Skip to content

Instantly share code, notes, and snippets.

@yanshengjia
Created December 26, 2017 18:31
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 yanshengjia/6aae7b3394dec0ebc7546b40eda404fe to your computer and use it in GitHub Desktop.
Save yanshengjia/6aae7b3394dec0ebc7546b40eda404fe to your computer and use it in GitHub Desktop.
Compute cosine similarity between two vectors
import math
def cosine_similarity(v1, v2):
"compute cosine similarity of v1 to v2: (v1 dot v2)/{||v1||*||v2||)"
sumxx, sumxy, sumyy = 0.0, 0.0, 0.0
for i in range(len(v1)):
x = v1[i]
y = v2[i]
sumxx += x * x
sumyy += y * y
sumxy += x * y
return sumxy / math.sqrt(sumxx * sumyy)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment