简体   繁体   中英

Python cosine-similarity on all possible pairs in list

I'm learning Python slowly and was wondering if I could have some help. I have a list of ips, occurrence_id and vector called info_list :

('188.74.64.243', '1', ['0, 1, 1, 0'])
('99.229.98.18',  '1', ['0, 1, 1, 1'])
('86.41.253.102', '1', ['1, 1, 1, 1'])
('188.74.64.243', '2', ['0, 1, 1, 0'])
('99.229.98.18',  '2', ['0, 1, 1, 1'])
('86.41.253.102', '2', ['1, 1, 1, 1'])

I want to calculate cosine similarity. I have the following:

def cosine_similarity(v1,v2):
    sumxx, sumxy, sumyy = 0, 0, 0
    for i in range(len(v1)):
        x = v1[i]; y = v2[i]
        sumxx += x*x
        sumyy += y*y
        sumxy += x*y
    return sumxy/math.sqrt(sumxx*sumyy)

v1 = [0, 1, 1, 0]
v2 = [1, 1, 1, 1]
print(v1, v2, cosine_similarity(v1,v2))

This works great when v1 and v2 are stated. My problem is that I'm in a little bit of a loop hole and can't seem to piece together my problem. I was hoping for a little help.

I need to loop through info_list , taking into consideration each pair of ips that have the same occurrence_id to calculate the cosine_similarity .

An example of the output would be a list like so:

    ('188.74.64.243', '99.229.98.18', '1', ['0, 1, 1, 0'],['0, 1, 1, 1'], 0.82 )
    ('188.74.64.243', '86.41.253.102', '1', ['0, 1, 1, 0'],['1, 1, 1, 1'], 0.70 )
    ('86.41.253.102', '99.229.98.18', '1', ['0, 1, 1, 1'],['1, 1, 1, 1'], 0.87 )

You can make use of Python's groupby and combinations functions as follows:

from itertools import groupby, combinations
import math

def cosine_similarity(v1,v2):
    sumxx, sumxy, sumyy = 0, 0, 0
    for i in range(len(v1)):
        x = v1[i]; y = v2[i]
        sumxx += x*x
        sumyy += y*y
        sumxy += x*y
    return sumxy/math.sqrt(sumxx * sumyy)

info_list = [
    ('188.74.64.243', '1', [0, 1, 1, 0]),
    ('99.229.98.18',  '1', [0, 1, 1, 1]),
    ('86.41.253.102', '1', [1, 1, 1, 1]),
    ('188.74.64.243', '2', [0, 1, 1, 0]),
    ('99.229.98.18',  '2', [0, 1, 1, 1]),
    ('86.41.253.102', '2', [1, 1, 1, 1]),
    ]

for k, g in groupby(info_list, key=lambda x: x[1]):
    for x, y in combinations(g, 2):
        print (x[0], y[0], x[1], x[2], y[2], cosine_similarity(x[2], y[2]))
    print

This will display the following output:

('188.74.64.243', '99.229.98.18', '1', [0, 1, 1, 0], [0, 1, 1, 1], 0.8164965809277261)
('188.74.64.243', '86.41.253.102', '1', [0, 1, 1, 0], [1, 1, 1, 1], 0.7071067811865475)
('99.229.98.18', '86.41.253.102', '1', [0, 1, 1, 1], [1, 1, 1, 1], 0.8660254037844387)

('188.74.64.243', '99.229.98.18', '2', [0, 1, 1, 0], [0, 1, 1, 1], 0.8164965809277261)
('188.74.64.243', '86.41.253.102', '2', [0, 1, 1, 0], [1, 1, 1, 1], 0.7071067811865475)
('99.229.98.18', '86.41.253.102', '2', [0, 1, 1, 1], [1, 1, 1, 1], 0.8660254037844387)

If the list is not sorted, ie the IDs are not grouped together, then the following line could be replaced:

for k, g in groupby(sorted(info_list, key=lambda x: x[1]), key=lambda x: x[1]):

Keeping the data as you gave it (with the vector represented by a string), You could write a function which takes two of your tuples, unpacks the string into an int vector, applies the similarity function, and the repackages. Then -- use this function with a basic nested loop:

import math

def cosine_similarity(v1,v2):
    sumxx, sumxy, sumyy = 0, 0, 0
    for i in range(len(v1)):
        x, y = v1[i],v2[i]
        sumxx += x*x
        sumyy += y*y
        sumxy += x*y
    return sumxy/math.sqrt(sumxx*sumyy)

def c_sim(t1,t2):
    ips1,id1,vlist1 = t1
    ips2,id2,vlist2 = t2
    v1 = [int(i) for i in vlist1[0].split(',')]
    v2 = [int(i) for i in vlist2[0].split(',')]
    if id1 == id2:
        return ips1,ips2,id1,vlist1,vlist2,cosine_similarity(v1,v2)

def process_list(data_list):
    n = len(data_list)
    ret_list = []
    for i in range(n-1):
        for j in range(i+1,n):
            t1,t2 = data_list[i],data_list[j]
            t = c_sim(t1,t2)
            if t: ret_list.append(t)
    return ret_list

data = [('188.74.64.243', '1', ['0, 1, 1, 0']),
('99.229.98.18',  '1', ['0, 1, 1, 1']),
('86.41.253.102', '1', ['1, 1, 1, 1']),
('188.74.64.243', '2', ['0, 1, 1, 0']),
('99.229.98.18',  '2', ['0, 1, 1, 1']),
('86.41.253.102', '2', ['1, 1, 1, 1'])]

for t in process_list(data): print(t)

Output:

('188.74.64.243', '99.229.98.18', '1', ['0, 1, 1, 0'], ['0, 1, 1, 1'], 0.8164965809277261)
('188.74.64.243', '86.41.253.102', '1', ['0, 1, 1, 0'], ['1, 1, 1, 1'], 0.7071067811865475)
('99.229.98.18', '86.41.253.102', '1', ['0, 1, 1, 1'], ['1, 1, 1, 1'], 0.8660254037844387)
('188.74.64.243', '99.229.98.18', '2', ['0, 1, 1, 0'], ['0, 1, 1, 1'], 0.8164965809277261)
('188.74.64.243', '86.41.253.102', '2', ['0, 1, 1, 0'], ['1, 1, 1, 1'], 0.7071067811865475)
('99.229.98.18', '86.41.253.102', '2', ['0, 1, 1, 1'], ['1, 1, 1, 1'], 0.8660254037844387)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM