【问题标题】:Calculating cosine similarity from file vectors in Python在 Python 中从文件向量计算余弦相似度
【发布时间】:2017-02-08 22:37:54
【问题描述】:

我想计算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))

【问题讨论】:

    标签: python list file-io cosine-similarity


    【解决方案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
    

    【讨论】:

    • 请再问一个问题,我添加了以下代码: with open('vectors','r') as myfile: for line in myfile.readlines(): print(line.split()[1 :]) 仅显示两个列表中的数字。但是我怎样才能把它作为两个单独的列表呢?你能帮忙吗? @Prune
    猜你喜欢
    • 2016-03-08
    • 2015-05-24
    • 1970-01-01
    • 2016-10-28
    • 2017-02-03
    • 2021-05-19
    • 2011-05-21
    • 1970-01-01
    相关资源
    最近更新 更多