Image classification
Last updated
Last updated
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 on the 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
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
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
Copied
Then take a look at an example:
Copied
Each example in the dataset has two fields:
image
: a PIL image of the food item
label
: 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:
Copied
Now you can convert the label id to a label name:
Copied
The next step is to load a ViT image processor to process the image into a tensor:
Copied
PytorchHide Pytorch content
Crop a random part of the image, resize it, and normalize it with the image mean and standard deviation:
Copied
Then create a preprocessing function to apply the transforms and return the pixel_values
- the inputs to the model - of the image:
Copied
Copied
Copied
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.image
or any other library you prefer.
Copied
Next, create functions to apply appropriate transformations to a batch of images, instead of one image at a time.
Copied
Copied
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
Copied
Then create a function that passes your predictions and labels to compute
to calculate the accuracy:
Copied
Your compute_metrics
function is ready to go now, and youโll return to it when you set up your training.
PytorchHide Pytorch content
Copied
At this point, only three steps remain:
Copied
Copied
TensorFlowHide TensorFlow content
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:
Copied
Copied
Copied
Configure the model for training with compile()
:
Copied
Copied
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:
Copied
Congratulations! You have fine-tuned your model and shared it on the ๐ Hub. You can now use it for 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:
Copied
Copied
You can also manually replicate the results of the pipeline
if youโd like:
PytorchHide Pytorch content
Load an image processor to preprocess the image and return the input
as PyTorch tensors:
Copied
Pass your inputs to the model and return the logits:
Copied
Get the predicted label with the highest probability, and use the modelโs id2label
mapping to convert it to a label:
Copied
TensorFlowHide TensorFlow content
Load an image processor to preprocess the image and return the input
as TensorFlow tensors:
Copied
Pass your inputs to the model and return the logits:
Copied
Get the predicted label with the highest probability, and use the modelโs id2label
mapping to convert it to a label:
Copied
Split the datasetโs train
split into a train and test set with the method:
Apply some image transformations to the images to make the model more robust against overfitting. Here youโll use torchvisionโs module, but you can also use any image library you like.
To apply the preprocessing function over the entire dataset, use ๐ Datasets method. The transforms are applied on the fly when you load an element of the dataset:
Now create a batch of examples using . Unlike other data collators in ๐Transformers, the DefaultDataCollator
does not apply additional preprocessing such as padding.
Use ๐ Datasets to apply the transformations on the fly:
Including a metric during training is often helpful for evaluating your modelโs performance. You can quickly load an evaluation method with the ๐ library. For this task, load the metric (see the ๐ Evaluate to learn more about how to load and compute a metric):
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 ViT with . Specify the number of labels along with the number of expected labels, and the label mappings:
Define your training hyperparameters in . 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 will evaluate the accuracy 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 are unfamiliar with fine-tuning a model with Keras, check out the first!
Then, load ViT with along with the label mappings:
Convert your datasets to the tf.data.Dataset
format using the and your data_collator
:
To compute the accuracy from the predictions and push your model to the ๐ Hub, use . Pass your compute_metrics
function to , and use the to upload the model:
For a more in-depth example of how to finetune a model for image classification, take a look at the corresponding .
The simplest way to try out your finetuned model for inference is to use it in a . Instantiate a pipeline
for image classification with your model, and pass your image to it: