In this article, we will explore three essential spaCy tricks that every developer should have in their toolkit to maximize processing speed and customize entity recognition.
# Introduction #
Thanks especially to contemporary large language models, natural language processing (NLP) is a fundamental pillar of modern AI and software systems. You'll find NLP techniques and technologies powering everything from search engines and chatbots to automated customer support routing and entity extraction pipelines. When it comes to production-grade NLP in Python,
spaCy Unfortunately, many developers treat spaCy as a simple black box monolith. They load a model, run it on text, and accept the default processing speeds and extraction limits. When scaling from a local prototype to processing millions of documents, these default configurations can become computational bottlenecks, leading to latency, bloated memory footprints, and missed domain-specific entities. In order to build high-performance text processing pipelines, you must understand how to optimize spaCy's internal execution flow.
In this article, we will explore three essential spaCy tricks that every developer should have in their toolkit to maximize processing speed and customize entity recognition: selective pipeline , parallel batch processing, and hybrid rule-based statistical entity recognition.
Before getting started, ensure you have spaCy installed, as well as its lightweight general-purpose English model:
pip install spacy
python -m spacy download en_core_web_sm
# 1. Selective Pipeline & Component Disabling #
By default, when you load a pre-trained spaCy model (such as en_core_web_sm
), spaCy initializes a complete NLP pipeline. This pipeline typically includes:
- a tokenizer
- a part-of-speech tagger (
tagger
) - a dependency parser (
parser
) - a lemmatizer (
lemmatizer
) - an attribute ruler (
attribute_ruler
) - a named entity recognizer (
ner
)
While this full default rich feature set is excellent, it comes with substantial computational overhead. If your application only needs to perform named entity recognition (NER), running the dependency parser and lemmatizer is a waste of CPU cycles and memory. Conversely, if you are only cleaning text and extracting lemmas, running the deep statistical NER model is highly inefficient. You can optimize this by selectively excluding components during , or temporarily disabling them during execution using a context manager.
This naive approach loads and runs every default component on the text, regardless of whether the components' outputs are actually used:
import spacy
import time
nlp = spacy.load("en_core_web_sm")
texts = ["Apple is looking at buying U.K. startup for $1 billion"] * 1000
start_time = time.time()
for text in texts:
doc = nlp(text)
entities = [(ent.text, ent.label_) for ent in doc.ents]
duration_full = time.time() - start_time
print(f"Full pipeline processed 1,000 docs in: {duration_full:.4f} seconds")
Output:
Full pipeline processed 1,000 docs in: 2.8540 seconds
Now let's optimize execution in two specific ways. First, we will be excluding heavy, unused components like the dependency parser at load time. Second, we will use nlp.select_pipes()
to temporarily disable components when processing specific workloads.
import spacy
import time
nlp_optimized = spacy.load("en_core_web_sm", exclude=["parser", "tagger"])
texts = ["Apple is looking at buying U.K. startup for $1 billion"] * 1000
start_time = time.time()
with nlp_optimized.select_pipes(disable=["attribute_ruler", "lemmatizer"]):
for text in texts:
doc = nlp_optimized(text)
entities = [(ent.text, ent.label_) for ent in doc.ents]
duration_opt = time.time() - start_time
print(f"Optimized pipeline processed 1,000 docs in: {duration_opt:.4f} seconds")
print(f"Speedup: {duration_full / duration_opt:.2f}x faster!")
Let's compare runtimes:
Full pipeline processed 1,000 docs in: 2.8739 seconds
Optimized pipeline processed 1,000 docs in: 1.7859 seconds
Speedup: 1.61x faster!
In the optimized example, passing exclude=["parser", "tagger"]
to spacy.load()
completely prevents these components from being loaded into memory. In an alternate method of reaching basically the same outcome, we passed disable=["attribute_ruler", "lemmatizer"]
to temporarily disabling their processing. The effect is that, when we process the text, spaCy skips token dependency analysis and part-of-speech tag labeling, which are mathematically expensive, and jumps straight to entity recognition. This results in a noticeable speedup with zero effect on NER accuracy, with even more noticeable advantages at greater scale.
# 2. High-Throughput Batch Processing with nlp.pipe & Metadata Propagation #
If you are iterating over a large corpus (e.g. pandas DataFrames, database rows, or raw text files), calling the nlp
object on individual strings in a loop (e.g. [nlp(text) for text in texts]
) is an anti-pattern.
Sequential processing prevents spaCy from optimizing memory buffers, grouping operations, and leveraging multi-core parallelization. Also, when processing text for database storage or ETL pipelines, you often need to carry metadata (like a record ID, timestamp, or category) through the NLP process so you can map the resulting entities back to the correct database rows.
The solution is to use nlp.pipe()
. This method processes documents as a stream, buffers them internally, and supports multi-processing. By setting as_tuples=True
, you can feed tuples of (text, context)
to spaCy. It will return (doc, context)
pairs, letting you pass metadata straight through the pipeline.
This naive approach runs processing sequentially and uses manual index tracking to align the resulting documents with their database IDs, which is brittle and slow:
import spacy
import time
nlp = spacy.load("en_core_web_sm", exclude=["parser", "tagger"])
records = [
{"id": f"DB-REC-{i}", "text": "Google was founded in September 1998 by Larry Page and Sergey Brin."}
for i in range(1000)
]
start_time = time.time()
extracted_data = []
for i, record in enumerate(records):
doc = nlp(record["text"])
entities = [(ent.text, ent.label_) for ent in doc.ents]
extracted_data.append({
"id": record["id"],
"entities": entities
})
duration_seq = time.time() - start_time
print(f"Sequential loop processed 1,000 docs in: {duration_seq:.4f} seconds")
Output:
Sequential loop processed 1,000 docs in: 2.7375 seconds
Here, we stream the data using nlp.pipe
, leveraging batch processing and multi-core parallelization (n_process
), while letting the database ID ride along as a context variable:
import spacy
import time
nlp = spacy.load("en_core_web_sm", exclude=["parser", "tagger"])
if __name__ == '__main__':
records = [
{"id": f"DB-REC-{i}", "text": "Google was founded in September 1998 by Larry Page and Sergey Brin."}
for i in range(1000)
]
start_time = time.time()
stream_input = [(rec["text"], rec["id"]) for rec in records]
extracted_data_pipe = []
docs_stream = nlp.pipe(stream_input, as_tuples=True, batch_size=256, n_process=-1)
for doc, rec_id in docs_stream:
entities = [(ent.text, ent.label_) for ent in doc.ents]
extracted_data_pipe.append({
"id": rec_id,
"entities": entities
})
duration_pipe = time.time() - start_time
print(f"nlp.pipe processed 1,000 docs in: {duration_pipe:.4f} seconds")
print(f"Speedup: {duration_seq / duration_pipe:.2f}x faster!")
Output:
nlp.pipe processed 1,000 docs in: 7.1310 seconds
In the optimized code snippet, we restructure the input dataset into a sequence of tuples: (text_string, metadata_context)
. When calling nlp.pipe(stream_input, as_tuples=True, batch_size=256, n_process=-1)
:
batch_size=256
tells spaCy to buffer and process texts in groups of 256, minimizing internal Python loop overheadn_process=-1
tells spaCy to automatically detect your system's CPU count and parallelize the tokenization and component extraction across all available coresas_tuples=True
instructs spaCy to yield pairs of(doc, context)
, ensuring the metadata (the record ID) remains perfectly aligned with the processed document without needing manual index arrays or list-alignment code
The astute reader will note that the processing time for the parallel batch processing code has actually increased over its predecessor. However, this is due to the overhead associated with setting up the parallel job, and the savings will become evident as the number of documents to process grows in number.
By re-running the same code excerpts above but with 10,000 records instead of 1,000, here are the results:
Sequential loop processed 1,000 docs in: 27.6733 seconds
nlp.pipe processed 1,000 docs in: 11.5444 seconds
You can see how the savings would continue to compound.
# 3. Hybrid Named Entity Recognition with EntityRuler #
Pre-trained statistical and transformer-based NER models are incredibly powerful for recognizing general entity types like ORG
, PERSON
, or DATE
based on context. However, models can frequently fail to recognize domain-specific terms (such as custom product SKUs, legacy code IDs, or highly niche medical terms) because they weren't exposed to them during training.
Fine-tuning a deep learning statistical model on custom entities is one solution, but it requires labeling thousands of sentences and runs the risk of "catastrophic forgetting," in which the model forgets how to recognize standard entities along the way.
A cleaner, highly efficient solution is a hybrid NER approach using spaCy's EntityRuler
. The EntityRuler
allows you to define patterns (using regular expressions or token-based dictionary dictionaries) and inject them directly into your pipeline. You can add it before the statistical NER — to pre-tag deterministic entities and help the model make context decisions — or after it — to act as a fallback or override.
Developers often try to patch statistical NER gaps by running regex on the text after running the spaCy pipeline, resulting in manual coordinate offset math and disconnected data structures:
import spacy
import re
nlp = spacy.load("en_core_web_sm")
text = "Please review system ticket ID: TKT-98421 on our corporate portal."
doc = nlp(text)
entities = [(ent.text, ent.label_) for ent in doc.ents]
print("Before post-process:", entities)
ticket_pattern = r"TKT-\d+"
matches = re.finditer(ticket_pattern, text)
custom_ents = []
for match in matches:
custom_ents.append((match.group(), "TICKET_ID"))
print("Regex entities:", custom_ents)
Output:
Before post-process: []
Regex entities: [('TKT-98421', 'TICKET_ID')]
By adding an EntityRuler
component directly to the pipeline, we merge rule-based regex patterns and statistical parsing into a single, unified doc.ents
output:
import spacy
nlp = spacy.load("en_core_web_sm")
ruler = nlp.add_pipe("entity_ruler", before="ner")
patterns = [
{"label": "TICKET_ID", "pattern": [{"TEXT": {"REGEX": "^TKT-\d+$"}}]},
{"label": "ORG", "pattern": "corporate portal"}
]
ruler.add_patterns(patterns)
text = "Please review system ticket ID: TKT-98421 on our corporate portal."
doc = nlp(text)
for ent in doc.ents:
print(f"Entity: {ent.text:<20} | Label: {ent.label_}")
Output:
Entity: TKT-98421 | Label: TICKET_ID
Entity: corporate portal | Label: ORG
In this hybrid implementation, we call nlp.add_pipe("entity_ruler", before="ner")
. The EntityRuler
acts as a native pipeline component. When the text is processed:
- The tokenizer splits the sentence into tokens.
- The
EntityRuler
runs first, identifying tokens that match our ticket regex pattern or exact dictionary strings and tagging them asTICKET_ID
orORG
. - The statistical
ner
component runs next. Because it sees that these tokens are already tagged as entities, it respects the tags (or adapts its predictions around them, avoiding conflicts).
This ensures that all entities, both learned statistical ones and deterministic rule-based ones, coexist cleanly within a single, cohesive Doc.ents
sequence, eliminating the need for brittle post-process sorting or offset adjustments.
# Wrapping Up #
Optimizing spaCy is about transitioning from default configurations to pipelines that respect your system resources and domain-specific requirements.
By adopting these three tricks, you can design highly efficient, production-grade text processing pipelines:
- Selective & component disabling eliminates unnecessary computation, accelerating your processing speed by up to 5x.
- Batch processing with
nlp.pipe
parallelizes execution across CPU cores, and settingas_tuples=True
propagates critical metadata without index-mapping bugs. - Hybrid NER with
EntityRuler
blends deterministic pattern-matching rules with general statistical inference, ensuring maximum extraction accuracy for custom domains without retraining.
Deploying these design patterns ensures that your NLP pipelines remain scalable, memory-efficient, and tailored to the unique vocabulary of your business data.
(
@mattmayo13KDnuggets&
Statology, and contributing editor at
Machine Learning Mastery, Matthew aims to make complex data science concepts accessible. His professional interests include natural language processing, language models, machine learning algorithms, and exploring emerging AI. He is driven by a mission to democratize knowledge in the data science community. Matthew has been coding since he was 6 years old.