Skip to content

Instantly share code, notes, and snippets.

@llSourcell
Created January 25, 2020 18:51
Show Gist options
  • Select an option

  • Save llSourcell/e4822c8ff4db677e5759d89ea72095de to your computer and use it in GitHub Desktop.

Select an option

Save llSourcell/e4822c8ff4db677e5759d89ea72095de to your computer and use it in GitHub Desktop.
def cosine_similarity_ngrams(a, b):
vec1 = Counter(a)
vec2 = Counter(b)
intersection = set(vec1.keys()) & set(vec2.keys())
numerator = sum([vec1[x] * vec2[x] for x in intersection])
sum1 = sum([vec1[x]**2 for x in vec1.keys()])
sum2 = sum([vec2[x]**2 for x in vec2.keys()])
denominator = math.sqrt(sum1) * math.sqrt(sum2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment