source
stringclasses
470 values
url
stringlengths
49
167
file_type
stringclasses
1 value
chunk
stringlengths
1
512
chunk_id
stringlengths
5
9
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/token_classification.md
https://huggingface.co/docs/transformers/en/tasks/token_classification/#evaluate
.md
... results = seqeval.compute(predictions=true_predictions, references=true_labels) ... return { ... "precision": results["overall_precision"], ... "recall": results["overall_recall"], ... "f1": results["overall_f1"], ... "accuracy": results["overall_accuracy"], ... } ``` Your `compute_metrics` function is ready to go now, and you'll return to it when you setup your training.
82_4_5
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/token_classification.md
https://huggingface.co/docs/transformers/en/tasks/token_classification/#train
.md
Before you start training your model, create a map of the expected ids to their labels with `id2label` and `label2id`: ```py >>> id2label = { ... 0: "O", ... 1: "B-corporation", ... 2: "I-corporation", ... 3: "B-creative-work", ... 4: "I-creative-work", ... 5: "B-group", ... 6: "I-group", ... 7: "B-location", ... 8: "I-location", ... 9: "B-person", ... 10: "I-person", ... 11: "B-product", ... 12: "I-product", ... } >>> label2id = { ... "O": 0,
82_5_0
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/token_classification.md
https://huggingface.co/docs/transformers/en/tasks/token_classification/#train
.md
... 10: "I-person", ... 11: "B-product", ... 12: "I-product", ... } >>> label2id = { ... "O": 0, ... "B-corporation": 1, ... "I-corporation": 2, ... "B-creative-work": 3, ... "I-creative-work": 4, ... "B-group": 5, ... "I-group": 6, ... "B-location": 7, ... "I-location": 8, ... "B-person": 9, ... "I-person": 10, ... "B-product": 11, ... "I-product": 12, ... } ``` <frameworkcontent> <pt> <Tip>
82_5_1
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/token_classification.md
https://huggingface.co/docs/transformers/en/tasks/token_classification/#train
.md
... "I-person": 10, ... "B-product": 11, ... "I-product": 12, ... } ``` <frameworkcontent> <pt> <Tip> If you aren't familiar with finetuning a model with the [`Trainer`], take a look at the basic tutorial [here](../training#train-with-pytorch-trainer)! </Tip> You're ready to start training your model now! Load DistilBERT with [`AutoModelForTokenClassification`] along with the number of expected labels, and the label mappings: ```py
82_5_2
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/token_classification.md
https://huggingface.co/docs/transformers/en/tasks/token_classification/#train
.md
```py >>> from transformers import AutoModelForTokenClassification, TrainingArguments, Trainer
82_5_3
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/token_classification.md
https://huggingface.co/docs/transformers/en/tasks/token_classification/#train
.md
>>> model = AutoModelForTokenClassification.from_pretrained( ... "distilbert/distilbert-base-uncased", num_labels=13, id2label=id2label, label2id=label2id ... ) ``` At this point, only three steps remain:
82_5_4
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/token_classification.md
https://huggingface.co/docs/transformers/en/tasks/token_classification/#train
.md
... ) ``` At this point, only three steps remain: 1. Define your training hyperparameters in [`TrainingArguments`]. 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 Hugging Face to upload your model). At the end of each epoch, the [`Trainer`] will evaluate the seqeval scores and save the training checkpoint.
82_5_5
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/token_classification.md
https://huggingface.co/docs/transformers/en/tasks/token_classification/#train
.md
2. Pass the training arguments to [`Trainer`] along with the model, dataset, tokenizer, data collator, and `compute_metrics` function. 3. Call [`~Trainer.train`] to finetune your model. ```py >>> training_args = TrainingArguments( ... output_dir="my_awesome_wnut_model", ... learning_rate=2e-5, ... per_device_train_batch_size=16, ... per_device_eval_batch_size=16, ... num_train_epochs=2, ... weight_decay=0.01, ... eval_strategy="epoch", ... save_strategy="epoch",
82_5_6
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/token_classification.md
https://huggingface.co/docs/transformers/en/tasks/token_classification/#train
.md
... num_train_epochs=2, ... weight_decay=0.01, ... eval_strategy="epoch", ... save_strategy="epoch", ... load_best_model_at_end=True, ... push_to_hub=True, ... )
82_5_7
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/token_classification.md
https://huggingface.co/docs/transformers/en/tasks/token_classification/#train
.md
>>> trainer = Trainer( ... model=model, ... args=training_args, ... train_dataset=tokenized_wnut["train"], ... eval_dataset=tokenized_wnut["test"], ... processing_class=tokenizer, ... data_collator=data_collator, ... compute_metrics=compute_metrics, ... )
82_5_8
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/token_classification.md
https://huggingface.co/docs/transformers/en/tasks/token_classification/#train
.md
>>> trainer.train() ``` Once training is completed, share your model to the Hub with the [`~transformers.Trainer.push_to_hub`] method so everyone can use your model: ```py >>> trainer.push_to_hub() ``` </pt> <tf> <Tip> If you aren't familiar with finetuning a model with Keras, take a look at the basic tutorial [here](../training#train-a-tensorflow-model-with-keras)! </Tip>
82_5_9
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/token_classification.md
https://huggingface.co/docs/transformers/en/tasks/token_classification/#train
.md
</Tip> To finetune a model in TensorFlow, start by setting up an optimizer function, learning rate schedule, and some training hyperparameters: ```py >>> from transformers import create_optimizer
82_5_10
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/token_classification.md
https://huggingface.co/docs/transformers/en/tasks/token_classification/#train
.md
>>> batch_size = 16 >>> num_train_epochs = 3 >>> num_train_steps = (len(tokenized_wnut["train"]) // batch_size) * num_train_epochs >>> optimizer, lr_schedule = create_optimizer( ... init_lr=2e-5, ... num_train_steps=num_train_steps, ... weight_decay_rate=0.01, ... num_warmup_steps=0, ... ) ``` Then you can load DistilBERT with [`TFAutoModelForTokenClassification`] along with the number of expected labels, and the label mappings: ```py
82_5_11
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/token_classification.md
https://huggingface.co/docs/transformers/en/tasks/token_classification/#train
.md
```py >>> from transformers import TFAutoModelForTokenClassification
82_5_12
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/token_classification.md
https://huggingface.co/docs/transformers/en/tasks/token_classification/#train
.md
>>> model = TFAutoModelForTokenClassification.from_pretrained( ... "distilbert/distilbert-base-uncased", num_labels=13, id2label=id2label, label2id=label2id ... ) ``` Convert your datasets to the `tf.data.Dataset` format with [`~transformers.TFPreTrainedModel.prepare_tf_dataset`]: ```py >>> tf_train_set = model.prepare_tf_dataset( ... tokenized_wnut["train"], ... shuffle=True, ... batch_size=16, ... collate_fn=data_collator, ... )
82_5_13
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/token_classification.md
https://huggingface.co/docs/transformers/en/tasks/token_classification/#train
.md
>>> tf_validation_set = model.prepare_tf_dataset( ... tokenized_wnut["validation"], ... shuffle=False, ... batch_size=16, ... collate_fn=data_collator, ... ) ``` Configure the model for training with [`compile`](https://keras.io/api/models/model_training_apis/#compile-method). Note that Transformers models all have a default task-relevant loss function, so you don't need to specify one unless you want to: ```py >>> import tensorflow as tf
82_5_14
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/token_classification.md
https://huggingface.co/docs/transformers/en/tasks/token_classification/#train
.md
>>> model.compile(optimizer=optimizer) # No loss argument! ``` 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](../main_classes/keras_callbacks). Pass your `compute_metrics` function to [`~transformers.KerasMetricCallback`]: ```py >>> from transformers.keras_callbacks import KerasMetricCallback
82_5_15
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/token_classification.md
https://huggingface.co/docs/transformers/en/tasks/token_classification/#train
.md
>>> metric_callback = KerasMetricCallback(metric_fn=compute_metrics, eval_dataset=tf_validation_set) ``` Specify where to push your model and tokenizer in the [`~transformers.PushToHubCallback`]: ```py >>> from transformers.keras_callbacks import PushToHubCallback
82_5_16
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/token_classification.md
https://huggingface.co/docs/transformers/en/tasks/token_classification/#train
.md
>>> push_to_hub_callback = PushToHubCallback( ... output_dir="my_awesome_wnut_model", ... tokenizer=tokenizer, ... ) ``` Then bundle your callbacks together: ```py >>> callbacks = [metric_callback, push_to_hub_callback] ``` Finally, you're ready to start training your model! Call [`fit`](https://keras.io/api/models/model_training_apis/#fit-method) with your training and validation datasets, the number of epochs, and your callbacks to finetune the model: ```py
82_5_17
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/token_classification.md
https://huggingface.co/docs/transformers/en/tasks/token_classification/#train
.md
```py >>> model.fit(x=tf_train_set, validation_data=tf_validation_set, epochs=3, callbacks=callbacks) ``` Once training is completed, your model is automatically uploaded to the Hub so everyone can use it! </tf> </frameworkcontent> <Tip> For a more in-depth example of how to finetune a model for token classification, take a look at the corresponding [PyTorch notebook](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/token_classification.ipynb)
82_5_18
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/token_classification.md
https://huggingface.co/docs/transformers/en/tasks/token_classification/#train
.md
or [TensorFlow notebook](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/token_classification-tf.ipynb). </Tip>
82_5_19
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/token_classification.md
https://huggingface.co/docs/transformers/en/tasks/token_classification/#inference
.md
Great, now that you've finetuned a model, you can use it for inference! Grab some text you'd like to run inference on: ```py >>> text = "The Golden State Warriors are an American professional basketball team based in San Francisco." ``` 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: ```py >>> from transformers import pipeline
82_6_0
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/token_classification.md
https://huggingface.co/docs/transformers/en/tasks/token_classification/#inference
.md
>>> classifier = pipeline("ner", model="stevhliu/my_awesome_wnut_model") >>> classifier(text) [{'entity': 'B-location', 'score': 0.42658573, 'index': 2, 'word': 'golden', 'start': 4, 'end': 10}, {'entity': 'I-location', 'score': 0.35856336, 'index': 3, 'word': 'state', 'start': 11, 'end': 16}, {'entity': 'B-group', 'score': 0.3064001, 'index': 4, 'word': 'warriors', 'start': 17, 'end': 25}, {'entity': 'B-location', 'score': 0.65523505, 'index': 13, 'word': 'san', 'start': 80, 'end': 83},
82_6_1
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/token_classification.md
https://huggingface.co/docs/transformers/en/tasks/token_classification/#inference
.md
'start': 17, 'end': 25}, {'entity': 'B-location', 'score': 0.65523505, 'index': 13, 'word': 'san', 'start': 80, 'end': 83}, {'entity': 'B-location', 'score': 0.4668663, 'index': 14, 'word': 'francisco', 'start': 84, 'end': 93}] ``` You can also manually replicate the results of the `pipeline` if you'd like: <frameworkcontent> <pt> Tokenize the text and return PyTorch tensors: ```py >>> from transformers import AutoTokenizer
82_6_2
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/token_classification.md
https://huggingface.co/docs/transformers/en/tasks/token_classification/#inference
.md
>>> tokenizer = AutoTokenizer.from_pretrained("stevhliu/my_awesome_wnut_model") >>> inputs = tokenizer(text, return_tensors="pt") ``` Pass your inputs to the model and return the `logits`: ```py >>> from transformers import AutoModelForTokenClassification
82_6_3
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/token_classification.md
https://huggingface.co/docs/transformers/en/tasks/token_classification/#inference
.md
>>> model = AutoModelForTokenClassification.from_pretrained("stevhliu/my_awesome_wnut_model") >>> with torch.no_grad(): ... logits = model(**inputs).logits ``` Get the class with the highest probability, and use the model's `id2label` mapping to convert it to a text label: ```py >>> predictions = torch.argmax(logits, dim=2) >>> predicted_token_class = [model.config.id2label[t.item()] for t in predictions[0]] >>> predicted_token_class ['O', 'O', 'B-location', 'I-location', 'B-group', 'O', 'O', 'O',
82_6_4
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/token_classification.md
https://huggingface.co/docs/transformers/en/tasks/token_classification/#inference
.md
>>> predicted_token_class ['O', 'O', 'B-location', 'I-location', 'B-group', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'B-location', 'B-location', 'O', 'O'] ``` </pt> <tf> Tokenize the text and return TensorFlow tensors: ```py >>> from transformers import AutoTokenizer
82_6_5
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/token_classification.md
https://huggingface.co/docs/transformers/en/tasks/token_classification/#inference
.md
>>> tokenizer = AutoTokenizer.from_pretrained("stevhliu/my_awesome_wnut_model") >>> inputs = tokenizer(text, return_tensors="tf") ``` Pass your inputs to the model and return the `logits`: ```py >>> from transformers import TFAutoModelForTokenClassification
82_6_6
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/token_classification.md
https://huggingface.co/docs/transformers/en/tasks/token_classification/#inference
.md
>>> model = TFAutoModelForTokenClassification.from_pretrained("stevhliu/my_awesome_wnut_model") >>> logits = model(**inputs).logits ``` Get the class with the highest probability, and use the model's `id2label` mapping to convert it to a text label: ```py >>> predicted_token_class_ids = tf.math.argmax(logits, axis=-1) >>> predicted_token_class = [model.config.id2label[t] for t in predicted_token_class_ids[0].numpy().tolist()] >>> predicted_token_class ['O', 'O', 'B-location', 'I-location', 'B-group',
82_6_7
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/token_classification.md
https://huggingface.co/docs/transformers/en/tasks/token_classification/#inference
.md
>>> predicted_token_class ['O', 'O', 'B-location', 'I-location', 'B-group', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'B-location', 'B-location', 'O', 'O'] ``` </tf> </frameworkcontent>
82_6_8
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/sequence_classification.md
https://huggingface.co/docs/transformers/en/tasks/sequence_classification/
.md
<!--Copyright 2022 The HuggingFace Team. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
83_0_0
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/sequence_classification.md
https://huggingface.co/docs/transformers/en/tasks/sequence_classification/
.md
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be rendered properly in your Markdown viewer. -->
83_0_1
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/sequence_classification.md
https://huggingface.co/docs/transformers/en/tasks/sequence_classification/#text-classification
.md
[[open-in-colab]] <Youtube id="leNG9fN9FQU"/> Text classification is a common NLP task that assigns a label or class to text. Some of the largest companies run text classification in production for a wide range of practical applications. One of the most popular forms of text classification is sentiment analysis, which assigns a label like 🙂 positive, 🙁 negative, or 😐 neutral to a sequence of text. This guide will show you how to:
83_1_0
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/sequence_classification.md
https://huggingface.co/docs/transformers/en/tasks/sequence_classification/#text-classification
.md
This guide will show you how to: 1. Finetune [DistilBERT](https://huggingface.co/distilbert/distilbert-base-uncased) on the [IMDb](https://huggingface.co/datasets/imdb) dataset to determine whether a movie review is positive or negative. 2. Use your finetuned model for inference. <Tip> To see all architectures and checkpoints compatible with this task, we recommend checking the [task-page](https://huggingface.co/tasks/text-classification). </Tip>
83_1_1
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/sequence_classification.md
https://huggingface.co/docs/transformers/en/tasks/sequence_classification/#text-classification
.md
</Tip> Before you begin, make sure you have all the necessary libraries installed: ```bash pip install transformers datasets evaluate accelerate ``` We encourage you to login to your Hugging Face account so you can upload and share your model with the community. When prompted, enter your token to login: ```py >>> from huggingface_hub import notebook_login
83_1_2
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/sequence_classification.md
https://huggingface.co/docs/transformers/en/tasks/sequence_classification/#text-classification
.md
>>> notebook_login() ```
83_1_3
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/sequence_classification.md
https://huggingface.co/docs/transformers/en/tasks/sequence_classification/#load-imdb-dataset
.md
Start by loading the IMDb dataset from the 🤗 Datasets library: ```py >>> from datasets import load_dataset
83_2_0
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/sequence_classification.md
https://huggingface.co/docs/transformers/en/tasks/sequence_classification/#load-imdb-dataset
.md
>>> imdb = load_dataset("imdb") ``` Then take a look at an example: ```py >>> imdb["test"][0] { "label": 0,
83_2_1
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/sequence_classification.md
https://huggingface.co/docs/transformers/en/tasks/sequence_classification/#load-imdb-dataset
.md
"text": "I love sci-fi and am willing to put up with a lot. Sci-fi movies/TV are usually underfunded, under-appreciated and misunderstood. I tried to like this, I really did, but it is to good TV sci-fi as Babylon 5 is to Star Trek (the original). Silly prosthetics, cheap cardboard sets, stilted dialogues, CG that doesn't match the background, and painfully one-dimensional characters cannot be overcome with a 'sci-fi' setting. (I'm sure there are those of you out there who think Babylon 5 is good sci-fi
83_2_2
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/sequence_classification.md
https://huggingface.co/docs/transformers/en/tasks/sequence_classification/#load-imdb-dataset
.md
cannot be overcome with a 'sci-fi' setting. (I'm sure there are those of you out there who think Babylon 5 is good sci-fi TV. It's not. It's clichéd and uninspiring.) While US viewers might like emotion and character development, sci-fi is a genre that does not take itself seriously (cf. Star Trek). It may treat important issues, yet not as a serious philosophy. It's really difficult to care about the characters here as they are not simply foolish, just missing a spark of life. Their actions and reactions
83_2_3
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/sequence_classification.md
https://huggingface.co/docs/transformers/en/tasks/sequence_classification/#load-imdb-dataset
.md
to care about the characters here as they are not simply foolish, just missing a spark of life. Their actions and reactions are wooden and predictable, often painful to watch. The makers of Earth KNOW it's rubbish as they have to always say \"Gene Roddenberry's Earth...\" otherwise people would not continue watching. Roddenberry's ashes must be turning in their orbit as this dull, cheap, poorly edited (watching it without advert breaks really brings this home) trudging Trabant of a show lumbers into space.
83_2_4
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/sequence_classification.md
https://huggingface.co/docs/transformers/en/tasks/sequence_classification/#load-imdb-dataset
.md
cheap, poorly edited (watching it without advert breaks really brings this home) trudging Trabant of a show lumbers into space. Spoiler. So, kill off a main character. And then bring him back as another actor. Jeeez! Dallas all over again.",
83_2_5
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/sequence_classification.md
https://huggingface.co/docs/transformers/en/tasks/sequence_classification/#load-imdb-dataset
.md
} ``` There are two fields in this dataset: - `text`: the movie review text. - `label`: a value that is either `0` for a negative review or `1` for a positive review.
83_2_6
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/sequence_classification.md
https://huggingface.co/docs/transformers/en/tasks/sequence_classification/#preprocess
.md
The next step is to load a DistilBERT tokenizer to preprocess the `text` field: ```py >>> from transformers import AutoTokenizer
83_3_0
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/sequence_classification.md
https://huggingface.co/docs/transformers/en/tasks/sequence_classification/#preprocess
.md
>>> tokenizer = AutoTokenizer.from_pretrained("distilbert/distilbert-base-uncased") ``` Create a preprocessing function to tokenize `text` and truncate sequences to be no longer than DistilBERT's maximum input length: ```py >>> def preprocess_function(examples): ... return tokenizer(examples["text"], truncation=True) ```
83_3_1
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/sequence_classification.md
https://huggingface.co/docs/transformers/en/tasks/sequence_classification/#preprocess
.md
```py >>> def preprocess_function(examples): ... return tokenizer(examples["text"], truncation=True) ``` To apply the preprocessing function over the entire dataset, use 🤗 Datasets [`~datasets.Dataset.map`] function. You can speed up `map` by setting `batched=True` to process multiple elements of the dataset at once: ```py tokenized_imdb = imdb.map(preprocess_function, batched=True) ```
83_3_2
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/sequence_classification.md
https://huggingface.co/docs/transformers/en/tasks/sequence_classification/#preprocess
.md
```py tokenized_imdb = imdb.map(preprocess_function, batched=True) ``` 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. <frameworkcontent> <pt> ```py >>> from transformers import DataCollatorWithPadding
83_3_3
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/sequence_classification.md
https://huggingface.co/docs/transformers/en/tasks/sequence_classification/#preprocess
.md
>>> data_collator = DataCollatorWithPadding(tokenizer=tokenizer) ``` </pt> <tf> ```py >>> from transformers import DataCollatorWithPadding >>> data_collator = DataCollatorWithPadding(tokenizer=tokenizer, return_tensors="tf") ``` </tf> </frameworkcontent>
83_3_4
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/sequence_classification.md
https://huggingface.co/docs/transformers/en/tasks/sequence_classification/#evaluate
.md
Including a metric during training is often helpful for evaluating your model's performance. You can quickly load a evaluation method with the 🤗 [Evaluate](https://huggingface.co/docs/evaluate/index) library. For this task, load the [accuracy](https://huggingface.co/spaces/evaluate-metric/accuracy) metric (see the 🤗 Evaluate [quick tour](https://huggingface.co/docs/evaluate/a_quick_tour) to learn more about how to load and compute a metric): ```py >>> import evaluate
83_4_0
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/sequence_classification.md
https://huggingface.co/docs/transformers/en/tasks/sequence_classification/#evaluate
.md
>>> accuracy = evaluate.load("accuracy") ``` Then create a function that passes your predictions and labels to [`~evaluate.EvaluationModule.compute`] to calculate the accuracy: ```py >>> import numpy as np
83_4_1
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/sequence_classification.md
https://huggingface.co/docs/transformers/en/tasks/sequence_classification/#evaluate
.md
>>> def compute_metrics(eval_pred): ... predictions, labels = eval_pred ... predictions = np.argmax(predictions, axis=1) ... return accuracy.compute(predictions=predictions, references=labels) ``` Your `compute_metrics` function is ready to go now, and you'll return to it when you setup your training.
83_4_2
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/sequence_classification.md
https://huggingface.co/docs/transformers/en/tasks/sequence_classification/#train
.md
Before you start training your model, create a map of the expected ids to their labels with `id2label` and `label2id`: ```py >>> id2label = {0: "NEGATIVE", 1: "POSITIVE"} >>> label2id = {"NEGATIVE": 0, "POSITIVE": 1} ``` <frameworkcontent> <pt> <Tip> If you aren't familiar with finetuning a model with the [`Trainer`], take a look at the basic tutorial [here](../training#train-with-pytorch-trainer)! </Tip>
83_5_0
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/sequence_classification.md
https://huggingface.co/docs/transformers/en/tasks/sequence_classification/#train
.md
</Tip> You're ready to start training your model now! Load DistilBERT with [`AutoModelForSequenceClassification`] along with the number of expected labels, and the label mappings: ```py >>> from transformers import AutoModelForSequenceClassification, TrainingArguments, Trainer
83_5_1
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/sequence_classification.md
https://huggingface.co/docs/transformers/en/tasks/sequence_classification/#train
.md
>>> model = AutoModelForSequenceClassification.from_pretrained( ... "distilbert/distilbert-base-uncased", num_labels=2, id2label=id2label, label2id=label2id ... ) ``` At this point, only three steps remain:
83_5_2
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/sequence_classification.md
https://huggingface.co/docs/transformers/en/tasks/sequence_classification/#train
.md
... ) ``` At this point, only three steps remain: 1. Define your training hyperparameters in [`TrainingArguments`]. 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 Hugging Face to upload your model). At the end of each epoch, the [`Trainer`] will evaluate the accuracy and save the training checkpoint.
83_5_3
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/sequence_classification.md
https://huggingface.co/docs/transformers/en/tasks/sequence_classification/#train
.md
2. Pass the training arguments to [`Trainer`] along with the model, dataset, tokenizer, data collator, and `compute_metrics` function. 3. Call [`~Trainer.train`] to finetune your model. ```py >>> training_args = TrainingArguments( ... output_dir="my_awesome_model", ... learning_rate=2e-5, ... per_device_train_batch_size=16, ... per_device_eval_batch_size=16, ... num_train_epochs=2, ... weight_decay=0.01, ... eval_strategy="epoch", ... save_strategy="epoch",
83_5_4
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/sequence_classification.md
https://huggingface.co/docs/transformers/en/tasks/sequence_classification/#train
.md
... num_train_epochs=2, ... weight_decay=0.01, ... eval_strategy="epoch", ... save_strategy="epoch", ... load_best_model_at_end=True, ... push_to_hub=True, ... )
83_5_5
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/sequence_classification.md
https://huggingface.co/docs/transformers/en/tasks/sequence_classification/#train
.md
>>> trainer = Trainer( ... model=model, ... args=training_args, ... train_dataset=tokenized_imdb["train"], ... eval_dataset=tokenized_imdb["test"], ... processing_class=tokenizer, ... data_collator=data_collator, ... compute_metrics=compute_metrics, ... )
83_5_6
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/sequence_classification.md
https://huggingface.co/docs/transformers/en/tasks/sequence_classification/#train
.md
>>> trainer.train() ``` <Tip> [`Trainer`] applies dynamic padding by default when you pass `tokenizer` to it. In this case, you don't need to specify a data collator explicitly. </Tip> Once training is completed, share your model to the Hub with the [`~transformers.Trainer.push_to_hub`] method so everyone can use your model: ```py >>> trainer.push_to_hub() ``` </pt> <tf> <Tip>
83_5_7
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/sequence_classification.md
https://huggingface.co/docs/transformers/en/tasks/sequence_classification/#train
.md
```py >>> trainer.push_to_hub() ``` </pt> <tf> <Tip> If you aren't familiar with finetuning a model with Keras, take a look at the basic tutorial [here](../training#train-a-tensorflow-model-with-keras)! </Tip> To finetune a model in TensorFlow, start by setting up an optimizer function, learning rate schedule, and some training hyperparameters: ```py >>> from transformers import create_optimizer >>> import tensorflow as tf
83_5_8
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/sequence_classification.md
https://huggingface.co/docs/transformers/en/tasks/sequence_classification/#train
.md
>>> batch_size = 16 >>> num_epochs = 5 >>> batches_per_epoch = len(tokenized_imdb["train"]) // batch_size >>> total_train_steps = int(batches_per_epoch * num_epochs) >>> optimizer, schedule = create_optimizer(init_lr=2e-5, num_warmup_steps=0, num_train_steps=total_train_steps) ``` Then you can load DistilBERT with [`TFAutoModelForSequenceClassification`] along with the number of expected labels, and the label mappings: ```py >>> from transformers import TFAutoModelForSequenceClassification
83_5_9
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/sequence_classification.md
https://huggingface.co/docs/transformers/en/tasks/sequence_classification/#train
.md
>>> model = TFAutoModelForSequenceClassification.from_pretrained( ... "distilbert/distilbert-base-uncased", num_labels=2, id2label=id2label, label2id=label2id ... ) ``` Convert your datasets to the `tf.data.Dataset` format with [`~transformers.TFPreTrainedModel.prepare_tf_dataset`]: ```py >>> tf_train_set = model.prepare_tf_dataset( ... tokenized_imdb["train"], ... shuffle=True, ... batch_size=16, ... collate_fn=data_collator, ... )
83_5_10
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/sequence_classification.md
https://huggingface.co/docs/transformers/en/tasks/sequence_classification/#train
.md
>>> tf_validation_set = model.prepare_tf_dataset( ... tokenized_imdb["test"], ... shuffle=False, ... batch_size=16, ... collate_fn=data_collator, ... ) ``` Configure the model for training with [`compile`](https://keras.io/api/models/model_training_apis/#compile-method). Note that Transformers models all have a default task-relevant loss function, so you don't need to specify one unless you want to: ```py >>> import tensorflow as tf
83_5_11
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/sequence_classification.md
https://huggingface.co/docs/transformers/en/tasks/sequence_classification/#train
.md
>>> model.compile(optimizer=optimizer) # No loss argument! ``` The last two things to setup before you start training is to compute the accuracy from the predictions, and provide a way to push your model to the Hub. Both are done by using [Keras callbacks](../main_classes/keras_callbacks). Pass your `compute_metrics` function to [`~transformers.KerasMetricCallback`]: ```py >>> from transformers.keras_callbacks import KerasMetricCallback
83_5_12
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/sequence_classification.md
https://huggingface.co/docs/transformers/en/tasks/sequence_classification/#train
.md
>>> metric_callback = KerasMetricCallback(metric_fn=compute_metrics, eval_dataset=tf_validation_set) ``` Specify where to push your model and tokenizer in the [`~transformers.PushToHubCallback`]: ```py >>> from transformers.keras_callbacks import PushToHubCallback
83_5_13
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/sequence_classification.md
https://huggingface.co/docs/transformers/en/tasks/sequence_classification/#train
.md
>>> push_to_hub_callback = PushToHubCallback( ... output_dir="my_awesome_model", ... tokenizer=tokenizer, ... ) ``` Then bundle your callbacks together: ```py >>> callbacks = [metric_callback, push_to_hub_callback] ``` Finally, you're ready to start training your model! Call [`fit`](https://keras.io/api/models/model_training_apis/#fit-method) with your training and validation datasets, the number of epochs, and your callbacks to finetune the model: ```py
83_5_14
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/sequence_classification.md
https://huggingface.co/docs/transformers/en/tasks/sequence_classification/#train
.md
```py >>> model.fit(x=tf_train_set, validation_data=tf_validation_set, epochs=3, callbacks=callbacks) ``` Once training is completed, your model is automatically uploaded to the Hub so everyone can use it! </tf> </frameworkcontent> <Tip> For a more in-depth example of how to finetune a model for text classification, take a look at the corresponding [PyTorch notebook](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/text_classification.ipynb)
83_5_15
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/sequence_classification.md
https://huggingface.co/docs/transformers/en/tasks/sequence_classification/#train
.md
[PyTorch notebook](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/text_classification.ipynb) or [TensorFlow notebook](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/text_classification-tf.ipynb). </Tip>
83_5_16
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/sequence_classification.md
https://huggingface.co/docs/transformers/en/tasks/sequence_classification/#inference
.md
Great, now that you've finetuned a model, you can use it for inference! Grab some text you'd like to run inference on: ```py >>> text = "This was a masterpiece. Not completely faithful to the books, but enthralling from beginning to end. Might be my favorite of the three." ``` The simplest way to try out your finetuned model for inference is to use it in a [`pipeline`]. Instantiate a `pipeline` for sentiment analysis with your model, and pass your text to it: ```py
83_6_0
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/sequence_classification.md
https://huggingface.co/docs/transformers/en/tasks/sequence_classification/#inference
.md
```py >>> from transformers import pipeline
83_6_1
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/sequence_classification.md
https://huggingface.co/docs/transformers/en/tasks/sequence_classification/#inference
.md
>>> classifier = pipeline("sentiment-analysis", model="stevhliu/my_awesome_model") >>> classifier(text) [{'label': 'POSITIVE', 'score': 0.9994940757751465}] ``` You can also manually replicate the results of the `pipeline` if you'd like: <frameworkcontent> <pt> Tokenize the text and return PyTorch tensors: ```py >>> from transformers import AutoTokenizer
83_6_2
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/sequence_classification.md
https://huggingface.co/docs/transformers/en/tasks/sequence_classification/#inference
.md
>>> tokenizer = AutoTokenizer.from_pretrained("stevhliu/my_awesome_model") >>> inputs = tokenizer(text, return_tensors="pt") ``` Pass your inputs to the model and return the `logits`: ```py >>> from transformers import AutoModelForSequenceClassification
83_6_3
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/sequence_classification.md
https://huggingface.co/docs/transformers/en/tasks/sequence_classification/#inference
.md
>>> model = AutoModelForSequenceClassification.from_pretrained("stevhliu/my_awesome_model") >>> with torch.no_grad(): ... logits = model(**inputs).logits ``` Get the class with the highest probability, and use the model's `id2label` mapping to convert it to a text label: ```py >>> predicted_class_id = logits.argmax().item() >>> model.config.id2label[predicted_class_id] 'POSITIVE' ``` </pt> <tf> Tokenize the text and return TensorFlow tensors: ```py >>> from transformers import AutoTokenizer
83_6_4
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/sequence_classification.md
https://huggingface.co/docs/transformers/en/tasks/sequence_classification/#inference
.md
>>> tokenizer = AutoTokenizer.from_pretrained("stevhliu/my_awesome_model") >>> inputs = tokenizer(text, return_tensors="tf") ``` Pass your inputs to the model and return the `logits`: ```py >>> from transformers import TFAutoModelForSequenceClassification
83_6_5
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/sequence_classification.md
https://huggingface.co/docs/transformers/en/tasks/sequence_classification/#inference
.md
>>> model = TFAutoModelForSequenceClassification.from_pretrained("stevhliu/my_awesome_model") >>> logits = model(**inputs).logits ``` Get the class with the highest probability, and use the model's `id2label` mapping to convert it to a text label: ```py >>> predicted_class_id = int(tf.math.argmax(logits, axis=-1)[0]) >>> model.config.id2label[predicted_class_id] 'POSITIVE' ``` </tf> </frameworkcontent>
83_6_6
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/knowledge_distillation_for_image_classification.md
https://huggingface.co/docs/transformers/en/tasks/knowledge_distillation_for_image_classification/
.md
<!--Copyright 2023 The HuggingFace Team. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
84_0_0
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/knowledge_distillation_for_image_classification.md
https://huggingface.co/docs/transformers/en/tasks/knowledge_distillation_for_image_classification/
.md
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be rendered properly in your Markdown viewer. -->
84_0_1
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/knowledge_distillation_for_image_classification.md
https://huggingface.co/docs/transformers/en/tasks/knowledge_distillation_for_image_classification/#knowledge-distillation-for-computer-vision
.md
[[open-in-colab]]
84_1_0
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/knowledge_distillation_for_image_classification.md
https://huggingface.co/docs/transformers/en/tasks/knowledge_distillation_for_image_classification/#knowledge-distillation-for-computer-vision
.md
Knowledge distillation is a technique used to transfer knowledge from a larger, more complex model (teacher) to a smaller, simpler model (student). To distill knowledge from one model to another, we take a pre-trained teacher model trained on a certain task (image classification for this case) and randomly initialize a student model to be trained on image classification. Next, we train the student model to minimize the difference between its outputs and the teacher's outputs, thus making it mimic the
84_1_1
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/knowledge_distillation_for_image_classification.md
https://huggingface.co/docs/transformers/en/tasks/knowledge_distillation_for_image_classification/#knowledge-distillation-for-computer-vision
.md
we train the student model to minimize the difference between its outputs and the teacher's outputs, thus making it mimic the behavior. It was first introduced in [Distilling the Knowledge in a Neural Network by Hinton et al](https://arxiv.org/abs/1503.02531). In this guide, we will do task-specific knowledge distillation. We will use the [beans dataset](https://huggingface.co/datasets/beans) for this.
84_1_2
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/knowledge_distillation_for_image_classification.md
https://huggingface.co/docs/transformers/en/tasks/knowledge_distillation_for_image_classification/#knowledge-distillation-for-computer-vision
.md
This guide demonstrates how you can distill a [fine-tuned ViT model](https://huggingface.co/merve/vit-mobilenet-beans-224) (teacher model) to a [MobileNet](https://huggingface.co/google/mobilenet_v2_1.4_224) (student model) using the [TrainerAPI](https://huggingface.co/docs/transformers/en/main_classes/trainer#trainer) of 🤗 Transformers. Let's install the libraries needed for distillation and evaluating the process. ```bash pip install transformers datasets accelerate tensorboard evaluate --upgrade
84_1_3
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/knowledge_distillation_for_image_classification.md
https://huggingface.co/docs/transformers/en/tasks/knowledge_distillation_for_image_classification/#knowledge-distillation-for-computer-vision
.md
```bash pip install transformers datasets accelerate tensorboard evaluate --upgrade ``` In this example, we are using the `merve/beans-vit-224` model as teacher model. It's an image classification model, based on `google/vit-base-patch16-224-in21k` fine-tuned on beans dataset. We will distill this model to a randomly initialized MobileNetV2. We will now load the dataset. ```python from datasets import load_dataset
84_1_4
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/knowledge_distillation_for_image_classification.md
https://huggingface.co/docs/transformers/en/tasks/knowledge_distillation_for_image_classification/#knowledge-distillation-for-computer-vision
.md
dataset = load_dataset("beans") ``` We can use an image processor from either of the models, as in this case they return the same output with same resolution. We will use the `map()` method of `dataset` to apply the preprocessing to every split of the dataset. ```python from transformers import AutoImageProcessor teacher_processor = AutoImageProcessor.from_pretrained("merve/beans-vit-224") def process(examples): processed_inputs = teacher_processor(examples["image"]) return processed_inputs
84_1_5
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/knowledge_distillation_for_image_classification.md
https://huggingface.co/docs/transformers/en/tasks/knowledge_distillation_for_image_classification/#knowledge-distillation-for-computer-vision
.md
processed_datasets = dataset.map(process, batched=True) ```
84_1_6
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/knowledge_distillation_for_image_classification.md
https://huggingface.co/docs/transformers/en/tasks/knowledge_distillation_for_image_classification/#knowledge-distillation-for-computer-vision
.md
Essentially, we want the student model (a randomly initialized MobileNet) to mimic the teacher model (fine-tuned vision transformer). To achieve this, we first get the logits output from the teacher and the student. Then, we divide each of them by the parameter `temperature` which controls the importance of each soft target. A parameter called `lambda` weighs the importance of the distillation loss. In this example, we will use `temperature=5` and `lambda=0.5`. We will use the Kullback-Leibler Divergence
84_1_7
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/knowledge_distillation_for_image_classification.md
https://huggingface.co/docs/transformers/en/tasks/knowledge_distillation_for_image_classification/#knowledge-distillation-for-computer-vision
.md
distillation loss. In this example, we will use `temperature=5` and `lambda=0.5`. We will use the Kullback-Leibler Divergence loss to compute the divergence between the student and teacher. Given two data P and Q, KL Divergence explains how much extra information we need to represent P using Q. If two are identical, their KL divergence is zero, as there's no other information needed to explain P from Q. Thus, in the context of knowledge distillation, KL divergence is useful.
84_1_8
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/knowledge_distillation_for_image_classification.md
https://huggingface.co/docs/transformers/en/tasks/knowledge_distillation_for_image_classification/#knowledge-distillation-for-computer-vision
.md
```python from transformers import TrainingArguments, Trainer import torch import torch.nn as nn import torch.nn.functional as F from accelerate.test_utils.testing import get_backend
84_1_9
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/knowledge_distillation_for_image_classification.md
https://huggingface.co/docs/transformers/en/tasks/knowledge_distillation_for_image_classification/#knowledge-distillation-for-computer-vision
.md
class ImageDistilTrainer(Trainer): def __init__(self, teacher_model=None, student_model=None, temperature=None, lambda_param=None, *args, **kwargs): super().__init__(model=student_model, *args, **kwargs) self.teacher = teacher_model self.student = student_model self.loss_function = nn.KLDivLoss(reduction="batchmean") device, _, _ = get_backend() # automatically detects the underlying device type (CUDA, CPU, XPU, MPS, etc.) self.teacher.to(device) self.teacher.eval() self.temperature = temperature
84_1_10
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/knowledge_distillation_for_image_classification.md
https://huggingface.co/docs/transformers/en/tasks/knowledge_distillation_for_image_classification/#knowledge-distillation-for-computer-vision
.md
self.teacher.to(device) self.teacher.eval() self.temperature = temperature self.lambda_param = lambda_param
84_1_11
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/knowledge_distillation_for_image_classification.md
https://huggingface.co/docs/transformers/en/tasks/knowledge_distillation_for_image_classification/#knowledge-distillation-for-computer-vision
.md
def compute_loss(self, student, inputs, return_outputs=False): student_output = self.student(**inputs) with torch.no_grad(): teacher_output = self.teacher(**inputs) # Compute soft targets for teacher and student soft_teacher = F.softmax(teacher_output.logits / self.temperature, dim=-1) soft_student = F.log_softmax(student_output.logits / self.temperature, dim=-1) # Compute the loss distillation_loss = self.loss_function(soft_student, soft_teacher) * (self.temperature ** 2)
84_1_12
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/knowledge_distillation_for_image_classification.md
https://huggingface.co/docs/transformers/en/tasks/knowledge_distillation_for_image_classification/#knowledge-distillation-for-computer-vision
.md
# Compute the loss distillation_loss = self.loss_function(soft_student, soft_teacher) * (self.temperature ** 2) # Compute the true label loss student_target_loss = student_output.loss
84_1_13
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/knowledge_distillation_for_image_classification.md
https://huggingface.co/docs/transformers/en/tasks/knowledge_distillation_for_image_classification/#knowledge-distillation-for-computer-vision
.md
# Compute the true label loss student_target_loss = student_output.loss # Calculate final loss loss = (1. - self.lambda_param) * student_target_loss + self.lambda_param * distillation_loss return (loss, student_output) if return_outputs else loss ``` We will now login to Hugging Face Hub so we can push our model to the Hugging Face Hub through the `Trainer`. ```python from huggingface_hub import notebook_login
84_1_14
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/knowledge_distillation_for_image_classification.md
https://huggingface.co/docs/transformers/en/tasks/knowledge_distillation_for_image_classification/#knowledge-distillation-for-computer-vision
.md
notebook_login() ``` Let's set the `TrainingArguments`, the teacher model and the student model. ```python from transformers import AutoModelForImageClassification, MobileNetV2Config, MobileNetV2ForImageClassification
84_1_15
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/knowledge_distillation_for_image_classification.md
https://huggingface.co/docs/transformers/en/tasks/knowledge_distillation_for_image_classification/#knowledge-distillation-for-computer-vision
.md
training_args = TrainingArguments( output_dir="my-awesome-model", num_train_epochs=30, fp16=True, logging_dir=f"{repo_name}/logs", logging_strategy="epoch", eval_strategy="epoch", save_strategy="epoch", load_best_model_at_end=True, metric_for_best_model="accuracy", report_to="tensorboard", push_to_hub=True, hub_strategy="every_save", hub_model_id=repo_name, ) num_labels = len(processed_datasets["train"].features["labels"].names)
84_1_16
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/knowledge_distillation_for_image_classification.md
https://huggingface.co/docs/transformers/en/tasks/knowledge_distillation_for_image_classification/#knowledge-distillation-for-computer-vision
.md
num_labels = len(processed_datasets["train"].features["labels"].names) # initialize models teacher_model = AutoModelForImageClassification.from_pretrained( "merve/beans-vit-224", num_labels=num_labels, ignore_mismatched_sizes=True )
84_1_17
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/knowledge_distillation_for_image_classification.md
https://huggingface.co/docs/transformers/en/tasks/knowledge_distillation_for_image_classification/#knowledge-distillation-for-computer-vision
.md
# training MobileNetV2 from scratch student_config = MobileNetV2Config() student_config.num_labels = num_labels student_model = MobileNetV2ForImageClassification(student_config) ``` We can use `compute_metrics` function to evaluate our model on the test set. This function will be used during the training process to compute the `accuracy` & `f1` of our model. ```python import evaluate import numpy as np accuracy = evaluate.load("accuracy")
84_1_18
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/knowledge_distillation_for_image_classification.md
https://huggingface.co/docs/transformers/en/tasks/knowledge_distillation_for_image_classification/#knowledge-distillation-for-computer-vision
.md
accuracy = evaluate.load("accuracy") def compute_metrics(eval_pred): predictions, labels = eval_pred acc = accuracy.compute(references=labels, predictions=np.argmax(predictions, axis=1)) return {"accuracy": acc["accuracy"]} ``` Let's initialize the `Trainer` with the training arguments we defined. We will also initialize our data collator. ```python from transformers import DefaultDataCollator
84_1_19
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/knowledge_distillation_for_image_classification.md
https://huggingface.co/docs/transformers/en/tasks/knowledge_distillation_for_image_classification/#knowledge-distillation-for-computer-vision
.md
data_collator = DefaultDataCollator() trainer = ImageDistilTrainer( student_model=student_model, teacher_model=teacher_model, training_args=training_args, train_dataset=processed_datasets["train"], eval_dataset=processed_datasets["validation"], data_collator=data_collator, processing_class=teacher_processor, compute_metrics=compute_metrics, temperature=5, lambda_param=0.5 ) ``` We can now train our model. ```python trainer.train() ``` We can evaluate the model on the test set. ```python
84_1_20
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/knowledge_distillation_for_image_classification.md
https://huggingface.co/docs/transformers/en/tasks/knowledge_distillation_for_image_classification/#knowledge-distillation-for-computer-vision
.md
) ``` We can now train our model. ```python trainer.train() ``` We can evaluate the model on the test set. ```python trainer.evaluate(processed_datasets["test"]) ```
84_1_21
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/knowledge_distillation_for_image_classification.md
https://huggingface.co/docs/transformers/en/tasks/knowledge_distillation_for_image_classification/#knowledge-distillation-for-computer-vision
.md
On test set, our model reaches 72 percent accuracy. To have a sanity check over efficiency of distillation, we also trained MobileNet on the beans dataset from scratch with the same hyperparameters and observed 63 percent accuracy on the test set. We invite the readers to try different pre-trained teacher models, student architectures, distillation parameters and report their findings. The training logs and checkpoints for distilled model can be found in [this
84_1_22