0
$\begingroup$

I'm trying to use Cosine Similarity in Python to compare users, but can't seem to get it quite right.

from math import*


ratings={'Mr. Perfect': {1: 1, 2: 2, 3: 1, 4: 3, 5: 3, 6: 1, 7: 3, 8: 1, 9: 2},
         'The Progressive': {1: 3, 2: 3, 3: 3, 4: 3, 5: 3, 6: 3, 7: 3, 8: 3, 9: 3},
         'Mr. Villain': {1: 3, 2: 3, 3: 3, 4: 3, 5: 3, 6: 3, 7: 3, 8: 3, 9: 3}}




def square_rooted(x):

    return round(sqrt(sum([a*a for a in x])),3)

def cosine_similarity(x,y):

    input1 = {}
    input2 = {}
    vector2 = []
    vector1 =[]

    if len(x) > len(y):
        input1 = x
        input2 = y
    else:
        input1 = y
        input2 = x


    vector1 = list(input1.values())

    for k in input1.keys():    # Normalizing input vectors. 
        if k in input2:
            vector2.append(float(input1[k]))
        else :
            vector2.append(float(0))


    numerator = sum(a*b for a,b in zip(vector2,vector1))
    denominator = square_rooted(vector1)*square_rooted(vector2)
    return round(numerator/float(denominator),3)





print("Similarity between Perfect and Progressive")
print (cosine_similarity(ratings['Mr. Perfect'],ratings['The Progressive']))

print("Similarity between Villain and Progressive")
print (cosine_similarity(ratings['Mr. Villain'],ratings['The Progressive']))

Basically, found the formula here https://stackoverflow.com/questions/35980910/return-similar-score-based-on-two-dictionaries-similarity-in-python but I keep getting results of 1. Any ideas would be helpful!

$\endgroup$

1 Answer 1

1
$\begingroup$

This is wrong: vector2.append(float(input1[k])) Replace by vector2.append(float(input2[k]))

$\endgroup$
1
  • $\begingroup$ Thanks tons! That looks like it did the trick. Do you think I should use Cosine or Jaccard Similarity? $\endgroup$ Oct 17, 2018 at 21:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.