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/examples/semantic_segmentation.ipynb
Views: 2535
Fine-tuning for Semantic Segmentation with 🤗 Transformers
In this notebook, you'll learn how to fine-tune a pretrained vision model for Semantic Segmentation on a custom dataset in PyTorch. The idea is to add a randomly initialized segmentation head on top of a pre-trained encoder, and fine-tune the model altogether on a labeled dataset. You can find an accompanying blog post here.
Model
This notebook is built for the SegFormer model and is supposed to run on any semantic segmentation dataset. You can adapt this notebook to other supported semantic segmentation models such as MobileViT.
Data augmentation
This notebook leverages torchvision
's transforms
module for applying data augmentation. Using other augmentation libraries like albumentations
is also supported.
Depending on the model and the GPU you are using, you might need to adjust the batch size to avoid out-of-memory errors. Set those two parameters, then the rest of the notebook should run smoothly.
In this notebook, we'll fine-tune from the https://huggingface.co/nvidia/mit-b0 checkpoint, but note that there are others available on the hub.
Before we start, let's install the datasets
, transformers
, and evaluate
libraries. We also install Git-LFS to upload the model checkpoints to Hub.
If you're opening this notebook locally, make sure your environment has an install from the last version of those libraries or run the pip install
command above with the --upgrade
flag.
You can share the resulting model with the community. By pushing the model to the Hub, others can discover your model and build on top of it. You also get an automatically generated model card that documents how the model works and a widget that will allow anyone to try out the model directly in the browser. To enable this, you'll need to login to your account.
We also quickly upload some telemetry - this tells us which examples and software versions are getting used so we know where to prioritize our maintenance efforts. We don't collect (or care about) any personally identifiable information, but if you'd prefer not to be counted, feel free to skip this step or delete this cell entirely.
Fine-tuning a model on a semantic segmentation task
Given an image, the goal is to associate each and every pixel to a particular category (such as table). The screenshot below is taken from a SegFormer fine-tuned on ADE20k - try out the inference widget!
Loading the dataset
We will use the 🤗 Datasets library to download our custom dataset into a DatasetDict
.
We're using the Sidewalk dataset which is dataset of sidewalk images gathered in Belgium in the summer of 2021. You can learn more about the dataset here.
Let us also load the Mean IoU metric, which we'll use to evaluate our model both during and after training.
IoU (short for Intersection over Union) tells us the amount of overlap between two sets. In our case, these sets will be the ground-truth segmentation map and the predicted segmentation map. To learn more, you can check out this article.
The ds
object itself is a DatasetDict
, which contains one key per split (in this case, only "train" for a training split).
Here, the features
tell us what each example is consisted of:
pixel_values
: the actual imagelabel
: segmentation mask
To access an actual element, you need to select a split first, then give an index:
Each of the pixels above can be associated to a particular category. Let's load all the categories that are associated with the dataset. Let's also create an id2label
dictionary to decode them back to strings and see what they are. The inverse label2id
will be useful too, when we load the model later.
Note: This dataset specificaly sets the 0th index as being unlabeled
. We want to take this information into consideration while computing the loss. Specifically, we'll want to mask the pixels where the network predicted unlabeled
and avoid computing the loss for it since it doesn't contribute to to training that much.
Let's shuffle the dataset and split the dataset in a train and test set. We'll explicitly define a random seed to use when calling ds.shuffle()
to ensure our results are the same each time we run this cell.
Preprocessing the data
Before we can feed these images to our model, we need to preprocess them.
Preprocessing images typically comes down to (1) resizing them to a particular size (2) normalizing the color channels (R,G,B) using a mean and standard deviation. These are referred to as image transformations.
To make sure we (1) resize to the appropriate size (2) use the appropriate image mean and standard deviation for the model architecture we are going to use, we instantiate what is called a feature extractor with the AutoFeatureExtractor.from_pretrained
method.
This feature extractor is a minimal preprocessor that can be used to prepare images for model training and inference.
We also defined some data augmentations to make our model more resilient to different lighting conditions. We used the ColorJitter
function from torchvision
to randomly change the brightness, contrast, saturation, and hue of the images in the batch.
Also, notice the differences in between transformations applied to the train and test splits. We're only applying jittering to the training split and not to the test split. Data augmentation is usually a training-only step and isn't applied during evaluation.
Training the model
Now that our data is ready, we can download the pretrained model and fine-tune it. We will use the SegformerForSemanticSegmentation
class. Calling the from_pretrained
method on it will download and cache the weights for us. As the label ids and the number of labels are dataset dependent, we pass label2id
, and id2label
alongside the model_checkpoint
here. This will make sure a custom segmentation head is created (with a custom number of output neurons).
The warning is telling us we are throwing away some weights (the weights and bias of the decode_head
layer) and randomly initializing some other (the weights and bias of a new decode_head
layer). This is expected in this case, because we are adding a new head for which we don't have pretrained weights, so the library warns us we should fine-tune this model before using it for inference, which is exactly what we are going to do.
To fine-tune the model, we'll use Hugging Face's Trainer API. To use the Trainer
, we'll need to define the training configuration and any evaluation metrics we might want to use.
First, we'll set up the TrainingArguments
. This defines all training hyperparameters, such as learning rate and the number of epochs, frequency to save the model and so on. We also specify to push the model to the hub after training (push_to_hub=True
) and specify a model name (hub_model_id
).
Next, we'll define a function that computes the evaluation metric we want to work with. Because we're doing semantic segmentation, we'll use the mean Intersection over Union (mIoU), which is directly accessible in the evaluate
library. IoU represents the overlap of segmentation masks. Mean IoU is the average of the IoU of all semantic classes. Take a look at this blogpost for an overview of evaluation metrics for image segmentation.
Because our model outputs logits with dimensions height/4 and width/4, we have to upscale them before we can compute the mIoU.
Finally, we can instantiate a Trainer
object.
Notice that we're passing feature_extractor
to the Trainer
. This will ensure the feature extractor is also uploaded to the Hub along with the model checkpoints.
Now that our trainer is set up, training is as simple as calling the train function. We don't need to worry about managing our GPU(s), the trainer will take care of that.
When we're done with training, we can push our fine-tuned model to the Hub.
This will also automatically create a model card with our results. We'll supply some extra information in kwargs to make the model card more complete.
Inference
Now comes the exciting part -- using our fine-tuned model! In this section, we'll show how you can load your model from the hub and use it for inference.
However, you can also try out your model directly on the Hugging Face Hub, thanks to the cool widgets powered by the hosted inference API. If you pushed your model to the Hub in the previous step, you should see an inference widget on your model page. You can add default examples to the widget by defining example image URLs in your model card. See this model card as an example.
Use the model from the Hub
We'll first load the model from the Hub using SegformerForSemanticSegmentation.from_pretrained()
.
Next, we'll load an image from our test dataset and its associated ground truth segmentation label.
To segment this test image, we first need to prepare the image using the feature extractor. Then we'll forward it through the model.
We also need to remember to upscale the output logits to the original image size. In order to get the actual category predictions, we just have to apply an argmax
on the logits.
Now it's time to display the result. The next cell defines the colors for each category, so that they match the "category coloring" on Segments.ai.
The next function overlays the output segmentation map on the original image.
We'll display the result next to the ground-truth mask.
What do you think? Would you send our pizza delivery robot on the road with this segmentation information?
The result might not be perfect yet, but we can always expand our dataset to make the model more robust. We can now also go train a larger SegFormer model, and see how it stacks up. If you want to explore further beyond this notebook, here are some things you can try next:
Train the model for longer.
Try out the different segmentation-specific training augmentations from libraries like
albumentations
.Try out a larger variant of the SegFormer model family or try an entirely new model family like MobileViT.