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.
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
pip install transformers datasets evaluate
We encourage you to log in to your BOINC AI account to upload and share your model with the community. When prompted, enter your token to log in:
Copied
>>> from boincai_hub import notebook_login
>>> notebook_login()
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.
Copied
>>> from datasets import load_dataset
>>> food = load_dataset("food101", split="train[:5000]")
Split the dataset’s train split into a train and test set with the train_test_split method:
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:
Copied
>>> def transforms(examples):
... examples["pixel_values"] = [_transforms(img.convert("RGB")) for img in examples["image"]]
... del examples["image"]
... return examples
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:
Copied
>>> food = food.with_transform(transforms)
Now create a batch of examples using DefaultDataCollator. Unlike other data collators in 🌍Transformers, the DefaultDataCollator does not apply additional preprocessing such as padding.
Copied
>>> from transformers import DefaultDataCollator
>>> data_collator = DefaultDataCollator()
TensorFlowHide TensorFlow content
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.imageor any other library you prefer.
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.
Copied
>>> from transformers import DefaultDataCollator
>>> data_collator = DefaultDataCollator(return_tensors="tf")
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):
Your compute_metrics function is ready to go now, and you’ll return to it when you set up your training.
Train
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 ViT with AutoModelForImageClassification. Specify the number of labels along with the number of expected labels, and the label mappings:
Define your training hyperparameters in TrainingArguments. It is important you don’t remove unused columns because that’ll drop the image column. Without the image column, you can’t create pixel_values. Set remove_unused_columns=False to prevent this behavior! The only other 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 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.
>>> from tensorflow.keras.losses import SparseCategoricalCrossentropy
>>> loss = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True)
>>> model.compile(optimizer=optimizer, loss=loss)
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:
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: