1

我有一本这样的字典:

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

我想计算每个单词之间的余弦相似度,我有一个余弦相似度函数,该函数采用两个向量。首先,它将为 'in' 和 'and' 取值,然后它应该为 'in' 和 'to' 取值等等。

我希望它将结果存储在另一个字典中,其中“in”应该是键,值应该是每个计算的余弦相似度值与该键的字典。就像我希望输出是这样的:

{in : {and : 0.4321, to : 0.218}, and : {in : 0.1245, to : 0.9876}, to : { in : 0.8764, and : 0.123}}

以下是执行所有这些操作的代码:

def cosine_similarity(vec1,vec2):
    sum11, sum12, sum22 = 0, 0, 0
    for i in range(len(vec1)):
        x = vec1[i]; y = vec2[i]
        sum11 += x*x
        sum22 += y*y
        sum12 += x*y
    return sum12/math.sqrt(sum11*sum22)

def resultInDict(result,name,value,keyC):
    new_dict={}
    new_dict[keyC]=value       
    if name in result:
        result[name] = new_dict
    else:
         result[name] = new_dict

def extract():
    result={}
    res={}
    with open('file.txt') as text:
        for line in text:
            record = line.split()
            key = record[0]
            values = [float(value) for value in record[1:]]
            res[key] = values
    for key,value in res.iteritems():
            temp = 0
            for keyC,valueC in res.iteritems():

                if keyC == key:
                    continue
                temp = cosine_similarity(value,valueC)
                resultInDict(result,key,temp,keyC)
    print result

但是,它给出的结果是这样的:

{'and': {'in': 0.12241083209661485}, 'to': {'in': -0.0654517869126785}, 'from': {'in': -0.5324142931780856}, 'in': {'from': -0.5324142931780856}}

我希望它是这样的:

{in : {and : 0.4321, to : 0.218}, and : {in : 0.1245, to : 0.9876}, to : { in : 0.8764, and : 0.123}}

我觉得是因为在resultInDict函数中我定义了一个新字典new_dict来为内部字典添加键值,但是每次调用函数resultInDict时,都会清空这一行的new_dict new_dict={},只添加一个键值对.

我怎样才能解决这个问题??

4

1 回答 1

1

不是很优雅,但它确实有效:

import math

def cosine_similarity(vec1,vec2):
    sum11, sum12, sum22 = 0, 0, 0
    for i in range(len(vec1)):
        x = vec1[i]; y = vec2[i]
        sum11 += x*x
        sum22 += y*y
        sum12 += x*y
    return sum12/math.sqrt(sum11*sum22)

mydict = {"in" : [0.01, -0.07, 0.09, -0.02], "and" : [0.2, 0.3, 0.5, 0.6], "to" : [0.87, 0.98, 0.54, 0.4]}
mydict_keys = mydict.keys()

result = {}
for k1 in mydict_keys:
   temp_dict = {}
   for k2 in mydict_keys:
      if k1 != k2:
         temp_dict[k2] = cosine_similarity(mydict[k1], mydict[k2])
   result[k1] = temp_dict

此外,如果您有大数据结构,请考虑使用scipyhttp://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.spatial.distance.cosine.html)或scikit-learnhttp:// /scikit-learn.org/stable/modules/generated/sklearn.metrics.pairwise.pairwise_distances.html)以更有效的方式计算余弦相似度(后者不仅速度快,而且内存友好,因为你可以喂它是一个scipy.sparse矩阵)。

于 2014-11-04T21:22:28.367 回答