Sub topic 11
Fine-tuning a Transformer for NER
Prerequisites and the training task
Assume you know basic Python, tokenization, and the idea that a neural network classifier learns from labelled examples. You should also understand BIO tags, where B-ORG begins an organization, I-ORG continues it, and O means that a token is outside an entity.
Fine-tuning means starting with a pretrained transformer and continuing its training on your labelled dataset. A transformer encoder reads the surrounding context for each token. A token-classification head then predicts one NER label for each token.
For example:
| Token | Label |
|---|---|
| Ada | B-PER |
| Lovelace | I-PER |
| visited | O |
| London | B-LOC |
The model learns your label set, so it can recognize domain-specific entities such as DRUG, DEVICE, or CUSTOMER_ID.
Prepare and align the data
A common dataset format stores words and their word-level NER labels:
{
"tokens": ["Ada", "Lovelace", "visited", "London"],
"ner_tags": [1, 2, 0, 3]
}The tokenizer may split one word into several subword tokens. For example, unbelievable could become un, ##believable. During training, assign the word's label to the first subword and use -100 for later subwords. The loss function ignores positions labelled -100.
The tokenizer provides word_ids(), which maps each output token back to its original word.
from transformers import AutoTokenizer
tokenizer = AutoTokenizer.from_pretrained("bert-base-cased")
def tokenize_and_align_labels(example):
encoded = tokenizer(
example["tokens"],
is_split_into_words=True,
truncation=True,
)
labels = []
previous_word_id = None
for word_id in encoded.word_ids():
if word_id is None:
labels.append(-100)
elif word_id != previous_word_id:
labels.append(example["ner_tags"][word_id])
else:
labels.append(-100)
previous_word_id = word_id
encoded["labels"] = labels
return encodedFine-tune with Hugging Face
The following example uses the CoNLL-2003 dataset. Its labels include PER, ORG, LOC, and MISC. Replace the dataset and label names when training on your own annotations.
from datasets import load_dataset
from transformers import (
AutoModelForTokenClassification,
AutoTokenizer,
DataCollatorForTokenClassification,
Trainer,
TrainingArguments,
)
import evaluate
dataset = load_dataset("conll2003")
label_names = dataset["train"].features["ner_tags"].feature.names
tokenizer = AutoTokenizer.from_pretrained("bert-base-cased")
def tokenize_and_align_labels(example):
encoded = tokenizer(
example["tokens"],
is_split_into_words=True,
truncation=True,
)
labels = []
previous_word_id = None
for word_id in encoded.word_ids():
if word_id is None:
labels.append(-100)
elif word_id != previous_word_id:
labels.append(example["ner_tags"][word_id])
else:
labels.append(-100)
previous_word_id = word_id
encoded["labels"] = labels
return encoded
tokenized = dataset.map(tokenize_and_align_labels)
model = AutoModelForTokenClassification.from_pretrained(
"bert-base-cased",
num_labels=len(label_names),
id2label=dict(enumerate(label_names)),
label2id={name: i for i, name in enumerate(label_names)},
)
metric = evaluate.load("seqeval")
def compute_metrics(predictions):
logits, labels = predictions
predicted_ids = logits.argmax(axis=-1)
true_labels = [
[label_names[label] for label in row if label != -100]
for row in labels
]
true_predictions = [
[
label_names[prediction]
for prediction, label in zip(pred_row, label_row)
if label != -100
]
for pred_row, label_row in zip(predicted_ids, labels)
]
scores = metric.compute(
predictions=true_predictions,
references=true_labels,
)
return {
"precision": scores["overall_precision"],
"recall": scores["overall_recall"],
"f1": scores["overall_f1"],
}
arguments = TrainingArguments(
output_dir="./ner-model",
eval_strategy="epoch",
save_strategy="epoch",
learning_rate=2e-5,
per_device_train_batch_size=8,
per_device_eval_batch_size=8,
num_train_epochs=3,
weight_decay=0.01,
load_best_model_at_end=True,
)
trainer = Trainer(
model=model,
args=arguments,
train_dataset=tokenized["train"],
eval_dataset=tokenized["validation"],
tokenizer=tokenizer,
data_collator=DataCollatorForTokenClassification(tokenizer),
compute_metrics=compute_metrics,
)
trainer.train()Install the required packages with pip install transformers datasets evaluate seqeval torch. GPU training is much faster, but the example also runs on a CPU dataset with a smaller batch size.
Common errors
- Assigning a label to every subword can overweight long words.
- Comparing token accuracy can hide incorrect entity boundaries.
- A mismatched label-to-ID mapping makes predictions appear to use the wrong entity types.
- Training and validation examples must use the same label set.
- Truncation can remove part of a long entity. Inspect truncated examples before training.
Exercise
Why does the alignment function label later subwords with -100 instead of repeating the word's BIO label?
Show answer
The first subword represents the word for the loss calculation. Ignoring later subwords prevents words split into many pieces from receiving extra influence.