Token Classification: NER with BERT
Named Entity Recognition introduced the task, the BIO tags (B-PER begins a person, I-PER continues it, O is outside any entity) and a tagger built from hand-made word features. A fine-tuned encoder replaces the features with contextual vectors: one label per token, predicted from a hidden state that has seen the whole sentence. The same setup serves part-of-speech tagging, slot filling in assistants ("book a table for four at seven"), PII redaction and extracting fields from invoices.
The model part is simple: a linear layer on every hidden state. What goes wrong in practice is the bookkeeping around it. Labels belong to words, the model sees subword tokens, and the score that matters counts entities, not tokens. This lesson builds that bookkeeping from scratch, then fine-tunes BERT on an original synthetic data set and measures what happens on names it has never seen.
The task as math
For a sentence of tokens with final hidden states and tags, the head is one shared linear layer:
is the set of positions that carry a label. Every other position gets the label , PyTorch's default ignore_index for cross-entropy, so it adds nothing to the loss or the gradient. Each prediction is independent given the hidden states; a CRF layer on top (the classic BiLSTM-CRF) would score whole tag sequences and forbid transitions such as O followed by I-PER, but with a fine-tuned transformer the gain is usually small and most libraries leave it out.
The data: templated sentences with three entity types
No public NER corpus is available offline here, so the lesson generates one. Eight sentence templates are filled with invented people (first + last name), organisations and places, some of them two words long. The name lists are split: training sentences use only the first part of each list, and a second test set uses only names that never appear in training. That split is the point of the exercise: a tagger that has memorised a name list looks perfect on the first test set and is found out on the second.
From scratch: word labels to subword labels
A tokenizer splits rare words into pieces, and word_ids() tells, for each token, which word it came from (None for [CLS], [SEP] and padding). The usual rule is: the first piece of each word gets the word's label, every continuation piece and every special token gets . The alternative, labelling every piece (continuations get the I- tag of their entity), trains on more positions but makes the loss count long words several times. Below, a stand-in tokenizer that cuts lower-cased words into pieces of at most 4 letters shows both rules:
import random
FIRST = ["Maren", "Tobin", "Ilse", "Corwin", "Yara", "Dario", "Senna", "Halvard", "Nkem", "Ottilie", "Rafe", "Liesel",
"Bram", "Zuri", "Anouk", "Kasimir"]
LAST = ["Vey", "Okonjo", "Halloran", "Brisk", "Tamsin", "Quell", "Marlow", "Feld", "Arkwright", "Senn", "Dube", "Lomax"]
ORG = ["Velto Labs", "Brightwave", "Karsten Freight", "Nimbus Bank", "Orrin Media", "Quillfield", "Tessaro Motors",
"Halcyon Health", "Pell & Rook", "Juniper Cloud", "Stonegate Insurance", "Lumen Tools"]
LOC = ["Karrow", "Port Elmsey", "Vantry", "Oldmere", "New Halden", "Ashby Cross", "Tiller", "Brennick", "Sauls Bay",
"Morvane", "Eastwold", "Cray Hill"]
TEMPLATES = ["{PER} works for {ORG} in {LOC} .", "{ORG} opened a new office in {LOC} .", "{PER} moved to {LOC} last year .",
"yesterday {PER} met {PER} at {ORG} .", "{ORG} hired {PER} as head of sales .", "the {LOC} branch of {ORG} is closing .",
"{PER} said that {ORG} will grow .", "flights from {LOC} to {LOC} are cheaper now ."]
def make(rng, n, first, last, org, loc):
data = []
for _ in range(n):
words, tags = [], []
for part in rng.choice(TEMPLATES).split():
if part[0] != "{":
words.append(part); tags.append("O"); continue
kind = part[1:4]
ent = {"PER": lambda: rng.choice(first) + " " + rng.choice(last), "ORG": lambda: rng.choice(org),
"LOC": lambda: rng.choice(loc)}[kind]().split()
words += ent; tags += ["B-" + kind] + ["I-" + kind] * (len(ent) - 1)
data.append((words, tags))
return data
rng = random.Random(0)
seen = (FIRST[:12], LAST[:9], ORG[:9], LOC[:9]) # names that appear in training
unseen = (FIRST[12:], LAST[9:], ORG[9:], LOC[9:]) # names kept for testing only
train = make(rng, 600, *seen)
test_seen, test_unseen = make(rng, 100, *seen), make(rng, 100, *unseen)
print("sentences: train", len(train), "| test seen names", len(test_seen), "| test unseen names", len(test_unseen))
words, tags = test_unseen[0]
print(" ".join(f"{w}/{t}" for w, t in zip(words, tags)))
def toy_subwords(word): # stand-in tokenizer: lower-case, pieces of at most 4 letters
w = word.lower()
return [w[:4]] + ["##" + w[i:i + 4] for i in range(4, len(w), 4)]
def tokenize_with_word_ids(words):
tokens, word_ids = ["[CLS]"], [None]
for i, w in enumerate(words):
pieces = toy_subwords(w)
tokens += pieces; word_ids += [i] * len(pieces)
return tokens + ["[SEP]"], word_ids + [None]
LABELS = ["O", "B-PER", "I-PER", "B-ORG", "I-ORG", "B-LOC", "I-LOC"]
def align(word_ids, tags, label_all=False):
out, prev = [], None
for wid in word_ids:
if wid is None:
out.append(-100) # [CLS], [SEP], padding: no loss
elif wid != prev:
out.append(LABELS.index(tags[wid])) # first piece of a word: the word's label
elif label_all:
out.append(LABELS.index(tags[wid].replace("B-", "I-"))) # continuation piece gets I-
else:
out.append(-100) # continuation piece: ignored
prev = wid
return out
toks, wids = tokenize_with_word_ids(words)
print("tokens: ", toks)
print("word_ids:", wids)
print("labels: ", align(wids, tags))
print("label all:", align(wids, tags, label_all=True))sentences: train 600 | test seen names 100 | test unseen names 100
yesterday/O Kasimir/B-PER Dube/I-PER met/O Zuri/B-PER Lomax/I-PER at/O Juniper/B-ORG Cloud/I-ORG ./O
tokens: ['[CLS]', 'yest', '##erda', '##y', 'kasi', '##mir', 'dube', 'met', 'zuri', 'loma', '##x', 'at', 'juni', '##per', 'clou', '##d', '.', '[SEP]']
word_ids: [None, 0, 0, 0, 1, 1, 2, 3, 4, 5, 5, 6, 7, 7, 8, 8, 9, None]
labels: [-100, 0, -100, -100, 1, -100, 2, 0, 1, 2, -100, 0, 3, -100, 4, -100, 0, -100]
label all: [-100, 0, 0, 0, 1, 2, 2, 0, 1, 2, 2, 0, 3, 4, 4, 4, 0, -100]
The 10 words became 18 tokens. With the first-piece rule, exactly 10 positions carry a label (one per word) and 8 are . Note how "kasi ##mir" keeps B-PER on "kasi" only: had the continuation piece also received B-PER, the model would learn to start a second person in the middle of a name. That is why "label all" turns B- into I- for continuation pieces.
The real BERT WordPiece tokenizer does the same with is_split_into_words=True, which tokenizes each word separately and records the mapping:
from transformers import AutoTokenizer
tok = AutoTokenizer.from_pretrained("google/bert_uncased_L-2_H-128_A-2")
words = ["yesterday", "Kasimir", "Dube", "met", "Zuri", "Lomax", "at", "Juniper", "Cloud", "."]
tags = ["O", "B-PER", "I-PER", "O", "B-PER", "I-PER", "O", "B-ORG", "I-ORG", "O"]
enc = tok(words, is_split_into_words=True)
print("tokens: ", enc.tokens())
print("word_ids:", enc.word_ids())
labels, prev = [], None
for wid in enc.word_ids():
labels.append(-100 if wid is None or wid == prev else tags[wid])
prev = wid
print("labels: ", labels)
print("whole sentence as one string:", tok("Kasimir Dube").tokens(), "| offsets:", tok("Kasimir Dube", return_offsets_mapping=True)["offset_mapping"])tokens: ['[CLS]', 'yesterday', 'ka', '##si', '##mir', 'dub', '##e', 'met', 'zur', '##i', 'lo', '##max', 'at', 'juniper', 'cloud', '.', '[SEP]']
word_ids: [None, 0, 1, 1, 1, 2, 2, 3, 4, 4, 5, 5, 6, 7, 8, 9, None]
labels: [-100, 'O', 'B-PER', -100, -100, 'I-PER', -100, 'O', 'B-PER', -100, 'I-PER', -100, 'O', 'B-ORG', 'I-ORG', 'O', -100]
whole sentence as one string: ['[CLS]', 'ka', '##si', '##mir', 'dub', '##e', '[SEP]'] | offsets: [(0, 0), (0, 2), (2, 4), (4, 7), (8, 11), (11, 12), (0, 0)]
The invented names fall apart into pieces ("ka ##si ##mir"), while "juniper" and "cloud" are whole vocabulary entries. The model is uncased, so the capital letter, the strongest clue for a name in English, is gone before the model sees the text: it must rely on context and on the pieces themselves. When the input is raw text instead of words, the offset mapping gives each token's character span ((0, 2) is "Ka", (8, 11) is "Dub"), which is how labelled character spans from an annotation tool are turned into token labels, and how predictions are turned back into highlighted text.
From scratch: entity-level scores
Token accuracy is a poor score for NER: most tokens are O, and an entity with one wrong token is useless to a downstream system. The standard score (CoNLL, seqeval) converts both tag sequences to sets of entities (type, start, end) and counts an entity as correct only if type and both boundaries match exactly:
with the gold entities and the predicted ones, summed over all sentences (micro average).
def spans(tags):
"""BIO tags -> set of (type, start, end) entities; an I- without a matching B- starts a new entity."""
out, start, kind = set(), None, None
for i, t in enumerate(tags + ["O"]):
if start is not None and (t == "O" or t.startswith("B-") or t[2:] != kind):
out.add((kind, start, i)); start = None
if t != "O" and start is None:
start, kind = i, t[2:]
return out
def entity_scores(gold_seqs, pred_seqs):
tp = fp = fn = 0
for g, p in zip(gold_seqs, pred_seqs):
G, P = spans(g), spans(p)
tp += len(G & P); fp += len(P - G); fn += len(G - P)
prec, rec = tp / (tp + fp), tp / (tp + fn)
return round(prec, 3), round(rec, 3), round(2 * prec * rec / (prec + rec), 3)
gold = [["B-PER", "I-PER", "O", "O", "B-ORG", "I-ORG", "O", "B-LOC", "O"],
["O", "B-PER", "I-PER", "O", "B-PER", "I-PER", "O", "B-ORG", "O"],
["O", "O", "B-LOC", "O", "B-LOC", "I-LOC", "O", "O", "O"]]
pred = [["B-PER", "I-PER", "O", "O", "B-ORG", "O", "O", "B-LOC", "O"], # ORG cut short
["O", "B-PER", "I-PER", "O", "B-PER", "I-PER", "O", "B-LOC", "O"], # ORG labelled LOC
["O", "O", "B-LOC", "O", "B-LOC", "I-LOC", "O", "O", "O"]] # all right
print("gold entities, sentence 1:", sorted(spans(gold[0])))
print("pred entities, sentence 1:", sorted(spans(pred[0])))
tok_acc = sum(g == p for G, P in zip(gold, pred) for g, p in zip(G, P)) / sum(map(len, gold))
print(f"token accuracy: {tok_acc:.3f}")
print("entity precision, recall, F1:", entity_scores(gold, pred))gold entities, sentence 1: [('LOC', 7, 8), ('ORG', 4, 6), ('PER', 0, 2)]
pred entities, sentence 1: [('LOC', 7, 8), ('ORG', 4, 5), ('PER', 0, 2)]
token accuracy: 0.926
entity precision, recall, F1: (0.75, 0.75, 0.75)
Two wrong tokens out of 27 give a token accuracy of 0.926, but they break two of the 8 entities: the organisation cut short is both a false positive (ORG 4 to 5) and a false negative (ORG 4 to 6), and the mislabelled one is the same. Entity F1 is 0.75. A boundary error costs twice, which is why entity F1 is the number to report.
Fine-tuning BERT for NER
The recorded example fine-tunes AutoModelForTokenClassification (BERT plus a 7-way linear layer on every token) with the first-piece rule, DataCollatorForTokenClassification (it pads input_ids with the pad id and labels with ), AdamW at , batches of 16, 4 epochs. At prediction time the tag of each word is read from its first piece. Two training sets of 600 sentences each are compared:
- fixed lists: the 600 training sentences above, built from 12 first names, 9 last names, 9 organisations and 9 places;
- varied names: the first 300 of those sentences plus 300 more whose names are coined from random syllables (hundreds of distinct names, none of them in either test set).
Both are scored on the 100 test sentences with training names and the 100 with unseen names, and on one sentence from a template the model never saw.
import random
import torch
from transformers import AutoTokenizer, AutoModelForTokenClassification, DataCollatorForTokenClassification
from transformers.utils import logging
logging.set_verbosity_error()
FIRST = ["Maren", "Tobin", "Ilse", "Corwin", "Yara", "Dario", "Senna", "Halvard", "Nkem", "Ottilie", "Rafe", "Liesel",
"Bram", "Zuri", "Anouk", "Kasimir"]
LAST = ["Vey", "Okonjo", "Halloran", "Brisk", "Tamsin", "Quell", "Marlow", "Feld", "Arkwright", "Senn", "Dube", "Lomax"]
ORG = ["Velto Labs", "Brightwave", "Karsten Freight", "Nimbus Bank", "Orrin Media", "Quillfield", "Tessaro Motors",
"Halcyon Health", "Pell & Rook", "Juniper Cloud", "Stonegate Insurance", "Lumen Tools"]
LOC = ["Karrow", "Port Elmsey", "Vantry", "Oldmere", "New Halden", "Ashby Cross", "Tiller", "Brennick", "Sauls Bay",
"Morvane", "Eastwold", "Cray Hill"]
TEMPLATES = ["{PER} works for {ORG} in {LOC} .", "{ORG} opened a new office in {LOC} .", "{PER} moved to {LOC} last year .",
"yesterday {PER} met {PER} at {ORG} .", "{ORG} hired {PER} as head of sales .", "the {LOC} branch of {ORG} is closing .",
"{PER} said that {ORG} will grow .", "flights from {LOC} to {LOC} are cheaper now ."]
def make(rng, n, first, last, org, loc):
data = []
for _ in range(n):
words, tags = [], []
for part in rng.choice(TEMPLATES).split():
if part[0] != "{":
words.append(part); tags.append("O"); continue
kind = part[1:4]
ent = {"PER": lambda: rng.choice(first) + " " + rng.choice(last), "ORG": lambda: rng.choice(org),
"LOC": lambda: rng.choice(loc)}[kind]().split()
words += ent; tags += ["B-" + kind] + ["I-" + kind] * (len(ent) - 1)
data.append((words, tags))
return data
rng = random.Random(0)
seen = (FIRST[:12], LAST[:9], ORG[:9], LOC[:9])
unseen = (FIRST[12:], LAST[9:], ORG[9:], LOC[9:])
train = make(rng, 600, *seen)
test_seen, test_unseen = make(rng, 100, *seen), make(rng, 100, *unseen)
SYL = ["ka", "ro", "mi", "tel", "sa", "vin", "do", "ra", "len", "bo", "ri", "um", "fa", "zel", "no", "ash"]
def coined(rng, k): # many distinct made-up names from syllables
return [("".join(rng.choice(SYL) for _ in range(rng.choice([2, 3])))).capitalize() for _ in range(k)]
r2 = random.Random(1)
varied = (coined(r2, 200), coined(r2, 200), [w + " " + r2.choice(["Labs", "Bank", "Media", "Freight"]) for w in coined(r2, 200)],
coined(r2, 200))
train_varied = train[:300] + make(r2, 300, *varied) # half the sentences keep the fixed lists, half get coined names
LABELS = ["O", "B-PER", "I-PER", "B-ORG", "I-ORG", "B-LOC", "I-LOC"]
name = "google/bert_uncased_L-2_H-128_A-2"
tok = AutoTokenizer.from_pretrained(name)
def encode(data): # first piece of a word gets its label, the rest -100
feats = []
for words, tags in data:
enc = tok(words, is_split_into_words=True)
labels, prev = [], None
for wid in enc.word_ids():
labels.append(-100 if wid is None or wid == prev else LABELS.index(tags[wid]))
prev = wid
feats.append(dict(input_ids=enc["input_ids"], labels=labels))
return feats
def spans(tags):
out, start, kind = set(), None, None
for i, t in enumerate(tags + ["O"]):
if start is not None and (t == "O" or t.startswith("B-") or t[2:] != kind):
out.add((kind, start, i)); start = None
if t != "O" and start is None:
start, kind = i, t[2:]
return out
def predict(model, data): # one tag per word, read from its first piece
model.eval(); preds = []
with torch.no_grad():
for words, _ in data:
enc = tok(words, is_split_into_words=True, return_tensors="pt")
ids = model(**enc).logits[0].argmax(-1).tolist()
wids = enc.word_ids()
first = {w: i for i, w in reversed(list(enumerate(wids))) if w is not None}
preds.append([LABELS[ids[first[w]]] for w in range(len(words))])
return preds
def f1(data, preds, kind=None): # entity-level micro F1
tp = fp = fn = 0
for (_, gold), p in zip(data, preds):
G = {s for s in spans(gold) if kind in (None, s[0])}; P = {s for s in spans(p) if kind in (None, s[0])}
tp += len(G & P); fp += len(P - G); fn += len(G - P)
return 2 * tp / (2 * tp + fp + fn)
def train_model(data):
torch.manual_seed(0)
model = AutoModelForTokenClassification.from_pretrained(name, num_labels=len(LABELS))
collate = DataCollatorForTokenClassification(tok) # pads input_ids with 0 and labels with -100
feats = encode(data)
opt = torch.optim.AdamW(model.parameters(), lr=1e-3, weight_decay=0.01)
g = torch.Generator().manual_seed(0)
for epoch in range(4):
model.train()
for idx in torch.randperm(len(feats), generator=g).split(16):
loss = model(**collate([feats[i] for i in idx])).loss
opt.zero_grad(); loss.backward(); opt.step()
return model
for tname, data in [("fixed lists ", train), ("varied names", train_varied)]:
model = train_model(data)
for label, test in [("seen names", test_seen), ("unseen names", test_unseen)]:
preds = predict(model, test)
print(f"{tname} | {label:12s}: entity F1 {f1(test, preds):.3f} | PER {f1(test, preds, 'PER'):.3f}"
f" | ORG {f1(test, preds, 'ORG'):.3f} | LOC {f1(test, preds, 'LOC'):.3f}")
words = "we asked Ilse Marlow about the Tiller office of Nimbus Bank .".split()
print("new template:", list(zip(words, predict(model, [(words, None)])[0])))fixed lists | seen names : entity F1 0.993 | PER 0.994 | ORG 0.987 | LOC 1.000
fixed lists | unseen names: entity F1 0.475 | PER 0.237 | ORG 0.648 | LOC 0.578
varied names | seen names : entity F1 1.000 | PER 1.000 | ORG 1.000 | LOC 1.000
varied names | unseen names: entity F1 0.817 | PER 0.609 | ORG 0.882 | LOC 0.986
new template: [('we', 'B-ORG'), ('asked', 'O'), ('Ilse', 'B-PER'), ('Marlow', 'I-PER'), ('about', 'O'), ('the', 'O'), ('Tiller', 'B-LOC'), ('office', 'O'), ('of', 'O'), ('Nimbus', 'B-ORG'), ('Bank', 'I-ORG'), ('.', 'O')]
What the numbers say (entity F1, 100 test sentences per set, one seed):
- A model trained on fixed name lists memorises them. 0.993 on sentences with training names, 0.475 on unseen names. Persons suffer most (0.237): an unseen two-piece name in "{PER} moved to {LOC}" looks a lot like an unseen place. If the test set had been drawn from the same lists, as happens when a corpus is split by sentence rather than by name or document, this model would have been reported as nearly perfect.
- Name diversity fixes most of it. Replacing half the sentences with coined names lifts unseen-name F1 to 0.817 (places 0.986, organisations 0.882) with the same number of sentences and the same 8 templates. The model can no longer get the loss down by remembering names, so it learns the contexts ("works for", "moved to", "Bank" at the end).
- New contexts are still a problem. In a sentence from a ninth template, the trained names are found, but "we" is tagged
B-ORG: the model has only ever seen an entity at the start of a sentence. Real data has thousands of contexts; a synthetic set with 8 templates teaches the shortcut "first word is an entity".
The same lessons hold for real NER corpora: split by document or source, report entity F1 per type, and check a set of entities that never appear in training. A cased model would also help here, since capitalisation is a strong clue that this uncased model never sees.
Pitfalls
- Labelling special tokens or continuation pieces with
B-. Use for special tokens and either or theI-tag for continuation pieces; never repeatB-inside a word. - Reading predictions from every piece. At inference, take the first piece's tag (or aggregate the pieces) and map back to words with
word_ids()or the offsets; otherwise one word becomes several entities. - Token accuracy as the headline. It is dominated by
Otokens; report entity-level precision, recall and F1 with exact boundaries, per type. - Splitting a corpus so test entities also appear in training. The score then measures memorisation; hold out names, documents or sources.
- Truncation cutting an entity in half. Long documents are split into windows (with
strideandreturn_overflowing_tokens=True); merge the window predictions afterwards. - Losing case or accents in preprocessing. For NER, prefer a cased model and keep the original text, since the offsets must point into it.
Practice
- A word is split into 3 pieces and is labelled
B-ORG. Which labels do its pieces get under the first-piece rule, and under "label all"? - Gold:
B-PER I-PER O B-LOC. Prediction:B-PER O O B-LOC. Give the entity precision, recall and F1. - Why did the model trained on fixed lists score lower on persons than on places for unseen names?
- A colleague reports token accuracy 0.97 on a corpus where 90 % of tokens are
O. What would you ask for?
Answers
- First-piece rule:
B-ORG, , . Label all:B-ORG,I-ORG,I-ORG. - Gold entities: (PER 0 to 2), (LOC 3 to 4). Predicted: (PER 0 to 1), (LOC 3 to 4). One true positive, so , , , while token accuracy is .
- Every person is two words of unseen pieces, so both boundaries and the type must be right, and several templates put persons and places in similar positions (at the start of the sentence, after "to" or "at"). Many places are one word and the "flights from ... to ..." context pins them down.
- Entity-level precision, recall and F1 per type, how the split was made (by document?), and the score on entities absent from training. A tagger that predicts
Oeverywhere already has 0.90 token accuracy.
Test yourself
Why do continuation subword pieces usually get the label -100?
- They are padding
- So that each word contributes one labelled position and the loss ignores the extra pieces
- Because -100 means the O tag
- To make the model faster
Gold has the entity ORG at words 4 to 6; the model predicts ORG at words 4 to 5. How does entity-level scoring count it?
- As correct
- As half correct
- As one false positive and one false negative
- It is ignored
The NER model trained on fixed name lists scored entity F1 0.993 on test sentences with training names and 0.475 with unseen names. What does that show?
- The unseen test set is mislabelled
- The model memorised the names; a test set that shares entities with training overstates the score
- Entity F1 is unreliable
- The model needs a larger learning rate
What does word_ids() return for the [CLS] and [SEP] tokens?
- 0
- -100
- None
- The index of the last word