Hugging Face 教程:微调 SegFormer 实现语义分割
Hugging Face 发布教程,指导用户利用 Transformers 库微调 SegFormer 模型以执行自定义数据集的语义分割任务。该案例以披萨配送机器人为背景,演示了从数据加载、模型训练到部署推理组件的全流程。
关联知识实体
报道正文
本文目录11 个章节
使用自定义数据集微调语义分割模型
发布于 2022 年 3 月 17 日 在 GitHub 上更新 点赞 37
Tobias Cornille tobiasc 客座作者 Niels Rogge nielsr
本指南将展示如何微调 SegFormer,这是一种最先进的语义分割模型。我们的目标是构建一个用于披萨配送机器人的模型,使其能够识别行驶路径并检测障碍物 🍕🤖。首先,我们将使用来自 🤗 hub 的可用分割数据集。然后,我们将利用 🤗 transformers(一个提供易于使用的最先进模型实现的开源库)来微调预训练的 SegFormer 模型。在此过程中,你将学习如何使用 Hugging Face Hub——这是最大的开源模型和数据集目录。
语义分割的任务是对图像中的每个像素进行分类。你可以将其视为一种更精确的图像分类方式。它在医学影像和自动驾驶等领域有着广泛的应用。例如,对于我们的披萨配送机器人来说,准确知道人行道在图像中的具体位置至关重要,而不仅仅是判断是否存在人行道。
由于语义分割本质上是一种分类任务,因此用于图像分类和语义分割的网络架构非常相似。2014 年,Long 等人发表了一篇开创性论文,使用卷积神经网络进行语义分割。最近,Transformer 已被用于图像分类(例如 ViT),现在它们也被应用于语义分割,进一步推动了技术前沿的发展。
SegFormer 是由 Xie 等人在 2021 年提出的一种语义分割模型。它采用了一种不使用位置编码的分层 Transformer 编码器(与 ViT 不同),以及一个简单的多层感知机解码器。SegFormer 在多个常见数据集上均实现了最先进的性能。让我们看看我们的披萨配送机器人在处理人行道图像时的表现如何。
让我们从安装必要的依赖项开始。由于我们需要将数据集和模型推送到 Hugging Face Hub,因此需要安装 Git LFS 并登录 Hugging Face。
git-lfs 的安装方式可能因系统而异。请注意,Google Colab 已预装 Git LFS。
pip install -q transformers datasets evaluate segments-ai
apt-get install git-lfs
git lfs install
huggingface-cli login1. 创建/选择数据集
任何机器学习项目的第一步都是构建一个高质量的数据集。为了训练语义分割模型,我们需要一个带有语义分割标签的数据集。我们可以使用 Hugging Face Hub 上现有的数据集,例如 ADE20k,或者通过为图像标注相应的分割图来创建我们自己的数据集。
对于我们的披萨配送机器人,我们可以使用现有的自动驾驶数据集,如 CityScapes 或 BDD100K。然而,这些数据集是由在道路上行驶的汽车采集的。由于我们的配送机器人将在人行道上行驶,这些数据集中的图像与机器人在现实世界中看到的数据之间存在不匹配。
为了避免让配送机器人感到困惑,我们使用在人行道上拍摄的图像创建了自定义的语义分割数据集。该数据集可在 segments/sidewalk-semantic 获取。这可以使用像 CVAT 或 Segments.ai 这样的标注平台来完成。
使用 Hub 上的数据集
我们将在此处加载完整的带有人行道标注的数据集。请注意,你可以直接在浏览器中查看示例。
hf_dataset_identifier = "segments/sidewalk-semantic"2. 加载并准备用于训练的 Hugging Face 数据集
现在我们已经创建了一个新数据集并将其推送到 Hugging Face Hub,我们可以通过一行代码加载该数据集。
from datasets import load_dataset
ds = load_dataset(hf_dataset_identifier)让我们对数据集进行洗牌(shuffle),并将其划分为训练集和测试集。
ds = ds.shuffle(seed=1)
ds = ds["train"].train_test_split(test_size=0.2)
train_ds = ds["train"]
test_ds = ds["test"]我们将提取标签数量及人类可读的 ID,以便后续正确配置分割模型。
import json
from huggingface_hub import hf_hub_download
repo_id = f"datasets/{hf_dataset_identifier}"
filename = "id2label.json"
id2label = json.load(open(hf_hub_download(repo_id=hf_dataset_identifier, filename=filename, repo_type="dataset"), "r"))
id2label = {int(k): v for k, v in id2label.items()}
label2id = {v: k for k, v in id2label.items()}
num_labels = len(id2label)图像处理器与数据增强
SegFormer 模型期望输入具有特定的形状。为了将训练数据转换为符合预期形状的格式,我们可以使用 SegFormerImageProcessor。虽然可以使用 ds.map 函数预先对整个训练数据集应用图像处理器,但这可能会占用大量磁盘空间。因此,我们将采用一种*转换(transform)*方法,仅在实际使用数据时动态准备批次数据(即即时处理)。这样,我们无需等待进一步的数据预处理即可开始训练。
在我们的转换过程中,还将定义一些数据增强操作,以增强模型对不同光照条件的鲁棒性。我们将使用 torchvision 中的 ColorJitter 函数,随机改变批次中图像的亮度、对比度、饱和度和色调。
from torchvision.transforms import ColorJitter
from transformers import SegformerImageProcessor
processor = SegformerImageProcessor()
jitter = ColorJitter(brightness=0.25, contrast=0.25, saturation=0.25, hue=0.1)
def train_transforms(example_batch):
images = [jitter(x) for x in example_batch['pixel_values']]
labels = [x for x in example_batch['label']]
inputs = processor(images, labels)
return inputs
def val_transforms(example_batch):
images = [x for x in example_batch['pixel_values']]
labels = [x for x in example_batch['label']]
inputs = processor(images, labels)
return inputs
train_ds.set_transform(train_transforms)
test_ds.set_transform(val_transforms)3. 微调 SegFormer 模型
加载待微调的模型
SegFormer 的作者定义了 5 种尺寸递增的模型:从 B0 到 B5。下图(取自原始论文)展示了这些不同模型在 ADE20K 数据集上与其他模型相比的性能表现。
Here, we'll load the smallest SegFormer model (B0), pre-trained on ImageNet-1k. It's only about 14MB in size! Using a small model will make sure that our model can run smoothly on our pizza delivery robot.
from transformers import SegformerForSemanticSegmentation
pretrained_model_name = "nvidia/mit-b0"
model = SegformerForSemanticSegmentation.from_pretrained(
pretrained_model_name,
id2label=id2label,
label2id=label2id
)Set up the Trainer
To fine-tune the model on our data, we'll use Hugging Face's Trainer API. We need to set up the training configuration and an evalutation metric to use a Trainer.
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).
from transformers import TrainingArguments
epochs = 50
lr = 0.00006
batch_size = 2
hub_model_id = "segformer-b0-finetuned-segments-sidewalk-2"
training_args = TrainingArguments(
"segformer-b0-finetuned-segments-sidewalk-outputs",
learning_rate=lr,
num_train_epochs=epochs,
per_device_train_batch_size=batch_size,
per_device_eval_batch_size=batch_size,
save_total_limit=3,
evaluation_strategy="steps",
save_strategy="steps",
save_steps=20,
eval_steps=20,
logging_steps=1,
eval_accumulation_steps=5,
load_best_model_at_end=True,
push_to_hub=True,
hub_model_id=hub_model_id,
hub_strategy="end",
)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), 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.
import torch
from torch import nn
import evaluate
metric = evaluate.load("mean_iou")
def compute_metrics(eval_pred):
with torch.no_grad():
logits, labels = eval_pred
logits_tensor = torch.from_numpy(logits)
logits_tensor = nn.functional.interpolate(
logits_tensor,
size=labels.shape[-2:],
mode="bilinear",
align_corners=False,
).argmax(dim=1)
pred_labels = logits_tensor.detach().cpu().numpy()
metrics = metric.compute(
predictions=pred_labels,
references=labels,
num_labels=len(id2label),
ignore_index=0,
reduce_labels=processor.do_reduce_labels,
)
per_category_accuracy = metrics.pop("per_category_accuracy").tolist()
per_category_iou = metrics.pop("per_category_iou").tolist()
metrics.update({f"accuracy_{id2label[i]}": v for i, v in enumerate(per_category_accuracy)})
metrics.update({f"iou_{id2label[i]}": v for i, v in enumerate(per_category_iou)})
return metricsFinally, we can instantiate a Trainer object.
from transformers import Trainer
trainer = Trainer(
model=model,
args=training_args,
train_dataset=train_ds,
eval_dataset=test_ds,
compute_metrics=compute_metrics,
)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.
trainer.train()When we're done with training, we can push our fine-tuned model and the image processor 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.
kwargs = {
"tags": ["vision", "image-segmentation"],
"finetuned_from": pretrained_model_name,
"dataset": hf_dataset_identifier,
}
processor.push_to_hub(hub_model_id)
trainer.push_to_hub(**kwargs)4. 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().
from transformers import SegformerImageProcessor, SegformerForSemanticSegmentation
processor = SegformerImageProcessor.from_pretrained("nvidia/segformer-b0-finetuned-ade-512-512")
model = SegformerForSemanticSegmentation.from_pretrained(f"{hf_username}/{hub_model_id}")Next, we'll load an image from our test dataset.
image = test_ds[0]['pixel_values']
gt_seg = test_ds[0]['label']
imageTo segment this test image, we first need to prepare the image using the image processor. Then we 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.
from torch import nn
inputs = processor(images=image, return_tensors="pt")
outputs = model(**inputs)
logits = outputs.logits
upsampled_logits = nn.functional.interpolate(
logits,
size=image.size[::-1],
mode='bilinear',
align_corners=False
)
pred_seg = upsampled_logits.argmax(dim=1)[0]Now it's time to display the result. 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.
5. Conclusion
That's it! You now know how to create your own image segmentation dataset and how to use it to fine-tune a semantic segmentation model.
We introduced you to some useful tools along the way, such as:
- Segments.ai for labeling your data
- 🤗 datasets for loading and sharing a dataset
- 🤗 transformers for easily fine-tuning a state-of-the-art segmentation model
- Hugging Face Hub for sharing our dataset and model, and for creating an inference widget for our model
We hope you enjoyed this post and learned something. Feel free to share your own model with us on Twitter (@TobiasCornille, @NielsRogge, and @huggingface).