TExcelTAD
Home › NLP, Transformers & LLM Fine-Tuning › Named Entity Recognition: BIO Tags and a Feature Tagger

Named Entity Recognition: BIO Tags and a Feature Tagger

A support ticket says "Marek Berger from Norvik Bank cannot log in since he moved to Graz". To route it, anonymise it or fill a CRM record, a system has to find the spans that name things and say what they are: a person (PER), an organisation (ORG), a location (LOC). That is named entity recognition (NER), the standard example of sequence labelling: one decision per token, where the decisions depend on each other.

This lesson builds the classical pipeline from scratch: span encodings (BIO, BIOES), the entity-level metric everyone reports, a feature-based tagger with logistic regression, and Viterbi decoding that enforces valid tag sequences. Token Classification: NER with BERT later replaces the hand-made features with a fine-tuned transformer; the encodings, the metric and the decoding stay the same.

From spans to tags

Entities are spans, but a token classifier predicts one label per token. BIO (also called IOB2) encodes a span of type XX as B-X on its first token and I-X on the rest; every other token is O. BIOES adds E-X for the last token of a multi-token span and S-X for a single-token entity. With LL entity types, BIO has 2L+12L + 1 tags and BIOES 4L+14L + 1.

PER ORG LOC wordBIOBIOES Anna B-PER B-PER Novak I-PER E-PER joined O O Tellura B-ORG B-ORG Systems I-ORG E-ORG in O O New B-LOC B-LOC Varna I-LOC E-LOC

Two adjacent entities of the same type stay separate in BIO because the second starts with a new B-. Some sequences are invalid: I-PER directly after O, or I-ORG after B-LOC. A decoder must either forbid them or have a rule for them.

The data is an original synthetic set: templated news sentences ("{PER} joined {ORG} in {LOC} last year .") filled from name pools with a fixed seed. Names can have one or two tokens, and capitalised words that are not entities ("Monday", "Yesterday", "According") appear too. The 200 test sentences draw half of their entities from pools never used in training ("Hana Duarte", "Vela Systems", "Port Elm"), which is the realistic case: a deployed NER model mostly meets names it has never seen.

python · try it yourself
import numpy as np

rng = np.random.default_rng(0)
POOLS = {   # (seen in training, only in test)
    "PER": (["Anna Novak", "Marek Berger", "Lucia Costa", "Tomas Lind", "Ines Moreau", "Pavel Petrov",
             "Sara", "Jonas", "Elena Ruiz", "Viktor Hale"], ["Hana Duarte", "Oskar Brandt", "Mira Kowalski", "Teo"]),
    "ORG": (["Norvik Bank", "Tellura Systems", "Brightline Foods", "Halden University", "Ostra Labs",
             "Kestrel Group", "Mondo Bank"], ["Vela Systems", "Orbis Labs", "Pinecrest Foods"]),
    "LOC": (["Porto", "Graz", "Tampere", "Bergen", "Lyon", "New Varna", "Santa Clara"], ["Utrecht", "Ghent", "Port Elm"]),
}
TEMPLATES = [
    "{PER} joined {ORG} in {LOC} last year .", "{ORG} opened an office in {LOC} on Monday .",
    "{PER} met {PER} at the {ORG} conference .", "According to {PER} , {ORG} will hire 200 engineers .",
    "The mayor of {LOC} thanked {PER} .", "{PER} flew from {LOC} to {LOC} in March .",
    "Yesterday the shares of {ORG} fell sharply .", "Prices in {LOC} rose again this week .",
    "The new report was written by {PER} .", "Last Friday it rained all day .",
]

def make(n, test=False):
    sents = []
    for _ in range(n):
        words, tags = [], []
        for part in TEMPLATES[rng.integers(len(TEMPLATES))].split():
            if part.startswith("{"):
                label = part[1:-1]
                seen, unseen = POOLS[label]
                pool = unseen if test and rng.random() < 0.5 else seen
                name = pool[rng.integers(len(pool))].split()
                words += name
                tags += ["B-" + label] + ["I-" + label] * (len(name) - 1)
            else:
                words.append(part)
                tags.append("O")
        sents.append((words, tags))
    return sents

train, test = make(400), make(200, test=True)

def tags_to_spans(tags):
    """BIO tags -> set of (label, start, end) with end exclusive. An I- that does not continue
    an entity of the same label starts a new one (what conlleval and seqeval do)."""
    spans, start, label = [], None, None
    for i, t in enumerate(tags + ["O"]):
        if start is not None and not (t.startswith("I-") and t[2:] == label):
            spans.append((label, start, i))
            start = None
        if t.startswith("B-") or (t.startswith("I-") and start is None):
            start, label = i, t[2:]
    return spans

def spans_to_tags(spans, n, scheme="BIO"):
    tags = ["O"] * n
    for label, s, e in spans:
        if scheme == "BIOES" and e - s == 1:
            tags[s] = "S-" + label
            continue
        tags[s] = "B-" + label
        for i in range(s + 1, e):
            tags[i] = "I-" + label
        if scheme == "BIOES":
            tags[e - 1] = "E-" + label
    return tags

words, tags = train[2]
print(" ".join(f"{w}/{t}" for w, t in zip(words, tags)))
spans = tags_to_spans(tags)
print("spans:", [(l, " ".join(words[s:e])) for l, s, e in spans])
print("BIOES:", spans_to_tags(spans, len(words), "BIOES"))
print("round trip on all training sentences:",
      all(spans_to_tags(tags_to_spans(t), len(t)) == t for _, t in train))
print("I- after O:", tags_to_spans(["O", "I-PER", "I-PER", "O", "B-LOC", "I-ORG"]))
counts = {}
for _, t in train:
    for l, s, e in tags_to_spans(t):
        counts[l] = counts.get(l, 0) + 1
print("training sentences:", len(train), "| entities:", counts, "| test sentences:", len(test))
Anna/B-PER Novak/I-PER joined/O Tellura/B-ORG Systems/I-ORG in/O New/B-LOC Varna/I-LOC last/O year/O ./O
spans: [('PER', 'Anna Novak'), ('ORG', 'Tellura Systems'), ('LOC', 'New Varna')]
BIOES: ['B-PER', 'E-PER', 'O', 'B-ORG', 'E-ORG', 'O', 'B-LOC', 'E-LOC', 'O', 'O', 'O']
round trip on all training sentences: True
I- after O: [('PER', 1, 3), ('LOC', 4, 5), ('ORG', 5, 6)]
training sentences: 400 | entities: {'PER': 279, 'LOC': 253, 'ORG': 202} | test sentences: 200

tags_to_spans turns the tag sequence back into (label, start, end) spans, and the round trip spans →\to tags →\to spans is exact on all 400 training sentences. The line "I- after O" shows the lenient rule used by conlleval and seqeval's default mode: a stray I-PER after O starts a new entity, and I-ORG after B-LOC ends the LOC and starts an ORG.

Measuring NER: entity-level precision, recall and F1

Token accuracy is the wrong metric. Most tokens are O, so a tagger that predicts O everywhere scores high, and a boundary error costs one token but ruins the entity. The CoNLL standard counts whole entities: a predicted entity is a true positive only if its type, start and end all match a gold entity.

P=∣gold∩pred∣∣pred∣,R=∣gold∩pred∣∣gold∣,F1=2PRP+RP = \frac{\lvert \text{gold} \cap \text{pred} \rvert}{\lvert \text{pred} \rvert}, \qquad R = \frac{\lvert \text{gold} \cap \text{pred} \rvert}{\lvert \text{gold} \rvert}, \qquad F_1 = \frac{2 P R}{P + R}

Scores are micro-averaged: the sets collect the entities of all sentences (each tagged with its sentence id) before counting.

python · try it yourself
def tags_to_spans(tags):                           # BIO -> {(label, start, end)}; a stray I- starts an entity
    spans, start, label = set(), None, None
    for i, t in enumerate(list(tags) + ["O"]):
        if start is not None and not (t.startswith("I-") and t[2:] == label):
            spans.add((label, start, i))
            start = None
        if t.startswith("B-") or (t.startswith("I-") and start is None):
            start, label = i, t[2:]
    return spans

def prf(gold, pred):                               # entity-level, exact match of label and boundaries
    tp = len(gold & pred)
    p = tp / len(pred) if pred else 0.0
    r = tp / len(gold) if gold else 0.0
    return p, r, (2 * p * r / (p + r) if p + r else 0.0)

words = "Marek Berger flew from New Varna to Graz in March .".split()
gold = ["B-PER", "I-PER", "O", "O", "B-LOC", "I-LOC", "O", "B-LOC", "O", "O", "O"]
pred = ["B-PER", "I-PER", "O", "O", "O", "B-LOC", "O", "B-ORG", "O", "B-LOC", "O"]
G, P = tags_to_spans(gold), tags_to_spans(pred)
show = lambda S: sorted((l, " ".join(words[s:e])) for l, s, e in S)
print("gold:", show(G))
print("pred:", show(P))
print("token accuracy:", round(sum(g == p for g, p in zip(gold, pred)) / len(gold), 3))
p, r, f = prf(G, P)
print(f"entity precision {p:.3f}, recall {r:.3f}, F1 {f:.3f}")
gold: [('LOC', 'Graz'), ('LOC', 'New Varna'), ('PER', 'Marek Berger')]
pred: [('LOC', 'March'), ('LOC', 'Varna'), ('ORG', 'Graz'), ('PER', 'Marek Berger')]
token accuracy: 0.636
entity precision 0.250, recall 0.333, F1 0.286

Seven of eleven tokens are right (0.636), but only one of four predicted entities is right. "Varna" instead of "New Varna" is a boundary error, and it counts twice: once as a false positive (the predicted "Varna") and once as a false negative (the missed "New Varna"). "Graz" as ORG is a type error, also counted twice. Precision is 14=0.25\frac{1}{4} = 0.25, recall 13≈0.333\frac{1}{3} \approx 0.333, F1=0.286F_1 = 0.286. Some evaluations (MUC, SemEval 2013) also give partial credit for overlapping spans; say which variant you report.

A feature-based tagger

Before neural networks, NER systems were linear classifiers over hand-designed features of a token and its neighbours, decoded with an HMM, a maximum-entropy Markov model or a CRF. The features that matter:

  • the word itself (lower-cased), its prefix or suffix ("-son", "-ova", "Labs");
  • the word shape: Xx for "Varna", d for "200", XxXx for "McKay" (runs of the same character class collapsed);
  • whether it is the first word (sentence-initial capitals are not evidence);
  • the same features of the neighbouring words: "joined ___" and "in ___" predict ORG and LOC whatever the name is.

Each token becomes a sparse dictionary of features, DictVectorizer one-hot encodes them, and a multinomial logistic regression predicts the tag of each token independently:

P(yi=k∣features(x,i))=softmax⁡(Wϕ(x,i)+b)kP(y_i = k \mid \text{features}(x, i)) = \operatorname{softmax}(W \phi(x, i) + b)_k
python · try it yourself
import numpy as np

rng = np.random.default_rng(0)
POOLS = {   # (seen in training, only in test)
    "PER": (["Anna Novak", "Marek Berger", "Lucia Costa", "Tomas Lind", "Ines Moreau", "Pavel Petrov",
             "Sara", "Jonas", "Elena Ruiz", "Viktor Hale"], ["Hana Duarte", "Oskar Brandt", "Mira Kowalski", "Teo"]),
    "ORG": (["Norvik Bank", "Tellura Systems", "Brightline Foods", "Halden University", "Ostra Labs",
             "Kestrel Group", "Mondo Bank"], ["Vela Systems", "Orbis Labs", "Pinecrest Foods"]),
    "LOC": (["Porto", "Graz", "Tampere", "Bergen", "Lyon", "New Varna", "Santa Clara"], ["Utrecht", "Ghent", "Port Elm"]),
}
TEMPLATES = [
    "{PER} joined {ORG} in {LOC} last year .", "{ORG} opened an office in {LOC} on Monday .",
    "{PER} met {PER} at the {ORG} conference .", "According to {PER} , {ORG} will hire 200 engineers .",
    "The mayor of {LOC} thanked {PER} .", "{PER} flew from {LOC} to {LOC} in March .",
    "Yesterday the shares of {ORG} fell sharply .", "Prices in {LOC} rose again this week .",
    "The new report was written by {PER} .", "Last Friday it rained all day .",
]

def make(n, test=False):
    sents = []
    for _ in range(n):
        words, tags = [], []
        for part in TEMPLATES[rng.integers(len(TEMPLATES))].split():
            if part.startswith("{"):
                label = part[1:-1]
                seen, unseen = POOLS[label]
                pool = unseen if test and rng.random() < 0.5 else seen
                name = pool[rng.integers(len(pool))].split()
                words += name
                tags += ["B-" + label] + ["I-" + label] * (len(name) - 1)
            else:
                words.append(part)
                tags.append("O")
        sents.append((words, tags))
    return sents

train, test = make(400), make(200, test=True)
def tags_to_spans(tags):                           # BIO -> {(label, start, end)}; a stray I- starts an entity
    spans, start, label = set(), None, None
    for i, t in enumerate(list(tags) + ["O"]):
        if start is not None and not (t.startswith("I-") and t[2:] == label):
            spans.add((label, start, i))
            start = None
        if t.startswith("B-") or (t.startswith("I-") and start is None):
            start, label = i, t[2:]
    return spans

def prf(gold, pred):                               # entity-level, exact match of label and boundaries
    tp = len(gold & pred)
    p = tp / len(pred) if pred else 0.0
    r = tp / len(gold) if gold else 0.0
    return p, r, (2 * p * r / (p + r) if p + r else 0.0)
from sklearn.feature_extraction import DictVectorizer
from sklearn.linear_model import LogisticRegression

def shape(w):                                      # "Varna" -> "Xx", "200" -> "d", "," -> ","
    s = "".join("X" if c.isupper() else "x" if c.islower() else "d" if c.isdigit() else c for c in w)
    return "".join(c for i, c in enumerate(s) if i == 0 or c != s[i - 1])

def token_features(words, i, full=True):
    w = words[i]
    f = {"w=" + w.lower(): 1, "shape=" + shape(w): 1, "suf3=" + w[-3:].lower(): 1, "first": int(i == 0)}
    if full:
        for o in (-2, -1, 1, 2):                   # neighbours' words and shapes
            j = i + o
            n = words[j] if 0 <= j < len(words) else "<edge>"
            f[f"w{o}=" + n.lower()] = 1
            f[f"shape{o}=" + shape(n)] = 1
    return f

def fit_tagger(train, full=True):
    X = [token_features(w, i, full) for w, _ in train for i in range(len(w))]
    y = [t for _, tags in train for t in tags]
    vec = DictVectorizer()
    clf = LogisticRegression(C=1.0, max_iter=2000).fit(vec.fit_transform(X), y)
    return vec, clf

def tag_probs(vec, clf, words, full=True):         # (n_words, n_tags) probabilities
    return clf.predict_proba(vec.transform([token_features(words, i, full) for i in range(len(words))]))

seen_names = {" ".join(w[s:e]) for w, t in train for _, s, e in tags_to_spans(t)}
print("shape('Varna'), shape('200'), shape('McKay'):", shape("Varna"), shape("200"), shape("McKay"))
for full in (False, True):
    vec, clf = fit_tagger(train, full)
    G, P, unseen, found = set(), set(), 0, 0
    for k, (words, tags) in enumerate(test):
        pred = clf.classes_[tag_probs(vec, clf, words, full).argmax(1)]
        g, p = tags_to_spans(tags), tags_to_spans(pred)
        G |= {(k,) + s for s in g}
        P |= {(k,) + s for s in p}
        for s in g:
            if " ".join(words[s[1]:s[2]]) not in seen_names:
                unseen += 1
                found += s in p
    print("features:", "word, shape, suffix + neighbours" if full else "word, shape, suffix only", f"({len(vec.vocabulary_)} columns)")
    for label in ("PER", "ORG", "LOC"):
        p, r, f = prf({s for s in G if s[1] == label}, {s for s in P if s[1] == label})
        print(f"  {label}: precision {p:.3f}, recall {r:.3f}, F1 {f:.3f}")
    p, r, f = prf(G, P)
    print(f"  all {len(G)} test entities: F1 {f:.3f} | recall on the {unseen} unseen names: {found / unseen:.3f}")
shape('Varna'), shape('200'), shape('McKay'): Xx d XxXx
features: word, shape, suffix only (170 columns)
  PER: precision 0.242, recall 0.514, F1 0.329
  ORG: precision 0.516, recall 0.516, F1 0.516
  LOC: precision 1.000, recall 0.517, F1 0.682
  all 380 test entities: F1 0.461 | recall on the 195 unseen names: 0.056
features: word, shape, suffix + neighbours (518 columns)
  PER: precision 1.000, recall 0.923, F1 0.960
  ORG: precision 0.939, recall 1.000, F1 0.969
  LOC: precision 0.959, recall 0.959, F1 0.959
  all 380 test entities: F1 0.962 | recall on the 195 unseen names: 0.913

Without neighbour features the tagger has only the token itself, and recall on names that never appeared in training is 0.056: a capitalised unknown word could be anything. With the context window, the same model reaches F1=0.962F_1 = 0.962 on all 380 test entities and finds 0.913 of the 195 unseen names, because "flew from ___ to" and "joined ___ in" are seen in training with other names. That is the main lesson of feature-based NER, and it carries over to neural models: context generalises, name lists do not.

A real corpus is harder than these templates: more entity types, nested entities ("Bank of Portugal"), ambiguous names ("Jordan", "Paris Hilton", "Santa Clara" the city or the university), lower-case text from chat and speech, and annotation disagreements. On CoNLL-2003 English test data, feature-based systems reached F1F_1 of about 0.84 (a CRF, McCallum and Li 2003) to 0.89 (the best shared-task entry, a combination of classifiers, Florian et al. 2003), BiLSTM-CRFs about 0.91 (Lample et al. 2016; Ma and Hovy 2016), and fine-tuned transformers about 0.92 to 0.94 (BERT 0.924 to 0.928, LUKE 0.943).

Decoding: Viterbi with a transition constraint

The classifier decides each token alone, so nothing stops it from outputting O I-ORG. Viterbi decoding finds the best sequence under a score that adds token scores and transition scores:

y^=arg⁡max⁡y1,…,yn∑i=1n(log⁡P(yi∣x,i)+Ayi−1,yi)\hat{y} = \arg\max_{y_1, \dots, y_n} \sum_{i=1}^{n} \Bigl(\log P(y_i \mid x, i) + A_{y_{i-1}, y_i}\Bigr)

With Aab=0A_{ab} = 0 for allowed transitions and −∞-\infty for forbidden ones (bb = I-X with aa not B-X or I-X, and the start treated as O), it returns the most probable valid sequence. Dynamic programming makes it exact in O(nK2)O(n K^2) for KK tags: δi(k)\delta_i(k) = best score of a sequence ending in tag kk at position ii, δi(k)=max⁡j(δi−1(j)+Ajk)+log⁡P(yi=k)\delta_i(k) = \max_j \bigl(\delta_{i-1}(j) + A_{jk}\bigr) + \log P(y_i = k), with back-pointers to recover the path. A CRF learns AA from data instead of fixing it; a BiLSTM-CRF or BERT-CRF puts the same layer on top of a neural encoder.

python · try it yourself
import numpy as np

rng = np.random.default_rng(0)
POOLS = {   # (seen in training, only in test)
    "PER": (["Anna Novak", "Marek Berger", "Lucia Costa", "Tomas Lind", "Ines Moreau", "Pavel Petrov",
             "Sara", "Jonas", "Elena Ruiz", "Viktor Hale"], ["Hana Duarte", "Oskar Brandt", "Mira Kowalski", "Teo"]),
    "ORG": (["Norvik Bank", "Tellura Systems", "Brightline Foods", "Halden University", "Ostra Labs",
             "Kestrel Group", "Mondo Bank"], ["Vela Systems", "Orbis Labs", "Pinecrest Foods"]),
    "LOC": (["Porto", "Graz", "Tampere", "Bergen", "Lyon", "New Varna", "Santa Clara"], ["Utrecht", "Ghent", "Port Elm"]),
}
TEMPLATES = [
    "{PER} joined {ORG} in {LOC} last year .", "{ORG} opened an office in {LOC} on Monday .",
    "{PER} met {PER} at the {ORG} conference .", "According to {PER} , {ORG} will hire 200 engineers .",
    "The mayor of {LOC} thanked {PER} .", "{PER} flew from {LOC} to {LOC} in March .",
    "Yesterday the shares of {ORG} fell sharply .", "Prices in {LOC} rose again this week .",
    "The new report was written by {PER} .", "Last Friday it rained all day .",
]

def make(n, test=False):
    sents = []
    for _ in range(n):
        words, tags = [], []
        for part in TEMPLATES[rng.integers(len(TEMPLATES))].split():
            if part.startswith("{"):
                label = part[1:-1]
                seen, unseen = POOLS[label]
                pool = unseen if test and rng.random() < 0.5 else seen
                name = pool[rng.integers(len(pool))].split()
                words += name
                tags += ["B-" + label] + ["I-" + label] * (len(name) - 1)
            else:
                words.append(part)
                tags.append("O")
        sents.append((words, tags))
    return sents

train, test = make(400), make(200, test=True)
def tags_to_spans(tags):                           # BIO -> {(label, start, end)}; a stray I- starts an entity
    spans, start, label = set(), None, None
    for i, t in enumerate(list(tags) + ["O"]):
        if start is not None and not (t.startswith("I-") and t[2:] == label):
            spans.add((label, start, i))
            start = None
        if t.startswith("B-") or (t.startswith("I-") and start is None):
            start, label = i, t[2:]
    return spans

def prf(gold, pred):                               # entity-level, exact match of label and boundaries
    tp = len(gold & pred)
    p = tp / len(pred) if pred else 0.0
    r = tp / len(gold) if gold else 0.0
    return p, r, (2 * p * r / (p + r) if p + r else 0.0)
from sklearn.feature_extraction import DictVectorizer
from sklearn.linear_model import LogisticRegression

def shape(w):                                      # "Varna" -> "Xx", "200" -> "d", "," -> ","
    s = "".join("X" if c.isupper() else "x" if c.islower() else "d" if c.isdigit() else c for c in w)
    return "".join(c for i, c in enumerate(s) if i == 0 or c != s[i - 1])

def token_features(words, i, full=True):
    w = words[i]
    f = {"w=" + w.lower(): 1, "shape=" + shape(w): 1, "suf3=" + w[-3:].lower(): 1, "first": int(i == 0)}
    if full:
        for o in (-2, -1, 1, 2):                   # neighbours' words and shapes
            j = i + o
            n = words[j] if 0 <= j < len(words) else "<edge>"
            f[f"w{o}=" + n.lower()] = 1
            f[f"shape{o}=" + shape(n)] = 1
    return f

def fit_tagger(train, full=True):
    X = [token_features(w, i, full) for w, _ in train for i in range(len(w))]
    y = [t for _, tags in train for t in tags]
    vec = DictVectorizer()
    clf = LogisticRegression(C=1.0, max_iter=2000).fit(vec.fit_transform(X), y)
    return vec, clf

def tag_probs(vec, clf, words, full=True):         # (n_words, n_tags) probabilities
    return clf.predict_proba(vec.transform([token_features(words, i, full) for i in range(len(words))]))

def allowed(prev, cur):                            # BIO rule: I-X only after B-X or I-X
    return not cur.startswith("I-") or (prev != "O" and prev[2:] == cur[2:])

def viterbi(logp, labels):
    """logp: (n, K) log-probabilities per token. Transitions are 0 (allowed) or -inf (forbidden)."""
    n, K = logp.shape
    trans = np.array([[0.0 if allowed(a, b) else -np.inf for b in labels] for a in labels])
    start = np.array([0.0 if allowed("O", b) else -np.inf for b in labels])   # sentence start acts like O
    score, back = start + logp[0], np.zeros((n, K), dtype=np.int64)
    for t in range(1, n):
        cand = score[:, None] + trans              # cand[i, j]: best path ending in i, then j
        back[t] = cand.argmax(0)
        score = cand.max(0) + logp[t]
    path = [int(score.argmax())]
    for t in range(n - 1, 0, -1):
        path.append(int(back[t, path[-1]]))
    return [labels[k] for k in path[::-1]]

def invalid(tags):
    return any(not allowed(a, b) for a, b in zip(["O"] + list(tags), tags))

for full in (False, True):
    vec, clf = fit_tagger(train, full)
    labels = [str(c) for c in clf.classes_]
    G, P_greedy, P_vit, bad = set(), set(), set(), 0
    for k, (words, tags) in enumerate(test):
        logp = np.log(tag_probs(vec, clf, words, full))
        greedy = [labels[j] for j in logp.argmax(1)]
        bad += invalid(greedy)
        best = viterbi(logp, labels)
        assert not invalid(best)
        G |= {(k,) + s for s in tags_to_spans(tags)}
        P_greedy |= {(k,) + s for s in tags_to_spans(greedy)}
        P_vit |= {(k,) + s for s in tags_to_spans(best)}
    print("neighbour features:" if full else "no neighbour features:",
          f"greedy F1 {prf(G, P_greedy)[2]:.3f} ({bad} of {len(test)} sentences with an invalid I-),",
          f"Viterbi F1 {prf(G, P_vit)[2]:.3f}")

words = "Vela Systems opened an office in Port Elm on Monday .".split()
vec, clf = fit_tagger(train, False)
labels = [str(c) for c in clf.classes_]
logp = np.log(tag_probs(vec, clf, words, False))
print("words:  ", words[:7])
print("greedy: ", [labels[j] for j in logp.argmax(1)][:7])
print("Viterbi:", viterbi(logp, labels)[:7])
no neighbour features: greedy F1 0.461 (45 of 200 sentences with an invalid I-), Viterbi F1 0.592
neighbour features: greedy F1 0.962 (6 of 200 sentences with an invalid I-), Viterbi F1 0.969
words:   ['Vela', 'Systems', 'opened', 'an', 'office', 'in', 'Port']
greedy:  ['O', 'I-ORG', 'O', 'O', 'O', 'O', 'B-PER']
Viterbi: ['B-ORG', 'I-ORG', 'O', 'O', 'O', 'O', 'B-PER']

With the weak tagger, 45 of the 200 greedy outputs contain an invalid I-, and constrained Viterbi raises F1F_1 from 0.461 to 0.592 without any retraining. The last lines show one repair: greedy decoding tags the unseen "Vela Systems" as O I-ORG, because "Systems" is a strong ORG suffix but "Vela" is unknown; Viterbi must choose a valid sequence and finds B-ORG I-ORG the most probable one. With context features only 6 sentences are invalid, and Viterbi still lifts F1F_1 from 0.962 to 0.969. Constrained decoding is cheap and almost always worth it. The same two lines also show what it cannot fix: "Port" of "Port Elm" is tagged B-PER, a valid tag with the wrong type.

The library route

sklearn-crfsuite (a wrapper of CRFsuite) trains a linear-chain CRF on exactly these feature dictionaries; it is not available in the browser, so it is shown without running:

python
import sklearn_crfsuite                            # pip install sklearn-crfsuite; not run here

X_train = [[token_features(w, i) for i in range(len(w))] for w, _ in train]
y_train = [tags for _, tags in train]
crf = sklearn_crfsuite.CRF(algorithm="lbfgs", c1=0.1, c2=0.1, max_iterations=100)
crf.fit(X_train, y_train)                          # learns token weights and the transition matrix A

For evaluation, seqeval implements the entity-level metric above (seqeval.metrics.classification_report(y_true, y_pred), lenient by default, mode="strict", scheme=IOB2 to count invalid sequences as errors). spaCy and Hugging Face pipelines ship pretrained NER models; the BERT lesson fine-tunes one and deals with the extra problem that subword tokenisation splits words into several tokens.

Pitfalls

  • Reporting token accuracy. It is dominated by O. Report entity-level PP, RR, F1F_1, per type and micro-averaged, and say whether the matching was strict.
  • Testing only on seen names. If the same names appear in train and test, the model can memorise them. Hold out names (as here) or documents, and report recall on unseen entities separately.
  • Splitting sentences of one document across train and test. A name repeated in a document leaks. Split by document.
  • Invalid sequences. Without a constraint or a CRF, O I-X appears, and different span conversions give different scores. Decode with constraints.
  • Mixing tag schemes. BIO (IOB2) and the older IOB1 (B- only between two adjacent entities of the same type) look the same but convert differently. Check what a data set uses.
  • Tokenisation mismatch. Gold spans are often given in characters; a tokenizer that splits "Norvik-Bank's" differently from the annotation creates spans that cannot be represented. Keep character offsets (see Tokenizers in Practice).

Practice

  1. Write the BIO and BIOES tags for "Lucia Costa met Sara at the Halden University conference ."
  2. Gold has 50 entities. A tagger predicts 40, of which 30 are exact matches and 6 have the right type but a boundary off by one token. Compute strict precision, recall and F1F_1.
  3. Why does the Viterbi example treat the sentence start like O?
  4. With K=7K = 7 tags and a sentence of 30 tokens, how many score additions does Viterbi do, roughly, compared with scoring every possible tag sequence?
  5. Add a feature "the word is in a gazetteer of training names" to the tagger. What happens to recall on unseen names, and why might the model rely on it too much?
Answers
  1. BIO: B-PER I-PER O B-PER O O B-ORG I-ORG O O. BIOES: B-PER E-PER O S-PER O O B-ORG E-ORG O O.
  2. P=3040=0.75P = \frac{30}{40} = 0.75, R=3050=0.6R = \frac{30}{50} = 0.6, F1=2⋅0.75⋅0.61.35≈0.667F_1 = \frac{2 \cdot 0.75 \cdot 0.6}{1.35} \approx 0.667. The 6 near misses count as false positives and their gold entities as false negatives.
  3. A sentence cannot start inside an entity, so I-X is forbidden at position 1, exactly as after O. Starting with the O row of the transition matrix expresses that.
  4. Viterbi: about nK2=30⋅49=1470n K^2 = 30 \cdot 49 = 1470 additions. All sequences: 730≈2.3⋅10257^{30} \approx 2.3 \cdot 10^{25}.
  5. It helps on names that are in the list and does nothing for unseen ones, which by definition are not in it. Worse, if training names always fire the feature, the model learns that the gazetteer feature is nearly sufficient and puts less weight on context, so recall on unseen names can drop. Use gazetteer dropout (randomly hide the feature during training) or build the list from data the training sentences do not come from.

Test yourself

With PER, ORG and LOC, how many tags does the BIO scheme have?

  1. 3
  2. 6
  3. 7
  4. 13

A tagger predicts 'Varna' as LOC where the gold entity is 'New Varna' (LOC). How does the strict entity metric count it?

  1. As a true positive
  2. As half a true positive
  3. As one false positive and one false negative
  4. It is ignored

In the feature tagger, what raised recall on unseen names from 0.056 to 0.913?

  1. A larger C
  2. Features of the neighbouring words
  3. More training sentences
  4. Lower-casing all words

What does constrained Viterbi decoding guarantee that greedy argmax does not?

  1. Higher probability for every single token
  2. A valid tag sequence (no I-X after O or after another type), and the most probable one among valid sequences
  3. Correct entity types
  4. Faster decoding