Semantic segmentation
Last updated
Last updated
Semantic segmentation assigns a label or class to each individual pixel of an image. There are several types of segmentation, and in the case of semantic segmentation, no distinction is made between unique instances of the same object. Both objects are given the same label (for example, “car” instead of “car-1” and “car-2”). Common real-world applications of semantic segmentation include training self-driving cars to identify pedestrians and important traffic information, identifying cells and abnormalities in medical imagery, and monitoring environmental changes from satellite imagery.
This guide will show you how to:
Finetune on the dataset.
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 log in to your BOINC AI account so you can 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 SceneParse150 dataset from the 🌍 Datasets library. This’ll 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
image
: a PIL image of the scene.
annotation
: a PIL image of the segmentation map, which is also the model’s target.
scene_category
: a category id that describes the image scene like “kitchen” or “office”. In this guide, you’ll only need image
and annotation
, both of which are PIL images.
You’ll also want to create a dictionary that maps a label id to a label class which will be useful when you set up the model later. Download the mappings from the Hub and create the id2label
and label2id
dictionaries:
Copied
The next step is to load a SegFormer image processor to prepare the images and annotations for the model. Some datasets, like this one, use the zero-index as the background class. However, the background class isn’t actually included in the 150 classes, so you’ll need to set reduce_labels=True
to subtract one from all the labels. The zero-index is replaced by 255
so it’s ignored by SegFormer’s loss function:
Copied
PytorchHide Pytorch content
Copied
Now create two preprocessing functions to prepare the images and annotations for the model. These functions convert the images into pixel_values
and annotations to labels
. For the training set, jitter
is applied before providing the images to the image processor. For the test set, the image processor crops and normalizes the images
, and only crops the labels
because no data augmentation is applied during testing.
Copied
Copied
TensorFlowHide TensorFlow content
training data transformations that include image augmentation
validation data transformations that only transpose the images, since computer vision models in 🌍 Transformers expect channels-first layout
Copied
Next, create two preprocessing functions to prepare batches of images and annotations for the model. These functions apply the image transformations and use the earlier loaded image_processor
to convert the images into pixel_values
and annotations to labels
. ImageProcessor
also takes care of resizing and normalizing the images.
Copied
Copied
Copied
Then create a function to compute
the metrics. Your predictions need to be converted to logits first, and then reshaped to match the size of the labels before you can call compute
:
PytorchHide Pytorch contentCopied
TensorFlowHide TensorFlow contentCopied
Your compute_metrics
function is ready to go now, and you’ll return to it when you setup 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 pretrained model.
Convert a 🌍 Dataset to a tf.data.Dataset
.
Compile your model.
Add callbacks to calculate metrics and upload your model to 🌍 Hub
Use the fit()
method to run the training.
Start by defining the hyperparameters, optimizer and learning rate schedule:
Copied
Copied
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 finetuned a model, you can use it for inference!
Load an image for inference:
Copied
PytorchHide Pytorch content
Copied
You can also manually replicate the results of the pipeline
if you’d like. Process the image with an image processor and place the pixel_values
on a GPU:
Copied
Pass your input to the model and return the logits
:
Copied
Next, rescale the logits to the original image size:
Copied
TensorFlowHide TensorFlow content
Load an image processor to preprocess the image and return the input as TensorFlow tensors:
Copied
Pass your input to the model and return the logits
:
Copied
Next, rescale the logits to the original image size and apply argmax on the class dimension:
Copied
Copied
Split the dataset’s train
split into a train and test set with the method:
It is common to apply some data augmentations to an image dataset to make a model more robust against overfitting. In this guide, you’ll use the function from to randomly change the color properties of an image, but you can also use any image library you like.
To apply the jitter
over the entire dataset, use the 🌍 Datasets function. The transform is applied on the fly which is faster and consumes less disk space:
It is common to apply some data augmentations to an image dataset to make a model more robust against overfitting. In this guide, you’ll use to randomly change the color properties of an image, but you can also use any image library you like. Define two separate transformation functions:
To apply the preprocessing transformations over the entire dataset, use the 🌍 Datasets function. The transform is applied on the fly which is faster and consumes less disk space:
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 (IoU) 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 SegFormer with , and pass the model the mapping between label ids and label classes:
Define your training hyperparameters in . It is important you don’t remove unused columns because this’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 IoU metric 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 SegFormer with along with the label mappings, and compile it with the optimizer. Note that Transformers models all have a default task-relevant loss function, so you don’t need to specify one unless you want to:
Convert your datasets to the tf.data.Dataset
format using the and the :
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:
The simplest way to try out your finetuned model for inference is to use it in a . Instantiate a pipeline
for image segmentation with your model, and pass your image to it:
To visualize the results, load the as ade_palette()
that maps each class to their RGB values. Then you can combine and plot your image and the predicted segmentation map: