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]}

2 つのベクトルを取るコサイン類似度関数を持つ各単語間のコサイン類似度を計算したいと考えています。まず、'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={}、1 つのキーと値のペアのみを追加します。 .

どうすればこれを修正できますか??

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

また、大きなデータ構造がある場合は、scipy( http://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.spatial.distance.cosine.html ) またはscikit-learn( http:/ /scikit-learn.org/stable/modules/generated/sklearn.metrics.pairwise.pairwise_distances.html ) より効率的な方法でコサイン類似度を計算するため (後者は、高速であるだけでなく、メモリに優しく、フィードできるため)それはscipy.sparseマトリックスです)。

于 2014-11-04T21:22:28.367 に答える