I would like to calculate cosine similarity between two vectors in the a file in the following format:
first_vector 1 2 3
second_vector 1 3 5
... simply the name of the vector and then its elements, separated by single space. I have defined a function which should take each line as individual list and then calculate the similarity. My problem is that I do not know I how to convert the two lines to two lists.
This is my code:
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))