Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@JBed
Created August 4, 2015 18:53
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 JBed/675f52b690c1a9f7e3e3 to your computer and use it in GitHub Desktop.
Save JBed/675f52b690c1a9f7e3e3 to your computer and use it in GitHub Desktop.
simple cosine similarity
import re, math
from collections import Counter
def sentence_to_vector(text):
words = WORD.findall(text)
return Counter(words)
def cos_similarity(text1, text2):
WORD = re.compile(r'\w+')
vec1 = text_to_vector(text1)
vec2 = text_to_vector(text2)
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)
return float(numerator) / denominator
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment