Token classification
Token classification assigns a label to individual tokens in a sentence. One of the most common token classification tasks is Named Entity Recognition (NER). NER attempts to find a label for each entity in a sentence, such as a person, location, or organization.
This guide will show you how to:
Finetune DistilBERT on the WNUT 17 dataset to detect new entities.
Use your finetuned model for inference.
The task illustrated in this tutorial is supported by the following model architectures:
ALBERT, BERT, BigBird, BioGpt, BLOOM, BROS, CamemBERT, CANINE, ConvBERT, Data2VecText, DeBERTa, DeBERTa-v2, DistilBERT, ELECTRA, ERNIE, ErnieM, ESM, Falcon, FlauBERT, FNet, Funnel Transformer, GPT-Sw3, OpenAI GPT-2, GPTBigCode, GPT Neo, GPT NeoX, I-BERT, LayoutLM, LayoutLMv2, LayoutLMv3, LiLT, Longformer, LUKE, MarkupLM, MEGA, Megatron-BERT, MobileBERT, MPNet, MPT, MRA, Nezha, NystrΓΆmformer, QDQBert, RemBERT, RoBERTa, RoBERTa-PreLayerNorm, RoCBert, RoFormer, SqueezeBERT, XLM, XLM-RoBERTa, XLM-RoBERTa-XL, XLNet, X-MOD, YOSO
Before you begin, make sure you have all the necessary libraries installed:
Copied
pip install transformers datasets evaluate seqevalWe encourage you to login to your BOINC AI account so you can upload and share your model with the community. When prompted, enter your token to login:
Copied
>>> from boincai_hub import notebook_login
>>> notebook_login()Load WNUT 17 dataset
Start by loading the WNUT 17 dataset from the π Datasets library:
Copied
Then take a look at an example:
Copied
Each number in ner_tags represents an entity. Convert the numbers to their label names to find out what the entities are:
Copied
The letter that prefixes each ner_tag indicates the token position of the entity:
B-indicates the beginning of an entity.I-indicates a token is contained inside the same entity (for example, theStatetoken is a part of an entity likeEmpire State Building).0indicates the token doesnβt correspond to any entity.
Preprocess
The next step is to load a DistilBERT tokenizer to preprocess the tokens field:
Copied
As you saw in the example tokens field above, it looks like the input has already been tokenized. But the input actually hasnβt been tokenized yet and youβll need to set is_split_into_words=True to tokenize the words into subwords. For example:
Copied
However, this adds some special tokens [CLS] and [SEP] and the subword tokenization creates a mismatch between the input and labels. A single word corresponding to a single label may now be split into two subwords. Youβll need to realign the tokens and labels by:
Mapping all tokens to their corresponding word with the
word_idsmethod.Assigning the label
-100to the special tokens[CLS]and[SEP]so theyβre ignored by the PyTorch loss function (see CrossEntropyLoss).Only labeling the first token of a given word. Assign
-100to other subtokens from the same word.
Here is how you can create a function to realign the tokens and labels, and truncate sequences to be no longer than DistilBERTβs maximum input length:
Copied
To apply the preprocessing function over the entire dataset, use π Datasets map function. You can speed up the map function by setting batched=True to process multiple elements of the dataset at once:
Copied
Now create a batch of examples using DataCollatorWithPadding. Itβs more efficient to dynamically pad the sentences to the longest length in a batch during collation, instead of padding the whole dataset to the maximum length.
PytorchHide Pytorch contentCopied
TensorFlowHide TensorFlow contentCopied
Evaluate
Including a metric during training is often helpful for evaluating your modelβs performance. You can quickly load a evaluation method with the π Evaluate library. For this task, load the seqeval framework (see the π Evaluate quick tour to learn more about how to load and compute a metric). Seqeval actually produces several scores: precision, recall, F1, and accuracy.
Copied
Get the NER labels first, and then create a function that passes your true predictions and true labels to compute to calculate the scores:
Copied
Your compute_metrics function is ready to go now, and youβll return to it when you setup your training.
Train
Before you start training your model, create a map of the expected ids to their labels with id2label and label2id:
Copied
PytorchHide Pytorch content
If you arenβt familiar with finetuning a model with the Trainer, take a look at the basic tutorial here!
Youβre ready to start training your model now! Load DistilBERT with AutoModelForTokenClassification along with the number of expected labels, and the label mappings:
Copied
At this point, only three steps remain:
Define your training hyperparameters in TrainingArguments. The only required parameter is
output_dirwhich specifies where to save your model. Youβll push this model to the Hub by settingpush_to_hub=True(you need to be signed in to BOINC AI to upload your model). At the end of each epoch, the Trainer will evaluate the seqeval scores and save the training checkpoint.Pass the training arguments to Trainer along with the model, dataset, tokenizer, data collator, and
compute_metricsfunction.Call train() to finetune your model.
Copied
Once training is completed, share your model to the Hub with the push_to_hub() method so everyone can use your model:
Copied
TensorFlowHide TensorFlow content
If you arenβt familiar with finetuning a model with Keras, take a look at the basic tutorial here!
To finetune a model in TensorFlow, start by setting up an optimizer function, learning rate schedule, and some training hyperparameters:Copied
Then you can load DistilBERT with TFAutoModelForTokenClassification along with the number of expected labels, and the label mappings:
Copied
Convert your datasets to the tf.data.Dataset format with prepare_tf_dataset():
Copied
Configure the model for training with compile. Note that Transformers models all have a default task-relevant loss function, so you donβt need to specify one unless you want to:
Copied
The last two things to setup before you start training is to compute the seqeval scores from the predictions, and provide a way to push your model to the Hub. Both are done by using Keras callbacks.
Pass your compute_metrics function to KerasMetricCallback:
Copied
Specify where to push your model and tokenizer in the PushToHubCallback:
Copied
Then bundle your callbacks together:
Copied
Finally, youβre ready to start training your model! Call fit with your training and validation datasets, the number of epochs, and your callbacks to finetune the model:
Copied
Once training is completed, your model is automatically uploaded to the Hub so everyone can use it!
For a more in-depth example of how to finetune a model for token classification, take a look at the corresponding PyTorch notebook or TensorFlow notebook.
Inference
Great, now that youβve finetuned a model, you can use it for inference!
Grab some text youβd like to run inference on:
Copied
The simplest way to try out your finetuned model for inference is to use it in a pipeline(). Instantiate a pipeline for NER with your model, and pass your text to it:
Copied
You can also manually replicate the results of the pipeline if youβd like:
PytorchHide Pytorch content
Tokenize the text and return PyTorch tensors:
Copied
Pass your inputs to the model and return the logits:
Copied
Get the class with the highest probability, and use the modelβs id2label mapping to convert it to a text label:
Copied
TensorFlowHide TensorFlow content
Tokenize the text and return TensorFlow tensors:
Copied
Pass your inputs to the model and return the logits:
Copied
Get the class with the highest probability, and use the modelβs id2label mapping to convert it to a text label:
Copied
Last updated