Python sklearn TfidfVectorizer : Vectorize documents ahead of query for semantic search

标签 python vectorization tfidfvectorizer

我想使用 TF-IDF 运行语义搜索。

此代码可以工作,但在大型文档语料库上使用时速度非常慢:

search_terms = "my query"
documents = ["my","list","of","docs"]

vectorizer = TfidfVectorizer()
doc_vectors = vectorizer.fit_transform([search_terms] + documents)
cosine_similarities = linear_kernel(doc_vectors[0:1], doc_vectors).flatten()
document_scores = [item.item() for item in cosine_similarities[1:]]

看起来效率很低:

每个新的搜索查询都会触发整个语料库的重新矢量化。

我想知道如何提前完成语料库矢量化的大量工作,并将结果保存在“索引文件”中。因此,当我运行查询时,唯一要做的就是对查询中的几个单词进行向量化,然后计算相似度。

我尝试分别矢量化查询和文档:

vec_docs = vectorizer.fit_transform(documents)
vec_query = vectorizer.fit_transform([search_terms])

cosine_similarities = linear_kernel(vec_query, vec_docs).flatten()

但它给了我这个错误:

ValueError: Incompatible dimension for X and Y matrices: X.shape[1] == 3 while Y.shape[1] == 260541

如何在不知道查询是什么的情况下提前运行语料库矢量化?

我的主要目标是通过提前进行大量数据处理,即使在处理大量文档(例如,几 GB 的文本)的情况下,即使在低功率服务器上,也能获得极快的结果.

最佳答案

TF/IDF 向量是高维且稀疏的。支持它的基本数据结构是 inverted index 。您可以自己实现它或使用标准索引(例如 Lucene )。

尽管如此,如果您想尝试现代基于深度神经的向量表示,请查看以下内容 semantic search demo 。它使用可以处理数十亿个向量的相似性搜索服务。

(请注意,我是该演示的共同作者。)

关于Python sklearn TfidfVectorizer : Vectorize documents ahead of query for semantic search,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68003003/

相关文章:

python - 查找网格交点的像素坐标

python - 构建 python 项目的非常*简单*的方法是什么?

python - 使用 python 清理凌乱的 CSV,保存在 Excel 中

r - 使用 XTS 查找早于特定时间戳的最新观察

nlp - 如何在 Python 中对文本使用双正态分离

python - 为什么 TfidVectorizer.fit_transform() 会更改我的文本数据的样本和标签数量?

python - 使用 bash 文件运行两个 python 脚本

python-3.x - torch 错误 "RuntimeError: index out of range: Tried to access index 512 out of table with 511 rows"

python : Vectorized conditional sum along a axis

python - nlp 多标签分类 tf 与 tfidf