scispaCy

repository·main·Indexed 24 days ago

https://github.com/allenai/scispacy

A library of custom pipes and models for processing scientific and biomedical documents using spaCy. It provides specialized tokenization, POS tagging, syntactic parsing, and NER models, including full pipelines (en_core_sci_sm, md, lg, scibert) and specialized NER models (CRAFT, JNLPBA, BC5CDR, BIONLP13CG). Key features include the AbbreviationDetector for identifying biomedical abbreviations, the EntityLinker for linking entities to knowledge bases like UMLS, MeSH, RxNorm, GO, and HPO, and the HyponymDetector for extracting Hearst patterns.

Tokens
9.3K
Snippets
16
Records
60
Agent score
84%

What's inside scispacy

  1. Extend scispaCy with external databases using pyobo

    main

    You can load arbitrary databases and ontologies into scispaCy by integrating with pyobo. This allows you to use the EntityLinker logic with external identifiers like HGNC.

    Requirements:

    • pip install "pyobo>=0.12.9"

    Use pyobo.get_scispacy_entity_linker(database_name, ...) to create a linker instance that can be used directly as a spaCy component.

    import pyobo
    import spacy
    from scispacy.linking import EntityLinker
    from tabulate import tabulate
    
    # Create a linker for the HGNC database
    linker: EntityLinker = pyobo.get_scispacy_entity_linker("hgnc", filter_for_definitions=False)
    
    # Use it with a standard spaCy model
    nlp = spacy.load("en_core_web_sm")
    
    text = "RAC(Rho family)-alpha serine/threonine-protein kinase is an enzyme that in humans is encoded by the AKT1 gene."
    
    # Apply the linker to the doc
    doc = linker(nlp(text))
    
    # Process results
    rows = [
        (
            span,
            span.start_char,
            span.end_char,
            f"[{identifier}](https://bioregistry.io/{identifier})",
            score,
        )
        for span in doc.ents
        for identifier, score in span._.kb_ents
    ]
    print(tabulate(rows, headers=["text", "start", "end", "prefix", "identifier"], tablefmt="github"))
  2. Install scispaCy and its models

    main
    Installing scispaCy is a two-step process: first, install the library itself, and then install a specific model. scispaCy requires Python 3.6 or greater. It is highly recommended to use an isolated environment like virtualenv or conda.
  3. Install scispaCy and biomedical models

    main

    To use scispaCy, you must install the base package via pip and then install a specific model using its direct URL.

    Example installation:

    pip install scispacy
    pip install <Model URL>
    pip install scispacy
    pip install <Model URL>
  4. Understand the KnowledgeBase structure

    main

    A KnowledgeBase object maintains two primary internal mappings used for entity linking:

    1. cui_to_entity: A mapping from local unique identifiers (like CUIs) to the full Entity object.
    2. alias_to_cuis: A mapping from aliases (including canonical names) to a set of unique identifiers for which those aliases are valid.
  5. Add the hyponym_detector to a spaCy pipeline

    main

    The HyponymDetector is a spaCy pipe that detects hyponyms (specific terms) and hypernyms (general terms) using Hearst patterns. You can add it to an existing spaCy Language object using nlp.add_pipe.

    When added, it populates the custom attribute Doc._.hearst_patterns with a list of tuples. Each tuple contains:

    • The matching predicate (string)
    • The extracted hypernym (Span)
    • The extracted hyponym (Span)

    By default, it uses BASE_PATTERNS. You can enable EXTENDED_PATTERNS via the configuration.

    # add the hyponym detector
    nlp.add_pipe('hyponym_detector', config={'extended': True}, last=True)
  6. Load a scispaCy model in Python

    main

    Once a model is installed via pip, you can load it using the standard spacy.load() method, just like any other spaCy model.

    import spacy
    
    # Load the installed model
    nlp = spacy.load("en_core_sci_sm")
    
    # Process text
    doc = nlp("Alterations in the hypocretin receptor 2 and preprohypocretin genes produce narcolepsy in some animals.")
  7. Example usage of scispaCy for biomedical text processing

    main

    You can use scispaCy by loading a model with spacy.load() and processing text. The models provide sentence segmentation, mention detection (general spans that might be entities in UMLS), and dependency parsing.

    Note: The mention detector in scispaCy models is more general than standard spaCy NER; it may include verbs or other spans that are potential biomedical entities.

  8. Use the AbbreviationDetector to identify biomedical abbreviations

    main

    The AbbreviationDetector is a spaCy component that implements the Schwartz & Hearst (2003) algorithm to identify abbreviation definitions in biomedical text.

    Once added to the pipeline, you can access identified abbreviations via the doc._.abbreviations attribute. For each abbreviation, the long form (a spacy.tokens.Span) can be accessed using the span._.long_form attribute.

    Note: To ensure doc objects can be serialized (saved and loaded), initialize the pipe with make_serializable=True in the config.

    import spacy
    from scispacy.abbreviation import AbbreviationDetector
    
    nlp = spacy.load("en_core_sci_sm")
    
    # Add the abbreviation pipe to the spacy pipeline.
    nlp.add_pipe("abbreviation_detector")
    
    doc = nlp("Spinal and bulbar muscular atrophy (SBMA) is an inherited motor neuron disease...")
    
    print("Abbreviation", "\t", "Definition")
    for abrv in doc._.abbreviations:
    	print(f"{abrv} \t ({abrv.start}, {abrv.end}) {abrv._.long_form}")
  9. Use the HyponymDetector to extract Hearst patterns

    main

    The HyponymDetector implements the Hearst patterns algorithm to identify hyponymy relations (e.g., "X such as Y").

    It populates the doc._.hearst_patterns attribute with a list of tuples containing:

    1. The relation rule used (str)
    2. The more general concept (spacy.Span)
    3. The more specific concept (spacy.Span)

    Configuration:

    • extended (bool, default False): If True, uses an extended set of patterns which increases recall but may decrease precision (e.g., including "X similar to Y").
    import spacy
    from scispacy.hyponym_detector import HyponymDetector
    
    nlp = spacy.load("en_core_sci_sm")
    nlp.add_pipe("hyponym_detector", last=True, config={"extended": False})
    
    doc = nlp("Keystone plant species such as fig trees are good for the soil.")
    
    print(doc._.hearst_patterns)
    # Output: [('such_as', Keystone plant species, fig trees)]
  10. Use the EntityLinker to link entities to knowledge bases

    main

    The EntityLinker (added via scispacy_linker) performs string overlap-based searches (char-3grams) to link named entities to concepts in a knowledge base. It sets the ._.kb_ents attribute on spaCy Spans, which contains a list of (concept_id, score) tuples.

    Supported Linkers (v2.5.0):

    • umls: Unified Medical Language System (~3M concepts).
    • mesh: Medical Subject Headings (~30k entities).
    • rxnorm: RxNorm ontology (~100k clinical drug concepts).
    • go: Gene Ontology (~67k gene function concepts).
    • hpo: Human Phenotype Ontology (~16k phenotypic abnormality concepts).

    Configuration Options:

    • resolve_abbreviations (bool, default False): If True, the linker uses the long form of abbreviations identified by an AbbreviationDetector in the pipeline. This requires the detector to be added before the linker.
    • k (int, default 30): Number of nearest neighbors to look up per mention.
    • threshold (float, default 0.7): Minimum score for a candidate to be added.
    • no_definition_threshold (float, default 0.95): Threshold for candidates without a definition.
    • filter_for_definitions (bool, default True): Only return entities that have definitions in the KB.
    • max_entities_per_mention (int, default 5): Maximum entities returned per mention.

    You can look up entity details using the linker's kb attribute: linker.kb.cui_to_entity[concept_id].

    import spacy
    import scispacy
    from scispacy.linking import EntityLinker
    
    nlp = spacy.load("en_core_sci_sm")
    
    # Note: resolve_abbreviations requires AbbreviationDetector to be in the pipeline
    nlp.add_pipe("scispacy_linker", config={"resolve_abbreviations": True, "linker_name": "umls"})
    
    doc = nlp("Spinal and bulbar muscular atrophy (SBMA) is an inherited motor neuron disease...")
    
    # Accessing linked entities
    entity = doc.ents[1]
    linker = nlp.get_pipe("scispacy_linker")
    for umls_ent in entity._.kb_ents:
    	print(linker.kb.cui_to_entity[umls_ent[0]])
  11. Configure AbbreviationDetector serialization

    main

    When initializing AbbreviationDetector, you can set the make_serializable parameter. If set to True, the detector will convert the Doc._.abbreviations list into a list of dictionaries instead of spaCy Span objects. This is useful for enabling multiprocessing, as standard spaCy Spans cannot always be easily serialized across process boundaries.

    The resulting dictionary for each abbreviation contains:

    • short_text: The text of the abbreviation.
    • short_start: The start token index of the abbreviation.
    • short_end: The end token index of the abbreviation.
    • long_text: The text of the long form.
    • long_start: The start token index of the long form.
    • long_end: The end token index of the long form.