python - 稀疏向量的快速余弦相似度
问题描述
我有 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)
解决方案
推荐阅读
- java - 如何从改造中成功登录 API 的字符串格式获取数据?
- graphql - Shopify Storefront API:使用 GraphQL 获取引用的变体
- c# - OWIN 身份验证成功,但 User.Identity.IsAuthenticated 为 false
- azure - 如何在 Azure 门户中创建对所有订阅中的所有资源具有只读访问权限的用户?
- r - 删除 Data.Table 中所有 NA 或 R 中 DPLYR 的组
- php - 如何在 Laravel 6 中上传图片并获取其 url
- date - Kotlin:获取两个日期之间的差异(现在和以前的日期)
- vba - 未设置对象变量 - 为什么未返回此 Dictionary 对象?
- .net - 如何在 VSTO 的“另存为”对话框中选择目录而不是文件?
- vue.js - 对 vue.js 中的每个子路由使用 v-if