python - How to iterate over the dictionary keys to calculate cosine similarity using the values? -


I have a dictionary like this:

  dict = {in: [0.01, - 0.07, 0.09, -0.02], and: For [0.2, 0.3, 0.5, 0.6]: [0.87, 0.98, 0.54, 0.4]}  

I calculate cosine parity I want to write for each word for which I have written a function which takes two vectors First of all, it will take the price for 'in' and 'and', then it should be accepted for 'in' and 'to'.

I want to store it in the second dictionary, where the 'key' should be, and the values ​​should be returned after computation of cosine equality. Similarly, I want dictionaries for other words too.

This is my job to calculate cosine parity:

  import math def cosine_similarity (vec1, vec2): sum11, sum12, sum22 = 0, 0, In the 0 range I (lane (vec1)): x = vec1 [i]; Y = vec2 [i] sum11 + = x * x sum22 + y = y sum12 + = x * y return sum12 / math.sqrt (sum11 * sum22)  

make vec1 and vec2 There can be two lists like [0.01, -0.07, 0.09, -0.02] and [0.2, 0.3, 0.5, 0.6] , and it gives a result Like: 0.14

How would I calculate this way for each key and submit the results in dictionaries like this?

< Div class = "post-text" itemprop = "text">

  import math input dict = {"in": [0.01, -0.07, 0.09, -0.02], "and": [0.2, 0.3 I (lane (VC1)) in the category: sum11, sum12, sum22 = 0, 0, 0: [0.87, 0.98, 0.54, 0.4]} def cosine_similarity (vec1, vec2): "0.5" X = vec1 [i]; Y = vec2 [i] sum11 + = x * x sum22 + y = y sum12 + = x * y return sum12 / math.sqrt (sum11 * sum22) for result = {} key, value in inputDict.items (): TempDict = 0, {} key, inputCict.items in valueC (): if keyC == key: temp = cosine_similarity (value, value C) tempDict [keyC] = temporary result [key] = tempDict print (results) < / Code> 

Output:

  {'in': {'and': 0.14007005254378826, 'to': -0.11279001655020567}, 'and': {'in' : 0.14007005254378826, 'to': 0.7719749900051109}, 'to': {'in': -0.11279001655020567, 'and': 0.7719749900051109}}  

Comments

Popular posts from this blog

apache - 504 Gateway Time-out The server didn't respond in time. How to fix it? -

c# - .net WebSocket: CloseOutputAsync vs CloseAsync -

c++ - How to properly scale qgroupbox title with stylesheet for high resolution display? -