I have received a type error while comparing two dictionaries using the cosine similarity. I have tried to search around but still not able to solve it, and would really appreciate if anyone could shed some light for me.
My dictionaries look as like below.
dict1 = {'a': 1, 'b': 0, 'c': 1}
dict2 = {'a': 1, 'b': 1, 'c': 0}
I have also looked around in stack overflow, and indeed there are members who also compared the values of dictionaries using cosine similarity. And I thought it should be very similar to my case. This is the url where I referenced to: Python: calculate cosine similarity of two dicts faster
This is the function as provided by @Davidmh (with slight modifications to it):
import numpy as np
def cos(v1, v2):
up = 0
for key in set(v1).intersection(v2):
v1_value = v1[key]
v2_value = v2[key]
up += v1_value * v2_value
if up == 0:
return 0
return up / (np.sqrt(np.dot(v1.values(), v1.values())) * np.sqrt(np.dot(v2.values(), v2.values())))
So the next thing I did is to call the function:
print(cos(dict1, dict2))
And below is the type error message that I received.
File "C:/Users/Yoshiaki/TextProcessing/compute.py", line 157, in cos
return up / (np.sqrt(np.dot(v1.values(), v1.values())) * np.sqrt(np.dot(v2.values(), v2.values())))
TypeError: unsupported operand type(s) for *: 'dict_values' and 'dict_values'
I have googled on the type error that appeared, but it doesn't gives me much explanation nor result. And it seems to do with set operations...? I also tried even without using the set operation (intersection), it will also give me the same error message...
Could anyone please advice to me of how I could solve this problem?
Thanks.
Could you try changing them to lists via list(v1.values())? dict_values is a type, so converting it to a list may solve the issue.
return up / (np.sqrt(np.dot(list(v1.values()), list(v1.values()))) * np.sqrt(np.dot(list(v2.values()), list(v2.values()))))
Reference: Python: simplest way to get list of values from dict?