在Python中计算文件向量的余弦相似度

时间:2017-02-08 22:37:54

标签: python list file-io cosine-similarity

我想用以下格式计算a文件中两个向量之间的余弦相似度:

first_vector 1 2 3  
second_vector 1 3 5  

...简单地说是矢量的名称,然后是它的元素,用单个空格分隔。我已经定义了一个函数,它应该将每一行作为单独的列表,然后计算相似性。我的问题是我不知道如何将两行转换为两个列表。

这是我的代码:

import math

def cosine_sim(vector1,vector2):

    sum_of_x,sum_of_y, sum_of_xy=0,0,0
    for i in range(len(v1)):
        x=vector1[i]; y=vector2[i]
        sum_of_x+=x*x;
        sum_of_y+=y*y;
        sum_of_xy += x*y
    return (sum_of_xy/math.sqrt(sum_of_x*sum_of_y))


myfile=open("vectors","r")
v1='#This should read the first line vector which is 1 2 3'
v2='#This should read the second line vector which is 1 3 5'
print("The similarity is",cosine_sim(v1,v2))

1 个答案:

答案 0 :(得分:1)

这些是您应该为此作业学习的基本数据操作技能。以下是步骤:

Read the entire line into a string.  # input()
Split the string on spaces.          # string.split()
Drop the first element.              # list slice or pop()
Convert the others to integer.       # int()

可以将所有内容填充到一行代码中,但我建议您分四步完成,在编写代码时测试每一步。最后一个可能是一个循环,取决于您当前的技能水平。

这会让你感动吗?

输入配对

要处理成对的输入行,y必须单独读取和拆分它们。另一种方法是维护一个布尔标志,告诉你当前的迭代是第一行还是第二行。

一种方式:

while not at end of file:    # I leave coding details to you
    line1 = myfile.readline().split(' ')[1:]
    line2 = myfile.readline().split(' ')[1:]
    # Convert both to numbers; compute cosine

另一种方式:

first = True
line in myfile.readlines():
    if first:
        line1 = myfile.readline().split(' ')[1:]
    else:
        line2 = myfile.readline().split(' ')[1:]
        # Convert both to numbers; compute cosine
        first = not first