rank_bm25 Documentation

repository·master·Indexed 23 days ago

https://github.com/dorianbrown/rank_bm25

A lightweight Python library providing BM25 implementations, including Okapi, BM25L, and BM25+, for querying document sets. It features methods like get_scores() for relevance scoring and get_top_n() for retrieving the most relevant documents from a tokenized corpus.

Tokens
579
Snippets
4
Records
5
Agent score
30%

What's inside rank_bm25

  1. Initialize BM25Okapi with a corpus

    master

    To use the library, you must first create an instance of a BM25 class (such as BM25Okapi). The class requires a tokenized_corpus, which must be a list of lists of strings (each inner list containing the tokens for a single document).

    Important: This package does not perform any automatic text preprocessing. You are responsible for tasks such as lowercasing, stopword removal, and stemming. You must apply the exact same preprocessing to both your corpus and your queries to ensure consistent results.

    from rank_bm25 import BM25Okapi
    
    corpus = [
        "Hello there good man!",
        "It is quite windy in London",
        "How is the weather today?"
    ]
    
    tokenized_corpus = [doc.split(" ") for doc in corpus]
    
    bm25 = BM25Okapi(tokenized_corpus)
  2. Get document scores using get_scores()

    master

    Once initialized, you can use get_scores() to retrieve relevance scores for every document in your corpus relative to a tokenized query. The query must be tokenized using the same method used for the corpus.

    query = "windy London"
    tokenized_query = query.split(" ")
    
    doc_scores = bm25.get_scores(tokenized_query)
    # Returns an array of scores, e.g., array([0.        , 0.93729472, 0.        ])
  3. Retrieve top documents using get_top_n()

    master
    If you want to skip manual score processing and directly retrieve the most relevant documents, use get_top_n(). This method requires the tokenized query, the original corpus (to return the actual text), and the number of documents n to retrieve.