🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Named Entity Recognition: Sequence Labeling and Beyond

Natural Language ProcessingNamed Entity Recognition: Sequence Labeling and BeyondđŸŸĸ Free Lesson

Named Entity Recognition: Sequence Labeling and Beyond

What You'll Learn

  • 1Count the label space for BIO and BIOES schemes over a fixed entity set
  • 2Derive the linear-chain CRF score, loss, and Viterbi decoding
  • 3Explain subword alignment when an entity spans several word pieces
  • 4Compute span level precision, recall, and F1 from tag sequences

NER assigns one label per token and then groups those labels into spans, so the task is a structured prediction problem rather than a bag of independent classifications. This lesson derives the BIO scheme and its label count, the linear-chain CRF that scores whole tag sequences with transitions, the Viterbi dynamic program that decodes them, and the span level metrics that make or break an evaluation.

BIO Tagging and the Label Space

The inside, outside, beginning scheme marks the first token of each entity with B, continuation tokens with I, and everything else with O:

where is the number of entity types. CoNLL-2003 uses four types, person, organization, location, and miscellaneous, so BIO needs tags, while the richer BIOES scheme, which adds end and single tags, needs tags. More tags mean more transition parameters but cleaner boundaries, and a single token entity is unambiguous in BIOES.

Linear-Chain CRF

A per-token softmax maximizes each tag independently, which happily produces I-PER after O even though that sequence is illegal. A linear-chain CRF instead scores the whole sequence by adding a transition term to the encoder emissions:

Training maximizes the log probability of the gold tag sequence, which is the negative log of the score marginally normalized over all legal paths:

The sum over all sequences is computed exactly with the forward algorithm in , and decoding uses Viterbi recursion:

ModelDecoding signalCoNLL-2003 F1Notes
Gazetteer rulesdictionary matchabout 75no training, brittle to variants
BiLSTM token headindependent softmaxabout 88sometimes emits illegal tag pairs
BiLSTM-CRF (2016)emissions plus transitions91.2transitions learned from data
BERT-CRFtransformer emissions plus transitionsabout 92subword alignment required

Transformers and Subword Alignment

Modern encoders tokenize names into several word pieces, so the label for a word is attached to its first subtoken and the remaining subtokens receive a special label that the loss ignores. Downstream, those subtoken predictions are regrouped to the original word before span extraction, otherwise a single token entity counts as three predictions.

The head itself is a linear layer over each encoder state, optionally followed by a CRF that enforces legal transitions, and training uses cross entropy over the gold tags or the CRF negative log likelihood. Beyond tagging, span models enumerate candidate spans directly, which handles nested entities such as an organization inside a location without a second labeling pass.

Worked Examples

Worked Code

python
import torch
import torch.nn as nn

class BiLSTMCRF(nn.Module):
    def __init__(self, vocab, embed_dim, hidden, tags):
        super().__init__()
        self.tags = tags
        self.embed = nn.Embedding(vocab, embed_dim, padding_idx=0)
        self.lstm = nn.LSTM(embed_dim, hidden, batch_first=True,
                            bidirectional=True)
        self.hidden2tag = nn.Linear(hidden * 2, tags)
        self.transitions = nn.Parameter(torch.randn(tags, tags))

    def emissions(self, tokens):
        out, _ = self.lstm(self.embed(tokens))
        return self.hidden2tag(out)

    def score(self, emit, tags):
        score = emit[0, tags[0]]
        for t in range(1, emit.size(0)):
            score = score + self.transitions[tags[t - 1], tags[t]] + emit[t, tags[t]]
        return score

    def viterbi(self, emit):
        backpointers = []
        best = emit[0]
        for t in range(1, emit.size(0)):
            cand = best.unsqueeze(1) + self.transitions
            best = cand.max(dim=0).values + emit[t]
            backpointers.append(cand.argmax(dim=0))
        path = [int(best.argmax())]
        for ptr in reversed(backpointers):
            path.append(int(ptr[path[-1]]))
        return list(reversed(path))

model = BiLSTMCRF(vocab=30000, embed_dim=100, hidden=256, tags=9)
tokens = torch.randint(1, 30000, (12,))
print("tags:", model.viterbi(model.emissions(tokens.unsqueeze(0))[0]))
print("params:", sum(p.numel() for p in model.parameters()))
python
def to_spans(tags):
    spans, current, start = [], None, None
    for i, tag in enumerate(tags):
        kind, label = (tag.split("-", 1) + ["O"])[:2] if "-" in tag else (tag, None)
        if kind == "B":
            if current is not None:
                spans.append((current, start, i))
            current, start = label, i
        elif kind == "I" and current == label:
            continue
        else:
            if current is not None:
                spans.append((current, start, i))
            current, start = None, None
    if current is not None:
        spans.append((current, start, len(tags)))
    return set(spans)

def span_scores(gold_tags, pred_tags):
    gold, pred = to_spans(gold_tags), to_spans(pred_tags)
    tp = len(gold & pred)
    precision = tp / len(pred) if pred else 0.0
    recall = tp / len(gold) if gold else 0.0
    f1 = (2 * precision * recall / (precision + recall)
          if precision + recall else 0.0)
    return precision, recall, f1

gold = ["B-PER", "I-PER", "O", "B-LOC", "O"]
pred = ["B-PER", "I-PER", "O", "O", "O"]
print("P R F1:", [round(v, 3) for v in span_scores(gold, pred)])

Real-World Applications

  • Customer support triage: NER extracts order numbers, product names, and locations from tickets before routing, and span errors are cheap to catch with regular expressions.
  • Financial disclosure scanning: organization and money tags feed document review, where recall is weighted above precision because missed mentions are the expensive error.
  • Knowledge base population: entity linking runs downstream of tagging, so a one point F1 gain in NER compounds into measurably better link coverage.

💡Transitions fix most label bugs

A CRF layer learns that I-PER may not follow O, which removes a whole class of nonsense predictions without any hand written constraint, and it costs , or 810 operations for a ten token sentence with nine tags.

Common Mistakes

Evaluating per token instead of per span

Fix: Convert predictions to spans first, since a shifted boundary is a wrong entity in every strict benchmark.

Labeling every subtoken of a word

Fix: Attach the label to the first subtoken and mask the rest, otherwise long names are counted three times.

Ignoring illegal tag pairs at evaluation

Fix: Either decode with a CRF or filter illegal transitions, since I tags without a preceding B inflate recall.

Best Practices

  • Report micro F1 on exact spans plus per type recall, since business costs differ by entity type
  • Keep the label scheme identical between training and serving, especially BIO versus BIOES
  • Normalize whitespace and unicode before tagging so spans line up with the source document

Key Takeaways

  • BIO over L types needs 2L plus 1 tags, which is 9 for the four CoNLL-2003 types
  • A CRF scores emissions plus transitions and normalizes over all legal sequences with the forward algorithm
  • Viterbi turns 9 to the 10 candidate sequences into 810 transition evaluations
  • Span level F1, not token accuracy, is the metric that reflects real entity extraction quality

Frequently Asked Questions

Does a CRF still help behind a transformer?

Yes, though less than behind a recurrent encoder. The transition matrix still suppresses illegal pairs such as I-ORG after O, and on benchmarks the CRF adds a few tenths of a point while removing post-processing rules.

How are nested entities handled?

A flat tag set allows one tag per token, so nested mentions need either a second labeling pass over already extracted spans or a span classification model that scores candidate start and end pairs directly.

What if the entity types differ from the training corpus?

Retrain with the target type inventory, because a CRF transition matrix is sized to the label set and cannot score types it never saw. Zero-shot alternatives classify span descriptions instead of fixed labels.

Interview Questions

Q1: Why does a per-token softmax fail on BIO tags?

It maximizes each position independently, so it can emit I-PER after O, an impossible path that a transition matrix scores as low and the CRF decoder never returns.

Q2: How many operations does Viterbi need for ten tokens and nine tags?

T times the tag count squared, so 10 times 81 equals 810 transition evaluations, versus 3,486,784,401 sequences by enumeration.

CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-07

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert NLP Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement