Sub topic 6
Detecting names and places with NER
Regular expressions work for identifiers that have a fixed shape, such as emails and card numbers. Names and places have no fixed shape. "Jordan" can be a person, a country, or a shoe brand, and only the surrounding words tell you which. Named-entity recognition (NER) is the standard tool for this job.
This chapter assumes you have read the earlier chapters on regex detection and checksums. It also assumes basic Python and the idea of a span, a (start, end, label) tuple. By the end you should be able to run an NER model, convert its output into spans, set a confidence threshold, and predict where it will fail.
What NER does
NER is a task in which a model reads text and marks stretches of it as belonging to categories such as person, location, or organization. Each marked stretch is an entity. For redaction, an entity is a span you may need to replace.
Most modern NER models work at the token level. A token is a word or word piece produced by a tokenizer. The model assigns each token a tag, and a post-processing step merges neighboring tags into spans.
A common tagging scheme is BIO:
| Tag | Meaning | Example token |
|---|---|---|
| `B-PER` | Beginning of a person entity | "John" |
| `I-PER` | Inside (continuing) a person entity | "Smith" |
| `B-LOC` | Beginning of a location entity | "Berlin" |
| `O` | Outside any entity | "lives" |
The sentence "John Smith lives in Berlin" is tagged B-PER I-PER O O B-LOC. The merge step joins B-PER and I-PER into one span covering "John Smith".
Why NER differs from regex
NER is statistical. The model learned from labelled examples, so it makes guesses based on context. This has three consequences for a redaction system.
- It generalizes. It can find names it has never seen, such as "Oluwaseun Adeyemi", because the context ("Dear ...", "my colleague ...") suggests a person.
- It makes mistakes you cannot enumerate. A regex fails in ways you can read from the pattern. An NER model fails in ways you find only by testing.
- Its output depends on the text around the entity. The same string can be tagged in one sentence and missed in another.
The model also needs more compute than a regex. A small model runs in milliseconds per short text on a CPU. A transformer model is slower and may need a GPU for high traffic.
Running a pretrained NER model with spaCy
spaCy ships small pretrained pipelines that include an NER component. The en_core_web_sm model is quick to load and suits experiments. Larger models such as en_core_web_lg and transformer-based pipelines are generally more accurate.
The code below loads the model, runs it, and converts entities to the span shape used in the rest of this tutorial. It keeps only the labels relevant to personal data.
# pip install spacy
# python -m spacy download en_core_web_sm
import spacy
nlp = spacy.load("en_core_web_sm")
# spaCy label -> the label used in our own pipeline
LABEL_MAP = {
"PERSON": "PERSON",
"GPE": "LOCATION", # countries, cities, states
"LOC": "LOCATION", # mountains, bodies of water, regions
"FAC": "LOCATION", # buildings, airports, highways
"ORG": "ORGANIZATION",
}
def find_entities(text):
doc = nlp(text)
return [
(ent.start_char, ent.end_char, LABEL_MAP[ent.label_])
for ent in doc.ents
if ent.label_ in LABEL_MAP
]
text = "Maria Lopez flew from Madrid to Toronto to visit Shopify."
for start, end, label in find_entities(text):
print(start, end, label, repr(text[start:end]))The output lists each entity with its character offsets. The exact entities depend on the model version, but you would typically expect "Maria Lopez" as PERSON and "Madrid" and "Toronto" as LOCATION.
Three details in this code matter.
- Character offsets, not token offsets.
ent.start_charandent.end_charindex into the original string, which is whatredactfrom the earlier chapter needs.ent.startandent.endindex tokens and would give wrong results. - A label map. spaCy's label set was designed for general text, not privacy. Mapping it to your own labels keeps the rest of the pipeline independent of the model you chose.
- A filter. spaCy also reports
DATE,MONEY,CARDINAL, and other labels. Redacting all of them would destroy useful content. Choose the labels that count as personal data in your application.
Choosing which labels to redact
The label map is a policy decision. Consider each label against your use case.
| NER label | Usually redact? | Reason |
|---|---|---|
| Person | Yes | A direct identifier in most contexts. |
| City or address-like place | Often | A quasi-identifier. It can identify someone when combined with other details. |
| Country | Often not | Too coarse to identify one person, and often needed for the task. |
| Organization | Depends | A company name is not personal data, but "my employer, Acme" can narrow down a person. |
| Public figure | Depends | Redacting "Albert Einstein" in a physics question harms the answer. |
A model cannot tell whether "Paris" in a travel question is sensitive. Your policy has to decide, and it is better to make the choice explicit in the label map than to inherit it from model defaults.
Getting confidence scores with a transformer model
spaCy's default entity output has no confidence score. If you want to trade recall for precision, use a model that exposes scores. The Hugging Face transformers library provides a token-classification pipeline. Setting aggregation_strategy="simple" merges word pieces into whole entities and returns a score for each.
# pip install transformers torch
from transformers import pipeline
ner = pipeline(
"token-classification",
model="dslim/bert-base-NER",
aggregation_strategy="simple",
)
LABEL_MAP = {"PER": "PERSON", "LOC": "LOCATION", "ORG": "ORGANIZATION"}
def find_entities(text, min_score=0.85):
spans = []
for ent in ner(text):
label = LABEL_MAP.get(ent["entity_group"])
if label and ent["score"] >= min_score:
spans.append((ent["start"], ent["end"], label))
return spans
print(find_entities("Please send the report to Priya Nair in Chennai."))This model uses the labels PER, LOC, ORG, and MISC. The MISC label covers things like nationalities and events, and the code ignores it because it is not in the map. The first call downloads the model, so it needs network access and disk space.
Setting the threshold
The min_score value controls the trade-off:
- A higher threshold produces fewer false positives and more missed names. This is higher precision and lower recall.
- A lower threshold produces more false positives and fewer missed names. This is lower precision and higher recall.
For privacy, a missed name is usually worse than an unnecessary placeholder, so thresholds for redaction tend to be lower than for tasks like building a search index. Do not guess a value. Pick it by measuring on labelled examples from your own data, as covered in the evaluation chapter.
Common failure modes
NER models have predictable weak spots. Test for each of these before relying on a model.
- Lowercase and unusual casing. Models lean on capitalization. "send it to maria lopez" or "MARIA LOPEZ" in an all-caps ticket header often scores lower or is missed. Chat messages are frequently informal, so this matters for LLM apps.
- Names from underrepresented groups. Models trained mostly on English news text tend to do worse on names from other languages and regions. This is a fairness problem as well as a leak risk, because some users get weaker protection than others.
- Very short context. A bare "Jordan" in a form field has no sentence around it. The model has nothing to judge by. Detection on single fields or short strings is much less reliable than on full sentences.
- Names that are also common words. "Will", "Rose", "Mark", "Bill", and "Grace" are easy to confuse with ordinary words in both directions.
- Ambiguous entity types. "Washington" can be a person, a city, or a state. The model picks one label, and a wrong label can still be safe to redact, provided your pipeline treats both labels as sensitive.
- Language mismatch. An English model applied to German or Hindi text will degrade sharply. Use a multilingual model, or detect the language first and route to the matching model.
- Long texts. Transformer models have a maximum input length, commonly 512 tokens. Text past that limit may be truncated and silently skipped, which would leave names unredacted. Split long documents into overlapping chunks and adjust the offsets when you merge results.
Offsets and chunking
When you split text into chunks, each chunk's entities have offsets relative to the chunk. You must add the chunk's starting position before you use them on the full text.
def find_entities_chunked(text, detect, size=1000, overlap=100):
spans = set()
step = size - overlap
for offset in range(0, len(text), step):
chunk = text[offset:offset + size]
for start, end, label in detect(chunk):
spans.add((start + offset, end + offset, label))
if offset + size >= len(text):
break
return sorted(spans)The overlap makes sure a name that straddles a chunk boundary appears whole in at least one chunk. The same entity can then be found twice, possibly with slightly different boundaries. The set removes exact duplicates, but partial overlaps remain and need the overlap-resolution step described in the next chapter. Also, cutting at an arbitrary character position can split a word in the middle, so a production version should cut at whitespace or sentence boundaries.
Where NER fits with the other detectors
NER and regex complement each other.
- Use regex for emails, phone numbers, IDs, and card numbers, where the format is rigid.
- Use NER for names, places, and organizations, where only the context reveals the type.
- Some detections overlap. An email such as
[email protected]contains a name. NER may tag part of it, and the regex tags the whole address. When the same text is claimed by two detectors, the pipeline needs a rule for choosing between them. That is the next chapter's subject.
Practical guidance
- Start with a small pretrained model to get a baseline, then measure it on your own data.
- Write your label map deliberately, and review it with whoever owns privacy policy for the product.
- Test with lowercase, all-caps, short strings, non-English names, and long documents.
- Log detection counts and label distributions, but never log the detected text itself. The log would then contain the data you meant to remove.
- Treat NER as a probabilistic layer. It lowers risk and does not remove it, a theme the final chapter returns to.
Exercise
A support-chat app sends each user message to an LLM after NER redaction. A user writes "my name is dana okafor, i live in leeds". The spaCy small model tags nothing in this message. Give two likely causes and two changes you could make to the pipeline.
Show answer
Likely causes: the text is entirely lowercase, and models rely heavily on capitalization, and the message is short and informal, which differs from the news-style text the model was trained on. Changes: add a rule-based detector for phrases like "my name is ..." and "i live in ...", and use a larger or transformer-based model, ideally one evaluated on lowercase chat text. You could also lower the score threshold if the model exposes scores, or fine-tune on your own labelled messages. Then measure recall on a test set of informal messages to confirm the fix.
Exercise
You run a transformer NER model on a 3,000-word contract. Names in the first page are redacted, but names near the end are not. What is the most likely cause, and how do you fix it without losing names that fall on a chunk boundary?
Show answer
The model has a maximum input length, so the text was truncated and everything past the limit was never analysed. Split the document into overlapping chunks, run the model on each chunk, add each chunk's starting offset to its spans, and merge the results. The overlap ensures that a name cut by one chunk boundary appears whole in the neighboring chunk. Duplicate or partially overlapping spans must then be resolved before redaction.