Created
December 26, 2017 18:31
-
-
Save yanshengjia/6aae7b3394dec0ebc7546b40eda404fe to your computer and use it in GitHub Desktop.
Compute cosine similarity between two vectors
This file contains 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 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