KeyBERT Documentation

repository·master·Indexed 26 days ago

https://github.com/maartengr/keybert

KeyBERT is a minimal keyword extraction technique that leverages BERT embeddings to find sub-phrases in a document most similar to the document itself using cosine similarity. It supports various embedding backends including Sentence-Transformers, Flair, Spacy, Gensim, and USE. The library provides features for diversifying results via Max Sum Distance and Maximal Marginal Relevance (MMR), as well as LLM-based extraction through KeyLLM with support for OpenAI and LiteLLM.

Tokens
13.3K
Snippets
37
Records
57
Agent score
87%

What's inside KeyBERT

  1. Create keywords using KeyLLM

    master

    Use KeyLLM to generate keywords that do not necessarily need to appear in the input documents. This process asks the LLM to come up with keywords based on the document content.

    First, install the required LLM provider (e.g., openai):

    pip install openai

    Then, initialize the OpenAI wrapper and pass it to KeyLLM.

    import openai
    from keybert.llm import OpenAI
    from keybert import KeyLLM
    
    # Create your LLM
    client = openai.OpenAI(api_key=MY_API_KEY)
    llm = OpenAI(client)
    
    # Load it in KeyLLM
    kw_model = KeyLLM(llm)
    
    # Extract keywords
    keywords = kw_model.extract_keywords(documents)
  2. Basic Keyword and Keyphrase Extraction with KeyBERT

    master

    Use the KeyBERT.extract_keywords() method to extract keywords from a document.

    Key parameters:

    • keyphrase_ngram_range: A tuple defining the (min, max) length of N-grams. Use (1, 1) for single words and (1, 2) or higher for keyphrases.
    • stop_words: Specify stop words (e.g., 'english') to filter results.
    • highlight: Set to True to highlight the extracted keywords in the original document text.

    Recommended models:

    • English: all-MiniLM-L6-v2
    • Multilingual: paraphrase-multilingual-MiniLM-L12-v2
    from keybert import KeyBERT
    
    doc = """
             Supervised learning is the machine learning task of learning a function that
             maps an input to an output based on example input-output pairs. It infers a
             function from labeled training data consisting of a set of training examples.
             In supervised learning, each example is a pair consisting of an input object
             (typically a vector) and a desired output value (also called the supervisory signal).
             A supervised learning algorithm analyzes the training data and produces an inferred function,
             which can be used for mapping new examples. An optimal scenario will allow for the
             algorithm to correctly determine the class labels for unseen instances. This requires
             the learning algorithm to generalize from the training data to unseen situations in a
             'reasonable' way (see inductive bias).
          ""
    kw_model = KeyBERT()
    
    # Extract single words
    keywords = kw_model.extract_keywords(doc, keyphrase_ngram_range=(1, 1), stop_words=None)
    
    # Extract keyphrases
    keyphrases = kw_model.extract_keywords(doc, keyphrase_ngram_range=(1, 2), stop_words=None)
    
    # Highlight keywords
    highlighted_doc = kw_model.extract_keywords(doc, highlight=True)
  3. Use Model2Vec for fast embeddings

    master

    Model2Vec provides high-speed embedding models. You can use it by passing a StaticModel to KeyBERT.

    To use a pre-trained StaticModel:

    from keybert import KeyBERT
    from model2vec import StaticModel
    
    embedding_model = StaticModel.from_pretrained("minishlab/potion-base-8M")
    kw_model = KeyBERT(embedding_model)

    To distill a sentence-transformers model with the vocabulary of your documents (recommended for large datasets):

    from keybert.backend import Model2VecBackend
    
    embedding_model = Model2VecBackend("sentence-transformers/all-MiniLM-L6-v2", distill=True)

    Tip: For a lightweight installation without sentence-transformers, use: pip install keybert --no-deps scikit-learn model2vec

    from keybert import KeyBERT
    from model2vec import StaticModel
    
    embedding_model = StaticModel.from_pretrained("minishlab/potion-base-8M")
    kw_model = KeyBERT(embedding_model)
  4. Speed up KeyBERT inference

    master

    To improve performance, follow these two methods:

    1. Use a GPU: Since KeyBERT uses large language models, a GPU is preferred for significantly faster inference.
    2. Batch processing: Instead of iterating through a list of documents and calling extract_keywords on each one individually, pass the entire list to extract_keywords at once. This allows words to be embedded only once, resulting in a major speedup.
    from keybert import KeyBERT
    
    kw_model = KeyBERT()
    
    # FASTER: Pass the entire list at once
    keywords = kw_model.extract_keywords(my_list_of_documents)
  5. Use OpenAI with KeyLLM

    master

    To use OpenAI's external API with KeyLLM, install the openai package, initialize an openai.OpenAI client, and wrap it using keybert.llm.OpenAI. You can use standard models or chat-based models by setting chat=True and specifying a model like gpt-3.5-turbo.

    import openai
    from keybert.llm import OpenAI
    from keybert import KeyLLM
    
    # For standard models
    client = openai.OpenAI(api_key=MY_API_KEY)
    llm = OpenAI(client)
    
    # For chat-based models
    client = openai.OpenAI(api_key=MY_API_KEY)
    llm = OpenAI(client, model="gpt-3.5-turbo", chat=True)
    
    # Load it in KeyLLM
    kw_model = KeyLLM(llm)
    keywords = kw_model.extract_keywords(MY_DOCUMENTS)
  6. Use CountVectorizer with KeyBERT

    master

    KeyBERT uses CountVectorizer to split documents into candidate keywords or keyphrases. Since splitting occurs after embedding, you can customize the vectorizer to change how candidates are parsed without affecting embedding quality. You can pass a CountVectorizer instance to the extract_keywords method.

    from keybert import KeyBERT
    from sklearn.feature_extraction.text import CountVectorizer
    
    doc = "Your document text here"
    kw_model = KeyBERT()
    vectorizer = CountVectorizer()
    keywords = kw_model.extract_keywords(doc, vectorizer=vectorizer)
    from keybert import KeyBERT
    from sklearn.feature_extraction.text import CountVectorizer
    
    doc = """
             Supervised learning is the machine learning task of learning a function that
             maps an input to an output based on example input-output pairs.[1] It infers a
             function from labeled training data consisting of a set of training examples.[2]
             In supervised learning, each example is a pair consisting of an input object
             (typically a vector) and a desired output value (also called the supervisory signal).
             A supervised learning algorithm analyzes the training data and produces an inferred function,
             which can be used for mapping new examples. An optimal scenario will allow for the
             algorithm to correctly determine the class labels for unseen instances. This requires
             the learning algorithm to generalize from the training data to unseen situations in a
             'reasonable' way (see inductive bias).
          ""
    kw_model = KeyBERT()
    vectorizer = CountVectorizer()
    keywords = kw_model.extract_keywords(doc, vectorizer=vectorizer)
  7. Use LiteLLM with KeyLLM

    master

    LiteLLM allows you to use various closed-source LLMs with KeyLLM. Install litellm and use the keybert.llm.LiteLLM class, passing the model name as a string. Ensure the appropriate API keys are set in your environment variables (e.g., OPENAI_API_KEY).

    pip install litellm
    import os
    from keybert.llm import LiteLLM
    from keybert import KeyLLM
    
    # Select LLM
    os.environ["OPENAI_API_KEY"] = "sk-..."
    llm = LiteLLM("gpt-3.5-turbo")
    
    # Load it in KeyLLM
    kw_model = KeyLLM(llm)
  8. Use Spacy for embeddings

    master

    Spacy models can be used as embedding backends. It is recommended to exclude unnecessary components like tagger, parser, etc., to save resources.

    To use a standard Spacy model:

    import spacy
    
    nlp = spacy.load("en_core_web_md", exclude=['tagger', 'parser', 'ner', 'attribute_ruler', 'lemmatizer'])
    kw_model = KeyBERT(model=nlp)

    To use a Spacy transformer model (_trf):

    import spacy
    
    spacy.prefer_gpu()
    nlp = spacy.load("en_core_web_trf", exclude=['tagger', 'parser', 'ner', 'attribute_ruler', 'lemmatizer'])
    kw_model = KeyBERT(model=nlp)

    If you encounter memory issues with transformer models, configure the GPU allocator:

    import spacy
    from thinc.api import set_gpu_allocator, require_gpu
    
    nlp = spacy.load("en_core_web_trf", exclude=['tagger', 'parser', 'ner', 'attribute_ruler', 'lemmatizer'])
    set_gpu_allocator("pytorch")
    require_gpu(0)
    
    kw_model = KeyBERT(model=nlp)
    import spacy
    
    nlp = spacy.load("en_core_web_md", exclude=['tagger', 'parser', 'ner', 'attribute_ruler', 'lemmatizer'])
    kw_model = KeyBERT(model=nlp)
  9. Extract keywords using Large Language Models (KeyLLM)

    master

    Use KeyLLM to perform keyword extraction via LLMs (e.g., OpenAI).

    Setup:

    1. Install the OpenAI package: pip install openai.
    2. Create an OpenAI client.
    3. Wrap the client in keybert.llm.OpenAI.
    4. Initialize KeyLLM with the LLM object.

    Efficient Extraction: To avoid redundant LLM calls, you can provide document embeddings and a threshold. KeyLLM will only query the LLM for documents that are sufficiently different from previously processed ones.

    Parameters for extract_keywords in KeyLLM:

    • embeddings: Pre-computed embeddings for the documents.
    • threshold: Similarity threshold to decide if documents should share the same keywords.
    import openai
    from keybert.llm import OpenAI
    from keybert import KeyLLM
    from sentence_transformers import SentenceTransformer
    
    # 1. Basic LLM Extraction
    client = openai.OpenAI(api_key=MY_API_KEY)
    llm = OpenAI(client)
    kw_model = KeyLLM(llm)
    keywords = kw_model.extract_keywords(doc)
    
    # 2. Efficient Extraction with Embeddings
    model = SentenceTransformer('all-MiniLM-L6-v2')
    embeddings = model.encode(MY_DOCUMENTS, convert_to_tensor=True)
    
    kw_model = KeyLLM(llm)
    keywords = kw_model.extract_keywords(MY_DOCUMENTS, embeddings=embeddings, threshold=.75)
  10. Use KeyBERT with Chinese documents

    master

    To support Chinese documents, you must provide a tokenizer that supports Chinese tokenization, such as jieba.

    1. Install jieba.
    2. Define a tokenization function using jieba.lcut.
    3. Pass a CountVectorizer configured with that tokenizer to the extract_keywords method via the vectorizer parameter.
    from keybert import KeyBERT
    from sklearn.feature_extraction.text import CountVectorizer
    import jieba
    
    def tokenize_zh(text):
        words = jieba.lcut(text)
        return words
    
    vectorizer = CountVectorizer(tokenizer=tokenize_zh)
    kw_model = KeyBERT()
    keywords = kw_model.extract_keywords(doc, vectorizer=vectorizer)
  11. Use Cohere with KeyLLM

    master

    To use Cohere's external API, install the cohere package, initialize a cohere.Client, and wrap it using keybert.llm.Cohere.

    import cohere
    from keybert.llm import Cohere
    from keybert import KeyLLM
    
    co = cohere.Client(my_api_key)
    llm = Cohere(co)
    
    # Load it in KeyLLM
    kw_model = KeyLLM(llm)
    keywords = kw_model.extract_keywords(MY_DOCUMENTS)
  12. Extract keywords present in text using KeyLLM

    master

    To ensure the LLM only extracts keywords that actually appear in the source text, use a custom prompt and set check_vocab=True in the extract_keywords method.

    import openai
    from keybert.llm import OpenAI
    from keybert import KeyLLM
    
    # Create your LLM with a custom prompt
    prompt = """
    I have the following document:
    [DOCUMENT]
    
    Based on the information above, extract the keywords that best describe the topic of the text.
    Make sure to only extract keywords that appear in the text.
    Use the following format separated by commas:
    <keywords>
    """
    client = openai.OpenAI(api_key=MY_API_KEY)
    llm = OpenAI(client)
    
    # Load it in KeyLLM
    kw_model = KeyLLM(llm)
    
    # Extract keywords with check_vocab=True
    keywords = kw_model.extract_keywords(documents, check_vocab=True)