首页 > 解决方案 > 稀疏向量的快速余弦相似度

问题描述

我有 Pandas 数据框,每行有一列带有稀疏向量。数据框还有一个索引,其中包含每个向量的字符串 id。我的目标是计算给定向量(输入是向量 id)和所有其他向量的 cosine_similarity。

import scipy
from sklearn.metrics.pairwise import cosine_similarity

cosine_similarity(df.at[input_id, 'vector'],  scipy.sparse.vstack(df['vector'].values))

这段代码可以工作,但是很慢,主要是因为 vstack。我能做些什么来加快这项工作?如果这会有所帮助,我不介意更改数据框格式和/或什至放弃 pandas 是对 raw numpy 的青睐。

数据框结构:

>df['vector'].values

array([<1x90000 sparse matrix of type '<class 'numpy.float32'>'
    with 55 stored elements in Compressed Sparse Row format>,
       <1x90000 sparse matrix of type '<class 'numpy.float32'>'
    with 54 stored elements in Compressed Sparse Row format>,
       <1x90000 sparse matrix of type '<class 'numpy.float32'>'
    with 78 stored elements in Compressed Sparse Row format>,
       ...,
       <1x90000 sparse matrix of type '<class 'numpy.float32'>'
    with 37 stored elements in Compressed Sparse Row format>,
       <1x90000 sparse matrix of type '<class 'numpy.float32'>'
    with 78 stored elements in Compressed Sparse Row format>,
       <1x90000 sparse matrix of type '<class 'numpy.float32'>'
    with 82 stored elements in Compressed Sparse Row format>], dtype=object)

标签: pythonpandasnumpyscipy

解决方案


推荐阅读