为文本检索提供极速Python BM25实现
BM25S为基于Python的文本检索排名函数,使用Scipy稀疏矩阵实现快速响应。其性能显著优于传统库,支持多种BM25变体,提供灵活API及Hugging Face集成,适合大规模数据的内存效率处理。
BM25S 是一个用纯 Python 实现的超快速的 BM25 算法库,依托于 Scipy 稀疏矩阵技术来提升性能。BM25 是文本检索任务中使用广泛的排序函数,也是像 Elasticsearch 这样的搜索服务的核心组件。
BM25S 以以下两大特点闻名:
安装 BM25S
用户可以通过下面的命令来安装 BM25S:
pip install bm25s
对于更好的检索结果,用户还可以安装词干 化工具:
pip install bm25s[full] pip install PyStemmer pip install jax[cpu]
快速开始
下面是一个简短的例子,展示如何使用 BM25S 来检索文本:
import bm25s import Stemmer corpus = [ "a cat is a feline and likes to purr", "a dog is the human's best friend and loves to play", "a bird is a beautiful animal that can fly", "a fish is a creature that lives in water and swims", ] stemmer = Stemmer.Stemmer("english") corpus_tokens = bm25s.tokenize(corpus, stopwords="en", stemmer=stemmer) retriever = bm25s.BM25() retriever.index(corpus_tokens) query = "does the fish purr like a cat?" query_tokens = bm25s.tokenize(query, stemmer=stemmer) results, scores = retriever.retrieve(query_tokens, corpus=corpus, k=2) for i in range(results.shape[1]): doc, score = results[0, i], scores[0, i] print(f"Rank {i+1} (score: {score:.2f}): {doc}")
BM25S 提供了高度灵活的 API,用户可以根据需要自定义 BM25 模型和标记化过程。例如,可以使用自定义的停用词列表或词干化功能来优化检索结果。
BM25S 具有内存高效的设计,支持使用内存映射文件来保存 BM25 索引,从而在不加载完整索引的情况下检索文档。这在需要处理非常大的索引时特别有用。
BM25S 支持多种 BM25 的变种,包括原始实现、ATIRE、BM25L、BM25+ 和 Lucene 版本。用户可以根据具体需求选择合适的实现方法。
BM25S 可以与 Hugging Face 公共模型仓库完美集成,让用户可以方便地共享 BM25 索引并使用社区提供的模型。
在性能测试中,BM25S 显示出显著的速度优势,在各种数据集上的每秒查询数 (QPS) 高于其他流行 BM25 实现。
BM25S 的中心思想和许多功能从一开始便受到了其他相关项目的启发,包括 bm25_pt 和 rank-bm25,包含多语言停用词列表的灵感来自 NLTK,及 numba 的实现受到 kiwa 和 retriv 大力支持。
欢迎对 BM25S 感兴趣的用户下载、使用,并将其应用于自己的工作,大大提升文档检索效率。请在您的工作中引用 BM25S。