Skip to content

Instantly share code, notes, and snippets.

@ajfriend
Created April 14, 2018 02:30
Show Gist options
  • Save ajfriend/bebae7b0d64dc4a878c49933ffa5929e to your computer and use it in GitHub Desktop.
Save ajfriend/bebae7b0d64dc4a878c49933ffa5929e to your computer and use it in GitHub Desktop.
import numpy as np
import matplotlib.pyplot as plt
def cos_sim(x1,x2):
"Compute cosine similarity"
n1 = np.linalg.norm(x1)
n2 = np.linalg.norm(x2)
if n1 <= 0 or n2 <= 0:
return 0
else:
return np.dot(x1,x2)/(n1*n2)
q = 10
ws = [.1,1,10]
N = 100000
scores = []
for i in range(N):
s1 = np.random.randint(-2,3,q)
s2 = np.random.randint(-2,3,q)
w1 = np.random.choice(ws,q)
w2 = np.random.choice(ws,q)
scores += [cos_sim(s1*w1, s2*w2)]
plt.hist(scores, 51);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment