Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place. Commercial Alternative to JupyterHub.
Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place. Commercial Alternative to JupyterHub.
Path: blob/main/transformers_doc/en/image_classification.ipynb
Views: 2542
Image classification
Image classification assigns a label or class to an image. Unlike text or audio classification, the inputs are the pixel values that comprise an image. There are many applications for image classification, such as detecting damage after a natural disaster, monitoring crop health, or helping screen medical images for signs of disease.
This guide illustrates how to:
Fine-tune ViT on the Food-101 dataset to classify a food item in an image.
Use your fine-tuned model for inference.
BEiT, BiT, ConvNeXT, ConvNeXTV2, CvT, Data2VecVision, DeiT, DiNAT, EfficientFormer, EfficientNet, FocalNet, ImageGPT, LeViT, MobileNetV1, MobileNetV2, MobileViT, MobileViTV2, NAT, Perceiver, PoolFormer, RegNet, ResNet, SegFormer, SwiftFormer, Swin Transformer, Swin Transformer V2, VAN, ViT, ViT Hybrid, ViTMSN
Before you begin, make sure you have all the necessary libraries installed:
We encourage you to log in to your Hugging Face account to upload and share your model with the community. When prompted, enter your token to log in:
Load Food-101 dataset
Start by loading a smaller subset of the Food-101 dataset from the 🤗 Datasets library. This will give you a chance to experiment and make sure everything works before spending more time training on the full dataset.
Split the dataset's train
split into a train and test set with the train_test_split method:
Then take a look at an example:
Each example in the dataset has two fields:
image
: a PIL image of the food itemlabel
: the label class of the food item
To make it easier for the model to get the label name from the label id, create a dictionary that maps the label name to an integer and vice versa:
Now you can convert the label id to a label name:
Preprocess
The next step is to load a ViT image processor to process the image into a tensor:
Apply some image transformations to the images to make the model more robust against overfitting. Here you'll use torchvision's transforms
module, but you can also use any image library you like.
Crop a random part of the image, resize it, and normalize it with the image mean and standard deviation:
Then create a preprocessing function to apply the transforms and return the pixel_values
- the inputs to the model - of the image:
To apply the preprocessing function over the entire dataset, use 🤗 Datasets with_transform method. The transforms are applied on the fly when you load an element of the dataset:
Now create a batch of examples using DefaultDataCollator. Unlike other data collators in 🤗 Transformers, the DefaultDataCollator
does not apply additional preprocessing such as padding.
To avoid overfitting and to make the model more robust, add some data augmentation to the training part of the dataset. Here we use Keras preprocessing layers to define the transformations for the training data (includes data augmentation), and transformations for the validation data (only center cropping, resizing and normalizing). You can use tf.image
or any other library you prefer.
Next, create functions to apply appropriate transformations to a batch of images, instead of one image at a time.
Use 🤗 Datasets set_transform to apply the transformations on the fly:
As a final preprocessing step, create a batch of examples using DefaultDataCollator
. Unlike other data collators in 🤗 Transformers, the DefaultDataCollator
does not apply additional preprocessing, such as padding.
Evaluate
Including a metric during training is often helpful for evaluating your model's performance. You can quickly load an evaluation method with the 🤗 Evaluate library. For this task, load the accuracy metric (see the 🤗 Evaluate quick tour to learn more about how to load and compute a metric):
Then create a function that passes your predictions and labels to compute to calculate the accuracy:
Your compute_metrics
function is ready to go now, and you'll return to it when you set up your training.
Train
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 ViT with AutoModelForImageClassification. Specify the number of labels along with the number of expected labels, and the label mappings:
At this point, only three steps remain:
Define your training hyperparameters in TrainingArguments. It is important you don't remove unused columns because that'll drop the
image
column. Without theimage
column, you can't createpixel_values
. Setremove_unused_columns=False
to prevent this behavior! The only other required parameter isoutput_dir
which 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 Hugging Face to upload your model). At the end of each epoch, the Trainer will evaluate the accuracy and save the training checkpoint.Pass the training arguments to Trainer along with the model, dataset, tokenizer, data collator, and
compute_metrics
function.Call train() to finetune your model.
Once training is completed, share your model to the Hub with the push_to_hub() method so everyone can use your model:
If you are unfamiliar with fine-tuning a model with Keras, check out the basic tutorial first!
To fine-tune a model in TensorFlow, follow these steps:
Define the training hyperparameters, and set up an optimizer and a learning rate schedule.
Instantiate a pre-trained model.
Convert a 🤗 Dataset to a
tf.data.Dataset
.Compile your model.
Add callbacks and use the
fit()
method to run the training.Upload your model to 🤗 Hub to share with the community.
Start by defining the hyperparameters, optimizer and learning rate schedule:
Then, load ViT with TFAutoModelForImageClassification along with the label mappings:
Convert your datasets to the tf.data.Dataset
format using the to_tf_dataset and your data_collator
:
Configure the model for training with compile()
:
To compute the accuracy from the predictions and push your model to the 🤗 Hub, use Keras callbacks. Pass your compute_metrics
function to KerasMetricCallback, and use the PushToHubCallback to upload the model:
Finally, you are ready to train your model! Call fit()
with your training and validation datasets, the number of epochs, and your callbacks to fine-tune the model:
Congratulations! You have fine-tuned your model and shared it on the 🤗 Hub. You can now use it for inference!
For a more in-depth example of how to finetune a model for image classification, take a look at the corresponding PyTorch notebook.
Inference
Great, now that you've fine-tuned a model, you can use it for inference!
Load an image you'd like to run inference on:
The simplest way to try out your finetuned model for inference is to use it in a pipeline(). Instantiate a pipeline
for image classification with your model, and pass your image to it:
You can also manually replicate the results of the pipeline
if you'd like:
Load an image processor to preprocess the image and return the input
as PyTorch tensors:
Pass your inputs to the model and return the logits:
Get the predicted label with the highest probability, and use the model's id2label
mapping to convert it to a label:
Load an image processor to preprocess the image and return the input
as TensorFlow tensors:
Pass your inputs to the model and return the logits:
Get the predicted label with the highest probability, and use the model's id2label
mapping to convert it to a label: