Interview's MateData Science
Interview's Mate

Data Science

Python → ML → MLOps

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
Data Science topics
Lesson 137/ 160
07. Deep Learning & NLP

Named Entity Recognition (NER) & Topic Modeling

Extract entities and discover latent topics with NER models and topic algorithms.

AdvancedNER · Topics3 quiz questions
Practice Generative AI Q&A
In plain wordsDiagramTheoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

In plain words

NER finds the names of people, places and companies in text and labels them. Topic modelling reads many documents and works out what themes they talk about, such as pricing, delivery or product quality.

Think of it like…

NER is a highlighter that colour-codes names, places and companies in a document. Topic modelling is sorting a pile of articles into themed piles without being told the themes in advance, then labelling each pile by looking at its most characteristic words.

Where you’ve seen it

The sentence "Priya joined Acme Corp in Berlin" is tagged B-PER, O, B-ORG, I-ORG, O, B-LOC. A model that outputs B-PER, O, B-ORG, O, O, B-LOC gets 5 of 6 tokens right (83% token accuracy) but is wrong on the span "Acme Corp" (it found only "Acme"), so under strict span matching it has 2 true positives, 1 false positive and 1 false negative: precision 2/3, recall 2/3 and entity-level F1 0.667. That gap is why NER is scored at the entity level. A contracts team fine-tunes a transformer for PARTY, DATE and AMOUNT entities, adds rules for currency patterns and checks per-type F1 because AMOUNT is easy while PARTY is not. On the topic side, 20,000 customer comments are cleaned (stop words removed, min_df filtering, lemmatised) and fitted with LDA. Each topic is a word distribution; a document with topic mixture (0.7 pricing, 0.3 support) where P(price | pricing) = 0.10 and P(price | support) = 0.01 has P(price | document) = 0.7 × 0.10 + 0.3 × 0.01 = 0.073. The number of topics is chosen by comparing coherence scores across runs (illustrative: K = 5 gives 0.41, K = 10 gives 0.48, K = 15 gives 0.46, K = 20 gives 0.43), then confirmed by reading the top words and example documents and naming each topic by hand. Stability is checked by re-running with different seeds and keeping topics that reappear.

Words you’ll hear

BIO tagging
B marks the first token of an entity, I the continuation and O any other token.
Entity-level F1
F1 computed on whole entity spans, counted correct only if boundaries and type match.
LDA
A generative model of documents as mixtures of topics over words.
Topic coherence
A score of how semantically related a topic's top words are.

Visual diagram

Loading interactive diagram

Theory & deep dive

NER as sequence tagging

Each token receives a tag: B-X starts an entity of type X, I-X continues it and O marks everything else. For "Priya joined Acme Corp in Berlin" the gold tags are B-PER, O, B-ORG, I-ORG, O, B-LOC. Approaches range from rules and gazetteers (lists of known names, regex for dates and amounts), through CRFs that model tag transitions, to fine-tuned transformers that read the context ("Apple" as organisation versus fruit). spaCy and Hugging Face provide pretrained pipelines, and fine-tuning adds your own entity types. With subword tokenisation, labels must be aligned to the first subword of each word, with the remaining pieces ignored in the loss (label −100 in common implementations).

Evaluate on entities, not tokens. With gold entities {Priya: PER, Acme Corp: ORG, Berlin: LOC} and predictions {Priya: PER, Acme: ORG, Berlin: LOC}, strict matching counts 2 true positives (Priya, Berlin), 1 false positive (Acme, the wrong span) and 1 false negative (Acme Corp), giving precision 0.667, recall 0.667 and F1 0.667, whereas token accuracy is 5/6 = 83%. Report per-type F1 and look at boundary errors, since most are partial spans, and at type confusions such as ORG versus LOC.

Token accuracy versus entity F1

Gold: B-PER O B-ORG I-ORG O B-LOC. Predicted: B-PER O B-ORG O O B-LOC. Token accuracy 5/6 = 83%. Entities: TP 2, FP 1, FN 1 → precision 0.667, recall 0.667, F1 0.667.

Key takeaway: Tag with BIO, score whole spans and inspect boundary and type errors by entity class.

Topic modelling with LDA and its alternatives

LDA assumes each document has a topic mixture θ and each topic a word distribution φ. The probability of a word in a document is the mixture-weighted sum: with θ = (0.7, 0.3) and P(price | topic A) = 0.10, P(price | topic B) = 0.01, P(price | document) = 0.7 × 0.10 + 0.3 × 0.01 = 0.073. Fitting infers θ for every document and φ for every topic from word counts alone. Key choices: the number of topics K, the Dirichlet priors (a small alpha gives documents with few topics), and the preprocessing: remove stop words, set min_df and max_df, lemmatise and consider bigrams. LDA works on bag-of-words counts, not TF-IDF.

Choosing K is a judgement supported by coherence (higher is better; for example K = 10 beating 5, 15 and 20) and by reading topics. Perplexity often disagrees with human judgement. Common issues: junk topics made of boilerplate, mixed topics where K is too small, duplicated topics where it is too large and instability across random seeds. NMF on TF-IDF is quick and often cleaner on short texts; BERTopic clusters sentence embeddings and labels clusters with class-based TF-IDF, which handles short text and semantics better but is less transparent. Always label topics manually, and treat them as exploratory, not as ground truth classes.

Mixture arithmetic

θ = (0.7 pricing, 0.3 support). P(price | pricing) = 0.10, P(price | support) = 0.01. P(price | doc) = 0.7 × 0.10 + 0.3 × 0.01 = 0.07 + 0.003 = 0.073. For the word refund with 0.02 and 0.08: 0.7 × 0.02 + 0.3 × 0.08 = 0.038.

Key takeaway: Pick K using coherence and by reading topics, preprocess carefully and treat topics as exploratory summaries.

How it works, step by step

Step 1 of 4
Data scientist

1. Define entity types or topic goals

List the entity types and annotation rules for NER, or the questions you want topics to answer.

PERSON · ORG · LOC · DATE · AMOUNT
Key numbers at this step
Write
annotation guide

When to use it & trade-offs

What it is

Named entity recognition (NER) finds spans of text that refer to real-world entities such as people, organisations, locations, dates and amounts, and labels each with a type. It is usually framed as sequence tagging with BIO tags (B-PER begins a person, I-PER continues it, O is outside any entity) and solved with rules and gazetteers, conditional random fields or fine-tuned transformers. Topic modelling is the unsupervised counterpart for discovering themes: LDA (latent Dirichlet allocation) models each document as a mixture of topics and each topic as a distribution over words, while NMF and embedding-plus-clustering approaches such as BERTopic give alternatives. NER extracts structured facts; topic models summarise what a large collection is about.

Why it matters: Entities turn free text into data you can join, count and search (which companies appear in contracts, which drugs in clinical notes), and topics let you explore tens of thousands of documents without reading them. Both are easy to run and easy to misjudge: token-level accuracy hides span errors in NER, and topic models always return topics whether or not they are coherent. Knowing the evaluation method, the preprocessing and the pitfalls separates a useful analysis from a word cloud.

When to reach for it

  • Extracting parties, dates and amounts from contracts
  • Summarising themes in survey comments and support tickets
  • Pre-processing step for knowledge graphs and search

When to avoid or be careful

  • Scoring NER by token accuracy alone
  • Presenting topic model output without reading the topics
  • Using LDA on tiny texts without checking that topics are coherent

Approaches

Rules and gazetteers
Best for: Closed lists and rigid patterns such as dates or IDs

Strengths: Precise; no training data.

Watch out: Misses new names and variations.

Fine-tuned transformer NER
Best for: Context-dependent entity types

Strengths: High accuracy; learns from labels.

Watch out: Needs annotated data and compute.

LDA / NMF topics
Best for: Exploring large collections without labels

Strengths: Interpretable word lists; fast.

Watch out: Needs K and manual labelling; unstable.

Embedding clustering (BERTopic)
Best for: Short texts and semantic grouping

Strengths: Captures meaning beyond word overlap.

Watch out: Heavier; less transparent.

Interview signals & numbers to know

When this topic comes up

  • “How do you evaluate an NER model?”
  • BIO tagging and subword alignment
  • How LDA represents documents and topics
  • Choosing the number of topics
  • LDA versus BERTopic

Benchmarks & rules of thumb

0.667 -
entity-level F1 where token accuracy looks like 83%
0.073 -
P(price | document) for the mixture example
K = 10 -
best coherence in the illustrative sweep (0.48)

Common mistakes & follow-ups

Common interview mistakes

  • Forgetting to align labels to subword tokens.
  • Choosing K from perplexity alone.
  • Treating topics as labelled classes in a downstream model without validation.

Likely interviewer follow-ups

  • How would you handle overlapping or nested entities?
  • How would you check topic quality?
  • When would you choose NMF over LDA?
Interview tip: Explain why token accuracy overstates NER quality, with the five-of-six example; it shows you evaluate what users actually consume.

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply Named Entity Recognition (NER) & Topic Modeling with data science interview Q&A and hands-on practice.

Open Data Science Q&A →Machine Learning Q&A
Previous topic
Sentiment Analysis & Text Classification
Next topic
Attention Mechanism & Transformer Overview