Token classification
Last updated
Last updated
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 on the dataset to detect new entities.
Use your finetuned model for inference.
The task illustrated in this tutorial is supported by the following model architectures:
, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,
Before you begin, make sure you have all the necessary libraries installed:
Copied
We 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
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, the State
token is a part of an entity like Empire State Building
).
0
indicates the token doesnโt correspond to any entity.
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:
Only labeling the first token of a given word. Assign -100
to 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
Copied
PytorchHide Pytorch contentCopied
TensorFlowHide TensorFlow contentCopied
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.
Before you start training your model, create a map of the expected ids to their labels with id2label
and label2id
:
Copied
PytorchHide Pytorch content
Copied
At this point, only three steps remain:
Copied
Copied
TensorFlowHide TensorFlow content
To finetune a model in TensorFlow, start by setting up an optimizer function, learning rate schedule, and some training hyperparameters:Copied
Copied
Copied
Copied
Copied
Copied
Then bundle your callbacks together:
Copied
Copied
Once training is completed, your model is automatically uploaded to the Hub so everyone can use it!
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
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
Mapping all tokens to their corresponding word with the method.
Assigning the label -100
to the special tokens [CLS]
and [SEP]
so theyโre ignored by the PyTorch loss function (see ).
To apply the preprocessing function over the entire dataset, use ๐ Datasets function. You can speed up the map
function by setting batched=True
to process multiple elements of the dataset at once:
Now create a batch of examples using . 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.
Including a metric during training is often helpful for evaluating your modelโs performance. You can quickly load a evaluation method with the ๐ library. For this task, load the framework (see the ๐ Evaluate to learn more about how to load and compute a metric). Seqeval actually produces several scores: precision, recall, F1, and accuracy.
If you arenโt familiar with finetuning a model with the , take a look at the basic tutorial !
Youโre ready to start training your model now! Load DistilBERT with along with the number of expected labels, and the label mappings:
Define your training hyperparameters in . The only required parameter is output_dir
which specifies where to save your model. Youโll push this model to the Hub by setting push_to_hub=True
(you need to be signed in to BOINC AI to upload your model). At the end of each epoch, the will evaluate the seqeval scores and save the training checkpoint.
Pass the training arguments to along with the model, dataset, tokenizer, data collator, and compute_metrics
function.
Call to finetune your model.
Once training is completed, share your model to the Hub with the method so everyone can use your model:
If you arenโt familiar with finetuning a model with Keras, take a look at the basic tutorial !
Then you can load DistilBERT with along with the number of expected labels, and the label mappings:
Convert your datasets to the tf.data.Dataset
format with :
Configure the model for training with . Note that Transformers models all have a default task-relevant loss function, so you donโt need to specify one unless you want to:
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 .
Pass your compute_metrics
function to :
Specify where to push your model and tokenizer in the :
Finally, youโre ready to start training your model! Call with your training and validation datasets, the number of epochs, and your callbacks to finetune the model:
For a more in-depth example of how to finetune a model for token classification, take a look at the corresponding or .
The simplest way to try out your finetuned model for inference is to use it in a . Instantiate a pipeline
for NER with your model, and pass your text to it: