如何将列表python计算成矩阵相似度

时间:2016-03-31 23:05:20

标签: python numpy scipy

我的数据存在问题

我从数据库中读取数据使用python,让我们说分配给变量data

type(data)list,实际上是list of list

data = [(1, 'Shirt', 2),(1, 'Pants', 3),(2, 'Top', 2),(2, 'Shirt', 1),(2, 'T-Shirt', 4), (3, 'Shirt', 3),(3, 'T-Shirt', 2)]

data[0][0] is unique_id以及data[0][1] is category_productdata[0][2] is count

我需要根据unique_id

使用余弦相似度(我计划使用scipy)计算category_product 1和2之间的相似度
  • unique_id不仅仅是两个,也可能超过2个

我想我需要将data转换为矩阵:

unique_id | Shirt | Pants | Top | T-Shirt
1 | 2 | 3 | 0 | 0 
2 | 1 | 0 | 2 | 4
3 | 3 | 0 | 0 | 2

我想用余弦相似度计算这个矩阵,输出是:

1,2,0.121045506534
1,3,0.461538461538
2,3,0.665750285936
  • Sim(1,2) = 0.121045506534

我怎么能用python做到这一点?

THX

1 个答案:

答案 0 :(得分:1)

import pandas as pd
from scipy import spatial
from itertools import combinations

df = pd.DataFrame(data, columns=['unique_id', 'category_product', 'count'])

pt = df.pivot(index='unique_id', columns='category_product', values='count').fillna(0)

>>> pt
category_product  Pants  Shirt  T-Shirt  Top
unique_id                                   
1                     3      2        0    0
2                     0      1        4    2
3                     0      3        2    0

combos = combinations(pt.index, 2)
>>> [(a, b, 1 - spatial.distance.cosine(pt.ix[a].values, pt.ix[b].values)) 
     for a, b in combos]
[(1, 2, 0.12104550653376045),
 (1, 3, 0.46153846153846168),
 (2, 3, 0.66575028593568275)]
相关问题