次のような辞書があります。
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 つのキーと値のペアのみを追加します。 .
どうすればこれを修正できますか??