Computer Engineering is coming soon

We're still writing and reviewing the notes for every subject, and we'll open it when every subject is ready. Meanwhile you can practise aptitude, ask Aria about any subject, or see the branches that are ready.

Named entity recognition

Named Entity Recognition (NER): recognising and classifying spans of text that name real-world entities, using rule-based, statistical, and neural sequence-labeling methods, their evaluation, and typical exam derivations.

Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.

Why it matters

Named Entity Recognition (NER) finds and classifies named entities — text spans that refer to real-world objects (people, organisations, locations, dates, etc.). An engineer uses NER in information extraction, question answering, search engines, resume parsing, chatbots and downstream tasks like relation extraction and coreference resolution.

Key ideas

  • Token: the atomic unit the system processes (commonly words or subwords). Define tokens consistently before labelling.

  • Entity mention / chunk: a contiguous group of tokens that form a named entity.

  • BIO (or IOB) tagging: a tagging scheme where each token gets one of: B-TYPE (begin entity of TYPE), I-TYPE (inside entity of TYPE), O (outside any entity). Exams often ask to convert spans to BIO tags and back. Constraint: an I-TYPE must follow B-TYPE or I-TYPE of the same TYPE for a valid chunk. Variants often seen in exams include BIOES/BILOU, which add E/L (end/last) and S/U (single-unit) to mark single-token entities and ends explicitly; be clear which scheme is used.

  • Sequence labelling models: typical supervised methods model P(y | x) where x is the token sequence and y is the tag sequence. Two classic approaches:

    • Hidden Markov Model (HMM) tagger: models joint probability P(x, y) = P(y1)·∏{t=2..T} P(yt | yt-1)·∏{t=1..T} P(xt | yt); assumption: Markov property (yt depends only on yt-1) and emissions independent given tag.
    • Conditional Random Field (CRF): a discriminative undirected model for P(y | x) with global normalization over tag sequences; it removes the need to model P(x | y) and allows overlapping, rich features.
  • Neural sequence models: modern NER uses embeddings + sequence encoder + structured decoder: e.g., BiLSTM-CRF where token embeddings (word vectors, char-CNN/LSTM) feed a bidirectional LSTM to get contextual vectors; a CRF layer enforces valid tag transitions. Current SOTA commonly fine-tunes Transformer encoders (e.g., BERT/RoBERTa) for token classification, optionally with a CRF on top; handle subword tokenization by aligning labels to wordpieces (e.g., label the first subword and mask the rest).

  • Gazetteers and rules: dictionaries of known names and handcrafted rules supplement statistical models, especially useful in low-data settings.

  • Evaluation: measured at entity (span+type) level. Define True Positive (TP) = predicted entity with exactly correct span and type; False Positive (FP) = predicted entity not matching any true entity; False Negative (FN) = true entity not predicted. From these we compute precision, recall, and F1 (harmonic mean of precision and recall). Note: token-level vs entity-level evaluation differ — the exam expects entity-level unless stated. Report whether scores are micro-averaged (aggregate TP/FP/FN over all types, as in CoNLL) or macro-averaged (average per-type F1); unless stated, micro-F1 is standard.

  • Training data: supervised NER uses manually annotated corpora with BIO labels. Common assumptions: training and test tokenisation and label schemes match; domain mismatch causes performance drop.

  • Diagrams to draw for exams:

    • For HMM/Viterbi: draw a time-indexed trellis with T columns (tokens t=1..T). In column t draw nodes for each tag/state. Label horizontal axis with t, vertical nodes with tag names. Draw edges between tags at t-1 and t labelled with transition probabilities a_{i,j}. Show emission probabilities b_j(x_t) at nodes. Indicate Viterbi max path by highlighting chosen node per column.
    • For CRF/BiLSTM-CRF: draw input tokens on bottom row, arrows up to contextual vectors from BiLSTM (two arrows left and right into each vector), then edges above between tag scores with a global normalization Z(x).
  • Derivations commonly asked:

    • Show why F1 is the harmonic mean: F1 = 2/(1/precision + 1/recall). Derive from desire to equally weight precision and recall and penalise imbalance.
    • Show CRF log-likelihood gradient: log P(y|x) = score(x,y) - log Z(x). Then gradient wrt parameter λ equals empirical feature counts minus expected feature counts under P(y|x). Steps: write score(x,y)=Σ_t Σ_k λ_k f_k(...), differentiate, apply chain rule to partition function.

Formulas

precision = TP / (TP + FP) — TP, FP are counts (unitless); applies to entity-level evaluation.

recall = TP / (TP + FN) — TP, FN are counts; applies to entity-level evaluation.

F1 = 2 * precision * recall / (precision + recall) — harmonic mean; unitless; valid when precision+recall > 0.

P(y | x) = (1 / Z(x)) * exp(Σ_t Σ_k λ_k f_k(y_{t-1}, y_t, x, t)) — CRF conditional probability; Z(x) = Σ_{y'} exp(Σ_t Σ_k λ_k f_k(y'_{t-1}, y'_t, x, t)). Symbols: x = input token sequence, y = tag sequence, λ_k = parameter weights, f_k = feature functions, Z(x) = partition function.

δ_t(j) = max_i [δ_{t-1}(i) * a_{i→j} * b_j(x_t)] — Viterbi recurrence for HMM in probability domain; δ_t(j) is max probability of a path ending in state j at time t; a_{i→j} is transition prob, b_j(x_t) emission prob. Initialization: δ_1(j) = π_j * b_j(x_1); backpointer ψ_t(j) = argmax_i [δ_{t-1}(i) * a_{i→j} * b_j(x_t)] for reconstruction.

(When implementing, use log-space: logδ_t(j) = max_i [logδ_{t-1}(i) + log a_{i→j} + log b_j(x_t)].)

Worked examples

Example 1 — BIO tagging (theory question) Sentence: "Barack Obama was born in Honolulu ." Tokens (index): 1:Barack 2:Obama 3:was 4:born 5:in 6:Honolulu 7:.

Step 1: Identify entity spans and types. "Barack Obama" is a PERSON; "Honolulu" is a LOCATION.

Step 2: Produce BIO tags: 1: B-PERSON 2: I-PERSON 3: O 4: O 5: O 6: B-LOCATION 7: O

To convert back to spans: group contiguous B/I of same TYPE. Result: [1–2 PERSON], [6–6 LOCATION]. This is what the examiner expects.

Example 2 — Evaluation (numerical) Gold entities (true): [1–2 PERSON], [6–6 LOCATION], [9–9 DATE] Predicted entities: [1–2 PERSON], [6–6 ORGANIZATION], [10–10 DATE]

Compute TP/FP/FN at entity-level:

  • TP: [1–2 PERSON] matches exactly, so TP=1.
  • Predicted [6–6 ORGANIZATION] has correct span but wrong type → counts as FP and also causes the gold [6–6 LOCATION] to be FN (type mismatch counts as error). So FP += 1, FN += 1.
  • Predicted [10–10 DATE] does not match any gold span (gold had [9–9 DATE]) → FP +=1 and the gold [9–9 DATE] is FN +=1. Total: TP=1, FP=2, FN=2.

Precision = 1 / (1+2) = 1/3 = 0.333 Recall = 1 / (1+2) = 1/3 = 0.333 F1 = 2 * 0.333 * 0.333 / (0.333 + 0.333) = 0.333

Final answer: Precision = 33.3%, Recall = 33.3%, F1 = 33.3% (report as 0.333).

Example 3 — Simple rule-based Python NER (runs without external libraries)

Program (save as ner_rule.py):

# Simple rule-based NER using a gazetteer
G = {"PERSON": {"Barack Obama", "Angela Merkel"},
     "LOCATION": {"Honolulu", "Berlin"},
     "ORG": {"Google", "Microsoft"}}

import re

def ner_rule(text):
    tokens = re.findall(r"\w+|[.,!?;]", text)
    spans = []
    i = 0
    while i < len(tokens):
        matched = False
        # Try longest gazetteer entry first
        for typ in G:
            for name in sorted(G[typ], key=lambda s: -len(s.split())):
                name_tokens = name.split()
                if i + len(name_tokens) <= len(tokens) and all(tokens[i + k].lower() == name_tokens[k].lower() for k in range(len(name_tokens))):
                    spans.append((i, i + len(name_tokens) - 1, typ, name))
                    i += len(name_tokens)
                    matched = True
                    break
            if matched:
                break
        if not matched:
            i += 1
    return tokens, spans

if __name__ == '__main__':
    text = input().strip()
    tokens, spans = ner_rule(text)
    print('Tokens:', tokens)
    for s in spans:
        print('Span tokens {}-{}: {} ({})'.format(s[0]+1, s[1]+1, s[3], s[2]))

Sample input (stdin): Barack Obama was in Honolulu .

Exact output (stdout): Tokens: ['Barack', 'Obama', 'was', 'in', 'Honolulu', '.'] Span tokens 1-2: Barack Obama (PERSON) Span tokens 5-5: Honolulu (LOCATION)

This program demonstrates a simple gazetteer-based NER: useful for small domains and to produce span-level outputs that can be converted to BIO tags.

Common mistakes

  • Invalid BIO sequences (I-TYPE starting without preceding B-TYPE of same TYPE) — when converting tags to spans, students often forget to handle invalid sequences.
  • Mixing tokenisation schemes between train and test (e.g., punctuation attached to tokens) causing wrong spans.
  • Treating same-surface string always as same entity ignoring context (e.g., "Apple" as ORG vs FRUIT).
  • Forgetting to normalise case when using gazetteers or rules.
  • In derivations, skipping the partition function when presenting CRF probabilities, or not showing gradient equals empirical minus expected counts.

For your exam

Typical question types:

  • Define terms (named entity, BIO, CRF, precision/recall).
  • Short notes (compare HMM vs CRF, describe BiLSTM-CRF architecture, explain gazetteers).
  • Derivations (derive F1, derive CRF log-likelihood gradient, show Viterbi recurrence).
  • Conversions and tagging (convert spans to BIO and back; correct invalid BIO sequences).
  • Numerical evaluation (compute precision/recall/F1 from given gold and predicted lists).
  • Simple programming tasks (write a rule-based recogniser or an evaluation routine).
  • Diagrams (draw trellis for Viterbi, BiLSTM-CRF schematic).

What a full-marks answer includes:

  • Clear definitions (bold terms in your head): state assumptions (contiguous spans, tokenisation), give correct formulas, and for derivations show all algebraic steps. For models, state independence assumptions (HMM) or conditional modelling (CRF). For evaluation, show counts TP/FP/FN and compute precision/recall/F1 with numbers and final percentage.

Quick check

  1. What does BIO stand for and what does B-PERSON mean?
  2. Give the CRF conditional probability formula symbolically.
  3. If TP=8, FP=2, FN=4, what is F1? (Give decimal to three places.)

Answers: 1. Begin-Inside-Outside; B-PERSON marks the token that begins a PERSON entity. 2. P(y|x) = (1/Z(x)) * exp(Σ_t Σ_k λ_k f_k(y_{t-1}, y_t, x, t)). 3. Precision=8/(8+2)=0.8, Recall=8/(8+4)=0.666..., F1=20.80.6666667/(0.8+0.6666667)=0.727 (≈0.727).

Finished this topic? Mark it so your progress, study plan and readiness keep up.

Stuck on something here?