From b7fd1bc2dc4356d5197987be71bfa27575559d39 Mon Sep 17 00:00:00 2001 From: sergiopaniego Date: Sat, 7 Sep 2024 11:04:10 +0200 Subject: [PATCH] Updated Object detection task notebooks --- transformers_doc/en/object_detection.ipynb | 1873 +++++++++-------- .../en/pytorch/object_detection.ipynb | 1873 +++++++++-------- .../en/tensorflow/object_detection.ipynb | 1873 +++++++++-------- 3 files changed, 2925 insertions(+), 2694 deletions(-) diff --git a/transformers_doc/en/object_detection.ipynb b/transformers_doc/en/object_detection.ipynb index 934b1a96..ad3ba3cd 100644 --- a/transformers_doc/en/object_detection.ipynb +++ b/transformers_doc/en/object_detection.ipynb @@ -1,900 +1,977 @@ { - "cells": [ - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "# Transformers installation\n", - "! pip install transformers datasets\n", - "# To install from source instead of the last release, comment the command above and uncomment the following one.\n", - "# ! pip install git+https://github.com/huggingface/transformers.git" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "# Object detection" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Object detection is the computer vision task of detecting instances (such as humans, buildings, or cars) in an image. Object detection models receive an image as input and output\n", - "coordinates of the bounding boxes and associated labels of the detected objects. An image can contain multiple objects,\n", - "each with its own bounding box and a label (e.g. it can have a car and a building), and each object can\n", - "be present in different parts of an image (e.g. the image can have several cars).\n", - "This task is commonly used in autonomous driving for detecting things like pedestrians, road signs, and traffic lights.\n", - "Other applications include counting objects in images, image search, and more.\n", - "\n", - "In this guide, you will learn how to:\n", - "\n", - " 1. Finetune [DETR](https://huggingface.co/docs/transformers/model_doc/detr), a model that combines a convolutional\n", - " backbone with an encoder-decoder Transformer, on the [CPPE-5](https://huggingface.co/datasets/cppe-5)\n", - " dataset.\n", - " 2. Use your finetuned model for inference.\n", - "\n", - "\n", - "The task illustrated in this tutorial is supported by the following model architectures:\n", - "\n", - "\n", - "\n", - "[Conditional DETR](https://huggingface.co/docs/transformers/main/en/tasks/../model_doc/conditional_detr), [Deformable DETR](https://huggingface.co/docs/transformers/main/en/tasks/../model_doc/deformable_detr), [DETA](https://huggingface.co/docs/transformers/main/en/tasks/../model_doc/deta), [DETR](https://huggingface.co/docs/transformers/main/en/tasks/../model_doc/detr), [Table Transformer](https://huggingface.co/docs/transformers/main/en/tasks/../model_doc/table-transformer), [YOLOS](https://huggingface.co/docs/transformers/main/en/tasks/../model_doc/yolos)\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "Before you begin, make sure you have all the necessary libraries installed:\n", - "\n", - "```bash\n", - "pip install -q datasets transformers evaluate timm albumentations\n", - "```\n", - "\n", - "You'll use 🤗 Datasets to load a dataset from the Hugging Face Hub, 🤗 Transformers to train your model,\n", - "and `albumentations` to augment the data. `timm` is currently required to load a convolutional backbone for the DETR model.\n", - "\n", - "We encourage you to share your model with the community. Log in to your Hugging Face account to upload it to the Hub.\n", - "When prompted, enter your token to log in:" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "from huggingface_hub import notebook_login\n", - "\n", - "notebook_login()" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Load the CPPE-5 dataset" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "The [CPPE-5 dataset](https://huggingface.co/datasets/cppe-5) contains images with\n", - "annotations identifying medical personal protective equipment (PPE) in the context of the COVID-19 pandemic.\n", - "\n", - "Start by loading the dataset:" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "DatasetDict({\n", - " train: Dataset({\n", - " features: ['image_id', 'image', 'width', 'height', 'objects'],\n", - " num_rows: 1000\n", - " })\n", - " test: Dataset({\n", - " features: ['image_id', 'image', 'width', 'height', 'objects'],\n", - " num_rows: 29\n", - " })\n", - "})" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "from datasets import load_dataset\n", - "\n", - "cppe5 = load_dataset(\"cppe-5\")\n", - "cppe5" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "You'll see that this dataset already comes with a training set containing 1000 images and a test set with 29 images.\n", - "\n", - "To get familiar with the data, explore what the examples look like." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "{'image_id': 15,\n", - " 'image': ,\n", - " 'width': 943,\n", - " 'height': 663,\n", - " 'objects': {'id': [114, 115, 116, 117],\n", - " 'area': [3796, 1596, 152768, 81002],\n", - " 'bbox': [[302.0, 109.0, 73.0, 52.0],\n", - " [810.0, 100.0, 57.0, 28.0],\n", - " [160.0, 31.0, 248.0, 616.0],\n", - " [741.0, 68.0, 202.0, 401.0]],\n", - " 'category': [4, 4, 0, 0]}}" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "cppe5[\"train\"][0]" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "The examples in the dataset have the following fields:\n", - "- `image_id`: the example image id\n", - "- `image`: a `PIL.Image.Image` object containing the image\n", - "- `width`: width of the image\n", - "- `height`: height of the image\n", - "- `objects`: a dictionary containing bounding box metadata for the objects in the image:\n", - " - `id`: the annotation id\n", - " - `area`: the area of the bounding box\n", - " - `bbox`: the object's bounding box (in the [COCO format](https://albumentations.ai/docs/getting_started/bounding_boxes_augmentation/#coco) )\n", - " - `category`: the object's category, with possible values including `Coverall (0)`, `Face_Shield (1)`, `Gloves (2)`, `Goggles (3)` and `Mask (4)`\n", - "\n", - "You may notice that the `bbox` field follows the COCO format, which is the format that the DETR model expects.\n", - "However, the grouping of the fields inside `objects` differs from the annotation format DETR requires. You will\n", - "need to apply some preprocessing transformations before using this data for training.\n", - "\n", - "To get an even better understanding of the data, visualize an example in the dataset." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "import numpy as np\n", - "import os\n", - "from PIL import Image, ImageDraw\n", - "\n", - "image = cppe5[\"train\"][0][\"image\"]\n", - "annotations = cppe5[\"train\"][0][\"objects\"]\n", - "draw = ImageDraw.Draw(image)\n", - "\n", - "categories = cppe5[\"train\"].features[\"objects\"].feature[\"category\"].names\n", - "\n", - "id2label = {index: x for index, x in enumerate(categories, start=0)}\n", - "label2id = {v: k for k, v in id2label.items()}\n", - "\n", - "for i in range(len(annotations[\"id\"])):\n", - " box = annotations[\"bbox\"][i - 1]\n", - " class_idx = annotations[\"category\"][i - 1]\n", - " x, y, w, h = tuple(box)\n", - " draw.rectangle((x, y, x + w, y + h), outline=\"red\", width=1)\n", - " draw.text((x, y), id2label[class_idx], fill=\"white\")\n", - "\n", - "image" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "
\n", - " \"CPPE-5\n", - "
\n", - "\n", - "To visualize the bounding boxes with associated labels, you can get the labels from the dataset's metadata, specifically\n", - "the `category` field.\n", - "You'll also want to create dictionaries that map a label id to a label class (`id2label`) and the other way around (`label2id`).\n", - "You can use them later when setting up the model. Including these maps will make your model reusable by others if you share\n", - "it on the Hugging Face Hub.\n", - "\n", - "As a final step of getting familiar with the data, explore it for potential issues. One common problem with datasets for\n", - "object detection is bounding boxes that \"stretch\" beyond the edge of the image. Such \"runaway\" bounding boxes can raise\n", - "errors during training and should be addressed at this stage. There are a few examples with this issue in this dataset.\n", - "To keep things simple in this guide, we remove these images from the data." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "remove_idx = [590, 821, 822, 875, 876, 878, 879]\n", - "keep = [i for i in range(len(cppe5[\"train\"])) if i not in remove_idx]\n", - "cppe5[\"train\"] = cppe5[\"train\"].select(keep)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Preprocess the data" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "To finetune a model, you must preprocess the data you plan to use to match precisely the approach used for the pre-trained model.\n", - "[AutoImageProcessor](https://huggingface.co/docs/transformers/main/en/model_doc/auto#transformers.AutoImageProcessor) takes care of processing image data to create `pixel_values`, `pixel_mask`, and\n", - "`labels` that a DETR model can train with. The image processor has some attributes that you won't have to worry about:\n", - "\n", - "- `image_mean = [0.485, 0.456, 0.406 ]`\n", - "- `image_std = [0.229, 0.224, 0.225]`\n", - "\n", - "These are the mean and standard deviation used to normalize images during the model pre-training. These values are crucial\n", - "to replicate when doing inference or finetuning a pre-trained image model.\n", - "\n", - "Instantiate the image processor from the same checkpoint as the model you want to finetune." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "from transformers import AutoImageProcessor\n", - "\n", - "checkpoint = \"facebook/detr-resnet-50\"\n", - "image_processor = AutoImageProcessor.from_pretrained(checkpoint)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Before passing the images to the `image_processor`, apply two preprocessing transformations to the dataset:\n", - "- Augmenting images\n", - "- Reformatting annotations to meet DETR expectations\n", - "\n", - "First, to make sure the model does not overfit on the training data, you can apply image augmentation with any data augmentation library. Here we use [Albumentations](https://albumentations.ai/docs/) ...\n", - "This library ensures that transformations affect the image and update the bounding boxes accordingly.\n", - "The 🤗 Datasets library documentation has a detailed [guide on how to augment images for object detection](https://huggingface.co/docs/datasets/object_detection),\n", - "and it uses the exact same dataset as an example. Apply the same approach here, resize each image to (480, 480),\n", - "flip it horizontally, and brighten it:" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "import albumentations\n", - "import numpy as np\n", - "import torch\n", - "\n", - "transform = albumentations.Compose(\n", - " [\n", - " albumentations.Resize(480, 480),\n", - " albumentations.HorizontalFlip(p=1.0),\n", - " albumentations.RandomBrightnessContrast(p=1.0),\n", - " ],\n", - " bbox_params=albumentations.BboxParams(format=\"coco\", label_fields=[\"category\"]),\n", - ")" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "The `image_processor` expects the annotations to be in the following format: `{'image_id': int, 'annotations': List[Dict]}`,\n", - " where each dictionary is a COCO object annotation. Let's add a function to reformat annotations for a single example:" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "def formatted_anns(image_id, category, area, bbox):\n", - " annotations = []\n", - " for i in range(0, len(category)):\n", - " new_ann = {\n", - " \"image_id\": image_id,\n", - " \"category_id\": category[i],\n", - " \"isCrowd\": 0,\n", - " \"area\": area[i],\n", - " \"bbox\": list(bbox[i]),\n", - " }\n", - " annotations.append(new_ann)\n", - "\n", - " return annotations" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Now you can combine the image and annotation transformations to use on a batch of examples:" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "# transforming a batch\n", - "def transform_aug_ann(examples):\n", - " image_ids = examples[\"image_id\"]\n", - " images, bboxes, area, categories = [], [], [], []\n", - " for image, objects in zip(examples[\"image\"], examples[\"objects\"]):\n", - " image = np.array(image.convert(\"RGB\"))[:, :, ::-1]\n", - " out = transform(image=image, bboxes=objects[\"bbox\"], category=objects[\"category\"])\n", - "\n", - " area.append(objects[\"area\"])\n", - " images.append(out[\"image\"])\n", - " bboxes.append(out[\"bboxes\"])\n", - " categories.append(out[\"category\"])\n", - "\n", - " targets = [\n", - " {\"image_id\": id_, \"annotations\": formatted_anns(id_, cat_, ar_, box_)}\n", - " for id_, cat_, ar_, box_ in zip(image_ids, categories, area, bboxes)\n", - " ]\n", - "\n", - " return image_processor(images=images, annotations=targets, return_tensors=\"pt\")" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Apply this preprocessing function to the entire dataset using 🤗 Datasets [with_transform](https://huggingface.co/docs/datasets/main/en/package_reference/main_classes#datasets.Dataset.with_transform) method. This method applies\n", - "transformations on the fly when you load an element of the dataset.\n", - "\n", - "At this point, you can check what an example from the dataset looks like after the transformations. You should see a tensor\n", - "with `pixel_values`, a tensor with `pixel_mask`, and `labels`." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "{'pixel_values': tensor([[[ 0.9132, 0.9132, 0.9132, ..., -1.9809, -1.9809, -1.9809],\n", - " [ 0.9132, 0.9132, 0.9132, ..., -1.9809, -1.9809, -1.9809],\n", - " [ 0.9132, 0.9132, 0.9132, ..., -1.9638, -1.9638, -1.9638],\n", - " ...,\n", - " [-1.5699, -1.5699, -1.5699, ..., -1.9980, -1.9980, -1.9980],\n", - " [-1.5528, -1.5528, -1.5528, ..., -1.9980, -1.9809, -1.9809],\n", - " [-1.5528, -1.5528, -1.5528, ..., -1.9980, -1.9809, -1.9809]],\n", - "\n", - " [[ 1.3081, 1.3081, 1.3081, ..., -1.8431, -1.8431, -1.8431],\n", - " [ 1.3081, 1.3081, 1.3081, ..., -1.8431, -1.8431, -1.8431],\n", - " [ 1.3081, 1.3081, 1.3081, ..., -1.8256, -1.8256, -1.8256],\n", - " ...,\n", - " [-1.3179, -1.3179, -1.3179, ..., -1.8606, -1.8606, -1.8606],\n", - " [-1.3004, -1.3004, -1.3004, ..., -1.8606, -1.8431, -1.8431],\n", - " [-1.3004, -1.3004, -1.3004, ..., -1.8606, -1.8431, -1.8431]],\n", - "\n", - " [[ 1.4200, 1.4200, 1.4200, ..., -1.6476, -1.6476, -1.6476],\n", - " [ 1.4200, 1.4200, 1.4200, ..., -1.6476, -1.6476, -1.6476],\n", - " [ 1.4200, 1.4200, 1.4200, ..., -1.6302, -1.6302, -1.6302],\n", - " ...,\n", - " [-1.0201, -1.0201, -1.0201, ..., -1.5604, -1.5604, -1.5604],\n", - " [-1.0027, -1.0027, -1.0027, ..., -1.5604, -1.5430, -1.5430],\n", - " [-1.0027, -1.0027, -1.0027, ..., -1.5604, -1.5430, -1.5430]]]),\n", - " 'pixel_mask': tensor([[1, 1, 1, ..., 1, 1, 1],\n", - " [1, 1, 1, ..., 1, 1, 1],\n", - " [1, 1, 1, ..., 1, 1, 1],\n", - " ...,\n", - " [1, 1, 1, ..., 1, 1, 1],\n", - " [1, 1, 1, ..., 1, 1, 1],\n", - " [1, 1, 1, ..., 1, 1, 1]]),\n", - " 'labels': {'size': tensor([800, 800]), 'image_id': tensor([756]), 'class_labels': tensor([4]), 'boxes': tensor([[0.7340, 0.6986, 0.3414, 0.5944]]), 'area': tensor([519544.4375]), 'iscrowd': tensor([0]), 'orig_size': tensor([480, 480])}}" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "cppe5[\"train\"] = cppe5[\"train\"].with_transform(transform_aug_ann)\n", - "cppe5[\"train\"][15]" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "You have successfully augmented the individual images and prepared their annotations. However, preprocessing isn't\n", - "complete yet. In the final step, create a custom `collate_fn` to batch images together.\n", - "Pad images (which are now `pixel_values`) to the largest image in a batch, and create a corresponding `pixel_mask`\n", - "to indicate which pixels are real (1) and which are padding (0)." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "def collate_fn(batch):\n", - " pixel_values = [item[\"pixel_values\"] for item in batch]\n", - " encoding = image_processor.pad_and_create_pixel_mask(pixel_values, return_tensors=\"pt\")\n", - " labels = [item[\"labels\"] for item in batch]\n", - " batch = {}\n", - " batch[\"pixel_values\"] = encoding[\"pixel_values\"]\n", - " batch[\"pixel_mask\"] = encoding[\"pixel_mask\"]\n", - " batch[\"labels\"] = labels\n", - " return batch" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Training the DETR model" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "You have done most of the heavy lifting in the previous sections, so now you are ready to train your model!\n", - "The images in this dataset are still quite large, even after resizing. This means that finetuning this model will\n", - "require at least one GPU.\n", - "\n", - "Training involves the following steps:\n", - "1. Load the model with [AutoModelForObjectDetection](https://huggingface.co/docs/transformers/main/en/model_doc/auto#transformers.AutoModelForObjectDetection) using the same checkpoint as in the preprocessing.\n", - "2. Define your training hyperparameters in [TrainingArguments](https://huggingface.co/docs/transformers/main/en/main_classes/trainer#transformers.TrainingArguments).\n", - "3. Pass the training arguments to [Trainer](https://huggingface.co/docs/transformers/main/en/main_classes/trainer#transformers.Trainer) along with the model, dataset, image processor, and data collator.\n", - "4. Call [train()](https://huggingface.co/docs/transformers/main/en/main_classes/trainer#transformers.Trainer.train) to finetune your model.\n", - "\n", - "When loading the model from the same checkpoint that you used for the preprocessing, remember to pass the `label2id`\n", - "and `id2label` maps that you created earlier from the dataset's metadata. Additionally, we specify `ignore_mismatched_sizes=True` to replace the existing classification head with a new one." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "from transformers import AutoModelForObjectDetection\n", - "\n", - "model = AutoModelForObjectDetection.from_pretrained(\n", - " checkpoint,\n", - " id2label=id2label,\n", - " label2id=label2id,\n", - " ignore_mismatched_sizes=True,\n", - ")" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "In the [TrainingArguments](https://huggingface.co/docs/transformers/main/en/main_classes/trainer#transformers.TrainingArguments) use `output_dir` to specify where to save your model, then configure hyperparameters as you see fit.\n", - "It is important you do not remove unused columns because this will drop the image column. Without the image column, you\n", - "can't create `pixel_values`. For this reason, set `remove_unused_columns` to `False`.\n", - "If you wish to share your model by pushing to the Hub, set `push_to_hub` to `True` (you must be signed in to Hugging\n", - "Face to upload your model)." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "from transformers import TrainingArguments\n", - "\n", - "training_args = TrainingArguments(\n", - " output_dir=\"detr-resnet-50_finetuned_cppe5\",\n", - " per_device_train_batch_size=8,\n", - " num_train_epochs=10,\n", - " fp16=True,\n", - " save_steps=200,\n", - " logging_steps=50,\n", - " learning_rate=1e-5,\n", - " weight_decay=1e-4,\n", - " save_total_limit=2,\n", - " remove_unused_columns=False,\n", - " push_to_hub=True,\n", - ")" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Finally, bring everything together, and call [train()](https://huggingface.co/docs/transformers/main/en/main_classes/trainer#transformers.Trainer.train):" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "from transformers import Trainer\n", - "\n", - "trainer = Trainer(\n", - " model=model,\n", - " args=training_args,\n", - " data_collator=collate_fn,\n", - " train_dataset=cppe5[\"train\"],\n", - " tokenizer=image_processor,\n", - ")\n", - "\n", - "trainer.train()" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "If you have set `push_to_hub` to `True` in the `training_args`, the training checkpoints are pushed to the\n", - "Hugging Face Hub. Upon training completion, push the final model to the Hub as well by calling the [push_to_hub()](https://huggingface.co/docs/transformers/main/en/main_classes/trainer#transformers.Trainer.push_to_hub) method." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "trainer.push_to_hub()" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Evaluate" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Object detection models are commonly evaluated with a set of COCO-style metrics.\n", - "You can use one of the existing metrics implementations, but here you'll use the one from `torchvision` to evaluate the final\n", - "model that you pushed to the Hub.\n", - "\n", - "To use the `torchvision` evaluator, you'll need to prepare a ground truth COCO dataset. The API to build a COCO dataset\n", - "requires the data to be stored in a certain format, so you'll need to save images and annotations to disk first. Just like\n", - "when you prepared your data for training, the annotations from the `cppe5[\"test\"]` need to be formatted. However, images\n", - "should stay as they are.\n", - "\n", - "The evaluation step requires a bit of work, but it can be split in three major steps.\n", - "First, prepare the `cppe5[\"test\"]` set: format the annotations and save the data to disk." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "import json\n", - "\n", - "\n", - "# format annotations the same as for training, no need for data augmentation\n", - "def val_formatted_anns(image_id, objects):\n", - " annotations = []\n", - " for i in range(0, len(objects[\"id\"])):\n", - " new_ann = {\n", - " \"id\": objects[\"id\"][i],\n", - " \"category_id\": objects[\"category\"][i],\n", - " \"iscrowd\": 0,\n", - " \"image_id\": image_id,\n", - " \"area\": objects[\"area\"][i],\n", - " \"bbox\": objects[\"bbox\"][i],\n", - " }\n", - " annotations.append(new_ann)\n", - "\n", - " return annotations\n", - "\n", - "\n", - "# Save images and annotations into the files torchvision.datasets.CocoDetection expects\n", - "def save_cppe5_annotation_file_images(cppe5):\n", - " output_json = {}\n", - " path_output_cppe5 = f\"{os.getcwd()}/cppe5/\"\n", - "\n", - " if not os.path.exists(path_output_cppe5):\n", - " os.makedirs(path_output_cppe5)\n", - "\n", - " path_anno = os.path.join(path_output_cppe5, \"cppe5_ann.json\")\n", - " categories_json = [{\"supercategory\": \"none\", \"id\": id, \"name\": id2label[id]} for id in id2label]\n", - " output_json[\"images\"] = []\n", - " output_json[\"annotations\"] = []\n", - " for example in cppe5:\n", - " ann = val_formatted_anns(example[\"image_id\"], example[\"objects\"])\n", - " output_json[\"images\"].append(\n", - " {\n", - " \"id\": example[\"image_id\"],\n", - " \"width\": example[\"image\"].width,\n", - " \"height\": example[\"image\"].height,\n", - " \"file_name\": f\"{example['image_id']}.png\",\n", - " }\n", - " )\n", - " output_json[\"annotations\"].extend(ann)\n", - " output_json[\"categories\"] = categories_json\n", - "\n", - " with open(path_anno, \"w\") as file:\n", - " json.dump(output_json, file, ensure_ascii=False, indent=4)\n", - "\n", - " for im, img_id in zip(cppe5[\"image\"], cppe5[\"image_id\"]):\n", - " path_img = os.path.join(path_output_cppe5, f\"{img_id}.png\")\n", - " im.save(path_img)\n", - "\n", - " return path_output_cppe5, path_anno" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Next, prepare an instance of a `CocoDetection` class that can be used with `cocoevaluator`." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "import torchvision\n", - "\n", - "\n", - "class CocoDetection(torchvision.datasets.CocoDetection):\n", - " def __init__(self, img_folder, feature_extractor, ann_file):\n", - " super().__init__(img_folder, ann_file)\n", - " self.feature_extractor = feature_extractor\n", - "\n", - " def __getitem__(self, idx):\n", - " # read in PIL image and target in COCO format\n", - " img, target = super(CocoDetection, self).__getitem__(idx)\n", - "\n", - " # preprocess image and target: converting target to DETR format,\n", - " # resizing + normalization of both image and target)\n", - " image_id = self.ids[idx]\n", - " target = {\"image_id\": image_id, \"annotations\": target}\n", - " encoding = self.feature_extractor(images=img, annotations=target, return_tensors=\"pt\")\n", - " pixel_values = encoding[\"pixel_values\"].squeeze() # remove batch dimension\n", - " target = encoding[\"labels\"][0] # remove batch dimension\n", - "\n", - " return {\"pixel_values\": pixel_values, \"labels\": target}\n", - "\n", - "\n", - "im_processor = AutoImageProcessor.from_pretrained(\"MariaK/detr-resnet-50_finetuned_cppe5\")\n", - "\n", - "path_output_cppe5, path_anno = save_cppe5_annotation_file_images(cppe5[\"test\"])\n", - "test_ds_coco_format = CocoDetection(path_output_cppe5, im_processor, path_anno)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Finally, load the metrics and run the evaluation." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "Accumulating evaluation results...\n", - "DONE (t=0.08s).\n", - "IoU metric: bbox\n", - " Average Precision (AP) @[ IoU=0.50:0.95 | area= all | maxDets=100 ] = 0.150\n", - " Average Precision (AP) @[ IoU=0.50 | area= all | maxDets=100 ] = 0.280\n", - " Average Precision (AP) @[ IoU=0.75 | area= all | maxDets=100 ] = 0.130\n", - " Average Precision (AP) @[ IoU=0.50:0.95 | area= small | maxDets=100 ] = 0.038\n", - " Average Precision (AP) @[ IoU=0.50:0.95 | area=medium | maxDets=100 ] = 0.036\n", - " Average Precision (AP) @[ IoU=0.50:0.95 | area= large | maxDets=100 ] = 0.182\n", - " Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets= 1 ] = 0.166\n", - " Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets= 10 ] = 0.317\n", - " Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets=100 ] = 0.335\n", - " Average Recall (AR) @[ IoU=0.50:0.95 | area= small | maxDets=100 ] = 0.104\n", - " Average Recall (AR) @[ IoU=0.50:0.95 | area=medium | maxDets=100 ] = 0.146\n", - " Average Recall (AR) @[ IoU=0.50:0.95 | area= large | maxDets=100 ] = 0.382" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "import evaluate\n", - "from tqdm import tqdm\n", - "\n", - "model = AutoModelForObjectDetection.from_pretrained(\"MariaK/detr-resnet-50_finetuned_cppe5\")\n", - "module = evaluate.load(\"ybelkada/cocoevaluate\", coco=test_ds_coco_format.coco)\n", - "val_dataloader = torch.utils.data.DataLoader(\n", - " test_ds_coco_format, batch_size=8, shuffle=False, num_workers=4, collate_fn=collate_fn\n", - ")\n", - "\n", - "with torch.no_grad():\n", - " for idx, batch in enumerate(tqdm(val_dataloader)):\n", - " pixel_values = batch[\"pixel_values\"]\n", - " pixel_mask = batch[\"pixel_mask\"]\n", - "\n", - " labels = [\n", - " {k: v for k, v in t.items()} for t in batch[\"labels\"]\n", - " ] # these are in DETR format, resized + normalized\n", - "\n", - " # forward pass\n", - " outputs = model(pixel_values=pixel_values, pixel_mask=pixel_mask)\n", - "\n", - " orig_target_sizes = torch.stack([target[\"orig_size\"] for target in labels], dim=0)\n", - " results = im_processor.post_process(outputs, orig_target_sizes) # convert outputs of model to COCO api\n", - "\n", - " module.add(prediction=results, reference=labels)\n", - " del batch\n", - "\n", - "results = module.compute()\n", - "print(results)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "These results can be further improved by adjusting the hyperparameters in [TrainingArguments](https://huggingface.co/docs/transformers/main/en/main_classes/trainer#transformers.TrainingArguments). Give it a go!" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Inference" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Now that you have finetuned a DETR model, evaluated it, and uploaded it to the Hugging Face Hub, you can use it for inference.\n", - "The simplest way to try out your finetuned model for inference is to use it in a [Pipeline](https://huggingface.co/docs/transformers/main/en/main_classes/pipelines#transformers.Pipeline). Instantiate a pipeline\n", - "for object detection with your model, and pass an image to it:" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "from transformers import pipeline\n", - "import requests\n", - "\n", - "url = \"https://i.imgur.com/2lnWoly.jpg\"\n", - "image = Image.open(requests.get(url, stream=True).raw)\n", - "\n", - "obj_detector = pipeline(\"object-detection\", model=\"MariaK/detr-resnet-50_finetuned_cppe5\")\n", - "obj_detector(image)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "You can also manually replicate the results of the pipeline if you'd like:" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "Detected Coverall with confidence 0.566 at location [1215.32, 147.38, 4401.81, 3227.08]\n", - "Detected Mask with confidence 0.584 at location [2449.06, 823.19, 3256.43, 1413.9]" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" + "cells": [ + { + "cell_type": "markdown", + "metadata": { + "id": "RGZ_ixRwjRCs" + }, + "source": [ + "# Object detection" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "jszgZ7oEjRCt" + }, + "source": [ + "Object detection is the computer vision task of detecting instances (such as humans, buildings, or cars) in an image. Object detection models receive an image as input and output\n", + "coordinates of the bounding boxes and associated labels of the detected objects. An image can contain multiple objects,\n", + "each with its own bounding box and a label (e.g. it can have a car and a building), and each object can\n", + "be present in different parts of an image (e.g. the image can have several cars).\n", + "This task is commonly used in autonomous driving for detecting things like pedestrians, road signs, and traffic lights.\n", + "Other applications include counting objects in images, image search, and more.\n", + "\n", + "In this guide, you will learn how to:\n", + "\n", + " 1. Finetune [DETR](https://huggingface.co/docs/transformers/model_doc/detr), a model that combines a convolutional\n", + " backbone with an encoder-decoder Transformer, on the [CPPE-5](https://huggingface.co/datasets/cppe-5)\n", + " dataset.\n", + " 2. Use your finetuned model for inference.\n", + "\n", + "\n", + "The task illustrated in this tutorial is supported by the following model architectures:\n", + "\n", + "\n", + "\n", + "[Conditional DETR](https://huggingface.co/docs/transformers/main/en/tasks/../model_doc/conditional_detr), [Deformable DETR](https://huggingface.co/docs/transformers/main/en/tasks/../model_doc/deformable_detr), [DETA](https://huggingface.co/docs/transformers/main/en/tasks/../model_doc/deta), [DETR](https://huggingface.co/docs/transformers/main/en/tasks/../model_doc/detr), [Table Transformer](https://huggingface.co/docs/transformers/main/en/tasks/../model_doc/table-transformer), [YOLOS](https://huggingface.co/docs/transformers/main/en/tasks/../model_doc/yolos)\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "Before you begin, make sure you have all the necessary libraries installed:" + ] + }, + { + "cell_type": "code", + "source": [ + "!pip install -q datasets transformers accelerate timm\n", + "!pip install -q -U albumentations>=1.4.5 torchmetrics pycocotools" + ], + "metadata": { + "id": "1P6a3PSnksas" + }, + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "source": [ + "You'll use 🤗 Datasets to load a dataset from the Hugging Face Hub, 🤗 Transformers to train your model,\n", + "and `albumentations` to augment the data.\n", + "\n", + "We encourage you to share your model with the community. Log in to your Hugging Face account to upload it to the Hub.\n", + "When prompted, enter your token to log in:" + ], + "metadata": { + "id": "3yYvu7pZkzWW" + } + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "id": "_HsPYGtsjRCv" + }, + "outputs": [], + "source": [ + "from huggingface_hub import notebook_login\n", + "\n", + "notebook_login()" + ] + }, + { + "cell_type": "markdown", + "source": [ + "To get started, we’ll define global constants, namely the model name and image size. For this tutorial, we’ll use the conditional DETR model due to its faster convergence. Feel free to select any object detection model available in the `transformers` library." + ], + "metadata": { + "id": "HQkmL1BilBI3" + } + }, + { + "cell_type": "code", + "source": [ + "MODEL_NAME = \"microsoft/conditional-detr-resnet-50\" # or \"facebook/detr-resnet-50\"\n", + "IMAGE_SIZE = 480" + ], + "metadata": { + "id": "cjII16SilI9W" + }, + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "eBe33FwfjRCw" + }, + "source": [ + "## Load the CPPE-5 dataset" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "ibpJ2155jRCw" + }, + "source": [ + "The [CPPE-5 dataset](https://huggingface.co/datasets/cppe-5) contains images with\n", + "annotations identifying medical personal protective equipment (PPE) in the context of the COVID-19 pandemic.\n", + "\n", + "Start by loading the dataset and creating a `validation` split from `train`:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "id": "dO9QdPcyjRCx" + }, + "outputs": [], + "source": [ + "from datasets import load_dataset\n", + "\n", + "cppe5 = load_dataset(\"cppe-5\")\n", + "\n", + "if \"validation\" not in cppe5:\n", + " split = cppe5[\"train\"].train_test_split(0.15, seed=1337)\n", + " cppe5[\"train\"] = split[\"train\"]\n", + " cppe5[\"validation\"] = split[\"test\"]\n", + "\n", + "cppe5" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "0gJDWXTujRCy" + }, + "source": [ + "You'll see that this dataset already comes with a training set containing 1000 images and a test set with 29 images.\n", + "\n", + "To get familiar with the data, explore what the examples look like." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "id": "T_m_UlnWjRCz" + }, + "outputs": [], + "source": [ + "cppe5[\"train\"][0]" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "fm2sEEuTjRCz" + }, + "source": [ + "The examples in the dataset have the following fields:\n", + "- `image_id`: the example image id\n", + "- `image`: a `PIL.Image.Image` object containing the image\n", + "- `width`: width of the image\n", + "- `height`: height of the image\n", + "- `objects`: a dictionary containing bounding box metadata for the objects in the image:\n", + " - `id`: the annotation id\n", + " - `area`: the area of the bounding box\n", + " - `bbox`: the object's bounding box (in the [COCO format](https://albumentations.ai/docs/getting_started/bounding_boxes_augmentation/#coco) )\n", + " - `category`: the object's category, with possible values including `Coverall (0)`, `Face_Shield (1)`, `Gloves (2)`, `Goggles (3)` and `Mask (4)`\n", + "\n", + "You may notice that the `bbox` field follows the COCO format, which is the format that the DETR model expects.\n", + "However, the grouping of the fields inside `objects` differs from the annotation format DETR requires. You will\n", + "need to apply some preprocessing transformations before using this data for training.\n", + "\n", + "To get an even better understanding of the data, visualize an example in the dataset." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "id": "jsFt7kGRjRC0" + }, + "outputs": [], + "source": [ + "import numpy as np\n", + "import os\n", + "from PIL import Image, ImageDraw\n", + "\n", + "image = cppe5[\"train\"][2][\"image\"]\n", + "annotations = cppe5[\"train\"][2][\"objects\"]\n", + "draw = ImageDraw.Draw(image)\n", + "\n", + "categories = cppe5[\"train\"].features[\"objects\"].feature[\"category\"].names\n", + "\n", + "id2label = {index: x for index, x in enumerate(categories, start=0)}\n", + "label2id = {v: k for k, v in id2label.items()}\n", + "\n", + "for i in range(len(annotations[\"id\"])):\n", + " box = annotations[\"bbox\"][i]\n", + " class_idx = annotations[\"category\"][i]\n", + " x, y, w, h = tuple(box)\n", + " # Check if coordinates are normalized or not\n", + " if max(box) > 1.0:\n", + " # Coordinates are un-normalized, no need to re-scale them\n", + " x1, y1 = int(x), int(y)\n", + " x2, y2 = int(x + w), int(y + h)\n", + " else:\n", + " # Coordinates are normalized, re-scale them\n", + " x1 = int(x * width)\n", + " y1 = int(y * height)\n", + " x2 = int((x + w) * width)\n", + " y2 = int((y + h) * height)\n", + " draw.rectangle((x, y, x + w, y + h), outline=\"red\", width=1)\n", + " draw.text((x, y), id2label[class_idx], fill=\"white\")\n", + "\n", + "image" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "HnpNthhkjRC0" + }, + "source": [ + "
\n", + " \"CPPE-5\n", + "
\n", + "\n", + "To visualize the bounding boxes with associated labels, you can get the labels from the dataset’s metadata, specifically the category field. You’ll also want to create dictionaries that map a label id to a label class (`id2label`) and the other way around (`label2id`). You can use them later when setting up the model. Including these maps will make your model reusable by others if you share it on the Hugging Face Hub. Please note that, the part of above code that draws the bounding boxes assume that it is in COCO format (`x_min`, `y_min`, `width`, `height`). It has to be adjusted to work for other formats like (`x_min`, `y_min`, `x_max`, `y_max`).\n", + "\n", + "As a final step of getting familiar with the data, explore it for potential issues. One common problem with datasets for object detection is bounding boxes that “stretch” beyond the edge of the image. Such “runaway” bounding boxes can raise errors during training and should be addressed. There are a few examples with this issue in this dataset. To keep things simple in this guide, we will set `clip=True` for BboxParams in transformations below." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "ldq8KElAjRC1" + }, + "source": [ + "## Preprocess the data" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "e_fYpGfWjRC1" + }, + "source": [ + "To finetune a model, you must preprocess the data you plan to use to match precisely the approach used for the pre-trained model.\n", + "[AutoImageProcessor](https://huggingface.co/docs/transformers/main/en/model_doc/auto#transformers.AutoImageProcessor) takes care of processing image data to create `pixel_values`, `pixel_mask`, and\n", + "`labels` that a DETR model can train with. The image processor has some attributes that you won't have to worry about:\n", + "\n", + "- `image_mean = [0.485, 0.456, 0.406 ]`\n", + "- `image_std = [0.229, 0.224, 0.225]`\n", + "\n", + "These are the mean and standard deviation used to normalize images during the model pre-training. These values are crucial\n", + "to replicate when doing inference or finetuning a pre-trained image model.\n", + "\n", + "Instantiate the image processor from the same checkpoint as the model you want to finetune." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "id": "UdoN2AY9jRC1" + }, + "outputs": [], + "source": [ + "from transformers import AutoImageProcessor\n", + "\n", + "MAX_SIZE = IMAGE_SIZE\n", + "\n", + "image_processor = AutoImageProcessor.from_pretrained(\n", + " MODEL_NAME,\n", + " do_resize=True,\n", + " size={\"max_height\": MAX_SIZE, \"max_width\": MAX_SIZE},\n", + " do_pad=True,\n", + " pad_size={\"height\": MAX_SIZE, \"width\": MAX_SIZE},\n", + ")" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "Dd4q8oAYjRC1" + }, + "source": [ + "Before passing the images to the `image_processor`, apply two preprocessing transformations to the dataset:\n", + "- Augmenting images\n", + "- Reformatting annotations to meet DETR expectations\n", + "\n", + "First, to make sure the model does not overfit on the training data, you can apply image augmentation with any data augmentation library. Here we use [Albumentations](https://albumentations.ai/docs/). This library ensures that transformations affect the image and update the bounding boxes accordingly. The 🤗 Datasets library documentation has a detailed [guide on how to augment images for object detection](https://huggingface.co/docs/datasets/object_detection), and it uses the exact same dataset as an example. Apply some geometric and color transformations to the image. For additional augmentation options, explore the [Albumentations Demo Space](https://huggingface.co/spaces/qubvel-hf/albumentations-demo)." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "id": "fNUndKt4jRC2" + }, + "outputs": [], + "source": [ + "import albumentations as A\n", + "\n", + "train_augment_and_transform = A.Compose(\n", + " [\n", + " A.Perspective(p=0.1),\n", + " A.HorizontalFlip(p=0.5),\n", + " A.RandomBrightnessContrast(p=0.5),\n", + " A.HueSaturationValue(p=0.1),\n", + " ],\n", + " bbox_params=A.BboxParams(format=\"coco\", label_fields=[\"category\"], clip=True, min_area=25),\n", + ")\n", + "\n", + "validation_transform = A.Compose(\n", + " [A.NoOp()],\n", + " bbox_params=A.BboxParams(format=\"coco\", label_fields=[\"category\"], clip=True),\n", + ")" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "22sllfV-jRC2" + }, + "source": [ + "The `image_processor` expects the annotations to be in the following format: `{'image_id': int, 'annotations': List[Dict]}`,\n", + " where each dictionary is a COCO object annotation. Let's add a function to reformat annotations for a single example:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "id": "JY03a11pjRC2" + }, + "outputs": [], + "source": [ + "def format_image_annotations_as_coco(image_id, categories, areas, bboxes):\n", + " \"\"\"Format one set of image annotations to the COCO format\n", + "\n", + " Args:\n", + " image_id (str): image id. e.g. \"0001\"\n", + " categories (List[int]): list of categories/class labels corresponding to provided bounding boxes\n", + " areas (List[float]): list of corresponding areas to provided bounding boxes\n", + " bboxes (List[Tuple[float]]): list of bounding boxes provided in COCO format\n", + " ([center_x, center_y, width, height] in absolute coordinates)\n", + "\n", + " Returns:\n", + " dict: {\n", + " \"image_id\": image id,\n", + " \"annotations\": list of formatted annotations\n", + " }\n", + " \"\"\"\n", + " annotations = []\n", + " for category, area, bbox in zip(categories, areas, bboxes):\n", + " formatted_annotation = {\n", + " \"image_id\": image_id,\n", + " \"category_id\": category,\n", + " \"iscrowd\": 0,\n", + " \"area\": area,\n", + " \"bbox\": list(bbox),\n", + " }\n", + " annotations.append(formatted_annotation)\n", + "\n", + " return {\n", + " \"image_id\": image_id,\n", + " \"annotations\": annotations,\n", + " }\n" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "CFc5loLwjRC2" + }, + "source": [ + "Now you can combine the image and annotation transformations to use on a batch of examples:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "id": "FVD6SfzNjRC2" + }, + "outputs": [], + "source": [ + "def augment_and_transform_batch(examples, transform, image_processor, return_pixel_mask=False):\n", + " \"\"\"Apply augmentations and format annotations in COCO format for object detection task\"\"\"\n", + "\n", + " images = []\n", + " annotations = []\n", + " for image_id, image, objects in zip(examples[\"image_id\"], examples[\"image\"], examples[\"objects\"]):\n", + " image = np.array(image.convert(\"RGB\"))\n", + "\n", + " # apply augmentations\n", + " output = transform(image=image, bboxes=objects[\"bbox\"], category=objects[\"category\"])\n", + " images.append(output[\"image\"])\n", + "\n", + " # format annotations in COCO format\n", + " formatted_annotations = format_image_annotations_as_coco(\n", + " image_id, output[\"category\"], objects[\"area\"], output[\"bboxes\"]\n", + " )\n", + " annotations.append(formatted_annotations)\n", + "\n", + " # Apply the image processor transformations: resizing, rescaling, normalization\n", + " result = image_processor(images=images, annotations=annotations, return_tensors=\"pt\")\n", + "\n", + " if not return_pixel_mask:\n", + " result.pop(\"pixel_mask\", None)\n", + "\n", + " return result" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "glo-4364jRC3" + }, + "source": [ + "Apply this preprocessing function to the entire dataset using 🤗 Datasets [with_transform](https://huggingface.co/docs/datasets/main/en/package_reference/main_classes#datasets.Dataset.with_transform) method. This method applies\n", + "transformations on the fly when you load an element of the dataset.\n", + "\n", + "At this point, you can check what an example from the dataset looks like after the transformations. You should see a tensor\n", + "with `pixel_values`, a tensor with `pixel_mask`, and `labels`." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "id": "gCpLY48BjRC3" + }, + "outputs": [], + "source": [ + "from functools import partial\n", + "\n", + "# Make transform functions for batch and apply for dataset splits\n", + "train_transform_batch = partial(\n", + " augment_and_transform_batch, transform=train_augment_and_transform, image_processor=image_processor\n", + ")\n", + "validation_transform_batch = partial(\n", + " augment_and_transform_batch, transform=validation_transform, image_processor=image_processor\n", + ")\n", + "\n", + "cppe5[\"train\"] = cppe5[\"train\"].with_transform(train_transform_batch)\n", + "cppe5[\"validation\"] = cppe5[\"validation\"].with_transform(validation_transform_batch)\n", + "cppe5[\"test\"] = cppe5[\"test\"].with_transform(validation_transform_batch)\n", + "\n", + "cppe5[\"train\"][15]" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "6fU4KuKBjRC3" + }, + "source": [ + "You have successfully augmented the individual images and prepared their annotations. However, preprocessing isn't\n", + "complete yet. In the final step, create a custom `collate_fn` to batch images together.\n", + "Pad images (which are now `pixel_values`) to the largest image in a batch, and create a corresponding `pixel_mask`\n", + "to indicate which pixels are real (1) and which are padding (0)." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "id": "BePJFLoIjRC3" + }, + "outputs": [], + "source": [ + "import torch\n", + "\n", + "def collate_fn(batch):\n", + " data = {}\n", + " data[\"pixel_values\"] = torch.stack([x[\"pixel_values\"] for x in batch])\n", + " data[\"labels\"] = [x[\"labels\"] for x in batch]\n", + " if \"pixel_mask\" in batch[0]:\n", + " data[\"pixel_mask\"] = torch.stack([x[\"pixel_mask\"] for x in batch])\n", + " return data\n" + ] + }, + { + "cell_type": "markdown", + "source": [ + "## Preparing function to compute mAP" + ], + "metadata": { + "id": "xqy6XSavm5w6" + } + }, + { + "cell_type": "markdown", + "source": [ + "Object detection models are commonly evaluated with a set of [COCO-style](https://cocodataset.org/#detection-eval) metrics. We are going to use `torchmetrics` to compute `mAP` (mean average precision) and `mAR` (mean average recall) metrics and will wrap it to `compute_metrics` function in order to use in [Trainer](https://huggingface.co/docs/transformers/v4.44.2/en/main_classes/trainer#transformers.Trainer) for evaluation.\n", + "\n", + "Intermediate format of boxes used for training is YOLO (normalized) but we will compute metrics for boxes in `Pascal VOC` (absolute) format in order to correctly handle box areas. Let’s define a function that converts bounding boxes to `Pascal VOC` format:" + ], + "metadata": { + "id": "ar_FF5dOm8P_" + } + }, + { + "cell_type": "code", + "source": [ + "from transformers.image_transforms import center_to_corners_format\n", + "\n", + "def convert_bbox_yolo_to_pascal(boxes, image_size):\n", + " \"\"\"\n", + " Convert bounding boxes from YOLO format (x_center, y_center, width, height) in range [0, 1]\n", + " to Pascal VOC format (x_min, y_min, x_max, y_max) in absolute coordinates.\n", + "\n", + " Args:\n", + " boxes (torch.Tensor): Bounding boxes in YOLO format\n", + " image_size (Tuple[int, int]): Image size in format (height, width)\n", + "\n", + " Returns:\n", + " torch.Tensor: Bounding boxes in Pascal VOC format (x_min, y_min, x_max, y_max)\n", + " \"\"\"\n", + " # convert center to corners format\n", + " boxes = center_to_corners_format(boxes)\n", + "\n", + " # convert to absolute coordinates\n", + " height, width = image_size\n", + " boxes = boxes * torch.tensor([[width, height, width, height]])\n", + "\n", + " return boxes" + ], + "metadata": { + "id": "zjQcKfc5nNub" + }, + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "source": [ + "Then, in `compute_metrics` function we collect `predicted` and `target` bounding boxes, scores and labels from evaluation loop results and pass it to the scoring function.\n", + "\n" + ], + "metadata": { + "id": "0fCnOE7lnQEr" + } + }, + { + "cell_type": "code", + "source": [ + "import numpy as np\n", + "from dataclasses import dataclass\n", + "from torchmetrics.detection.mean_ap import MeanAveragePrecision\n", + "\n", + "\n", + "@dataclass\n", + "class ModelOutput:\n", + " logits: torch.Tensor\n", + " pred_boxes: torch.Tensor\n", + "\n", + "\n", + "@torch.no_grad()\n", + "def compute_metrics(evaluation_results, image_processor, threshold=0.0, id2label=None):\n", + " \"\"\"\n", + " Compute mean average mAP, mAR and their variants for the object detection task.\n", + "\n", + " Args:\n", + " evaluation_results (EvalPrediction): Predictions and targets from evaluation.\n", + " threshold (float, optional): Threshold to filter predicted boxes by confidence. Defaults to 0.0.\n", + " id2label (Optional[dict], optional): Mapping from class id to class name. Defaults to None.\n", + "\n", + " Returns:\n", + " Mapping[str, float]: Metrics in a form of dictionary {: }\n", + " \"\"\"\n", + "\n", + " predictions, targets = evaluation_results.predictions, evaluation_results.label_ids\n", + "\n", + " # For metric computation we need to provide:\n", + " # - targets in a form of list of dictionaries with keys \"boxes\", \"labels\"\n", + " # - predictions in a form of list of dictionaries with keys \"boxes\", \"scores\", \"labels\"\n", + "\n", + " image_sizes = []\n", + " post_processed_targets = []\n", + " post_processed_predictions = []\n", + "\n", + " # Collect targets in the required format for metric computation\n", + " for batch in targets:\n", + " # collect image sizes, we will need them for predictions post processing\n", + " batch_image_sizes = torch.tensor(np.array([x[\"orig_size\"] for x in batch]))\n", + " image_sizes.append(batch_image_sizes)\n", + " # collect targets in the required format for metric computation\n", + " # boxes were converted to YOLO format needed for model training\n", + " # here we will convert them to Pascal VOC format (x_min, y_min, x_max, y_max)\n", + " for image_target in batch:\n", + " boxes = torch.tensor(image_target[\"boxes\"])\n", + " boxes = convert_bbox_yolo_to_pascal(boxes, image_target[\"orig_size\"])\n", + " labels = torch.tensor(image_target[\"class_labels\"])\n", + " post_processed_targets.append({\"boxes\": boxes, \"labels\": labels})\n", + "\n", + " # Collect predictions in the required format for metric computation,\n", + " # model produce boxes in YOLO format, then image_processor convert them to Pascal VOC format\n", + " for batch, target_sizes in zip(predictions, image_sizes):\n", + " batch_logits, batch_boxes = batch[1], batch[2]\n", + " output = ModelOutput(logits=torch.tensor(batch_logits), pred_boxes=torch.tensor(batch_boxes))\n", + " post_processed_output = image_processor.post_process_object_detection(\n", + " output, threshold=threshold, target_sizes=target_sizes\n", + " )\n", + " post_processed_predictions.extend(post_processed_output)\n", + "\n", + " # Compute metrics\n", + " metric = MeanAveragePrecision(box_format=\"xyxy\", class_metrics=True)\n", + " metric.update(post_processed_predictions, post_processed_targets)\n", + " metrics = metric.compute()\n", + "\n", + " # Replace list of per class metrics with separate metric for each class\n", + " classes = metrics.pop(\"classes\")\n", + " map_per_class = metrics.pop(\"map_per_class\")\n", + " mar_100_per_class = metrics.pop(\"mar_100_per_class\")\n", + " for class_id, class_map, class_mar in zip(classes, map_per_class, mar_100_per_class):\n", + " class_name = id2label[class_id.item()] if id2label is not None else class_id.item()\n", + " metrics[f\"map_{class_name}\"] = class_map\n", + " metrics[f\"mar_100_{class_name}\"] = class_mar\n", + "\n", + " metrics = {k: round(v.item(), 4) for k, v in metrics.items()}\n", + "\n", + " return metrics\n", + "\n", + "\n", + "eval_compute_metrics_fn = partial(\n", + " compute_metrics, image_processor=image_processor, id2label=id2label, threshold=0.0\n", + ")" + ], + "metadata": { + "id": "CzwJvhGRnS3B" + }, + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "0UxzYsMnjRC4" + }, + "source": [ + "## Training the detection model" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "_l19Rj6DjRC4" + }, + "source": [ + "You have done most of the heavy lifting in the previous sections, so now you are ready to train your model!\n", + "The images in this dataset are still quite large, even after resizing. This means that finetuning this model will\n", + "require at least one GPU.\n", + "\n", + "Training involves the following steps:\n", + "1. Load the model with [AutoModelForObjectDetection](https://huggingface.co/docs/transformers/main/en/model_doc/auto#transformers.AutoModelForObjectDetection) using the same checkpoint as in the preprocessing.\n", + "2. Define your training hyperparameters in [TrainingArguments](https://huggingface.co/docs/transformers/main/en/main_classes/trainer#transformers.TrainingArguments).\n", + "3. Pass the training arguments to [Trainer](https://huggingface.co/docs/transformers/main/en/main_classes/trainer#transformers.Trainer) along with the model, dataset, image processor, and data collator.\n", + "4. Call [train()](https://huggingface.co/docs/transformers/main/en/main_classes/trainer#transformers.Trainer.train) to finetune your model.\n", + "\n", + "When loading the model from the same checkpoint that you used for the preprocessing, remember to pass the `label2id`\n", + "and `id2label` maps that you created earlier from the dataset's metadata. Additionally, we specify `ignore_mismatched_sizes=True` to replace the existing classification head with a new one." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "id": "oltzA-rFjRC4" + }, + "outputs": [], + "source": [ + "from transformers import AutoModelForObjectDetection\n", + "\n", + "model = AutoModelForObjectDetection.from_pretrained(\n", + " MODEL_NAME,\n", + " id2label=id2label,\n", + " label2id=label2id,\n", + " ignore_mismatched_sizes=True,\n", + ")" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "Qxizsg6DjRC4" + }, + "source": [ + "In the [TrainingArguments](https://huggingface.co/docs/transformers/v4.44.2/en/main_classes/trainer#transformers.TrainingArguments) use `output_dir` to specify where to save your model, then configure hyperparameters as you see fit. For `num_train_epochs=30` training will take about 35 minutes in Google Colab T4 GPU, increase the number of epoch to get better results.\n", + "\n", + "Important notes:\n", + "\n", + "* Do not remove unused columns because this will drop the image column. Without the image column, you can’t create pixel_values. For this reason, set `remove_unused_columns` to False.\n", + "* Set `eval_do_concat_batches=False` to get proper evaluation results. Images have different number of target boxes, if batches are concatenated we will not be able to determine which boxes belongs to particular image.\n", + "\n", + "If you wish to share your model by pushing to the Hub, set `push_to_hub` to `True` (you must be signed in to Hugging Face to upload your model)." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "id": "Pxo6N6mRjRC4" + }, + "outputs": [], + "source": [ + "from transformers import TrainingArguments\n", + "\n", + "training_args = TrainingArguments(\n", + " output_dir=\"detr_finetuned_cppe5\",\n", + " num_train_epochs=30,\n", + " fp16=False,\n", + " per_device_train_batch_size=8,\n", + " dataloader_num_workers=4,\n", + " learning_rate=5e-5,\n", + " lr_scheduler_type=\"cosine\",\n", + " weight_decay=1e-4,\n", + " max_grad_norm=0.01,\n", + " metric_for_best_model=\"eval_map\",\n", + " greater_is_better=True,\n", + " load_best_model_at_end=True,\n", + " eval_strategy=\"epoch\",\n", + " save_strategy=\"epoch\",\n", + " save_total_limit=2,\n", + " remove_unused_columns=False,\n", + " eval_do_concat_batches=False,\n", + " push_to_hub=True,\n", + ")" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "6x5DqV79jRC5" + }, + "source": [ + "Finally, bring everything together, and call [train()](https://huggingface.co/docs/transformers/main/en/main_classes/trainer#transformers.Trainer.train):" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "id": "xh288Qz_jRC5" + }, + "outputs": [], + "source": [ + "from transformers import Trainer\n", + "\n", + "trainer = Trainer(\n", + " model=model,\n", + " args=training_args,\n", + " train_dataset=cppe5[\"train\"],\n", + " eval_dataset=cppe5[\"validation\"],\n", + " tokenizer=image_processor,\n", + " data_collator=collate_fn,\n", + " compute_metrics=eval_compute_metrics_fn,\n", + ")\n", + "\n", + "trainer.train()" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "y-EBN0HpjRC6" + }, + "source": [ + "If you have set `push_to_hub` to `True` in the `training_args`, the training checkpoints are pushed to the\n", + "Hugging Face Hub. Upon training completion, push the final model to the Hub as well by calling the [push_to_hub()](https://huggingface.co/docs/transformers/main/en/main_classes/trainer#transformers.Trainer.push_to_hub) method." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "id": "9P8AhLUBjRC6" + }, + "outputs": [], + "source": [ + "trainer.push_to_hub()" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "iqHN9RJvjRC6" + }, + "source": [ + "## Evaluate" + ] + }, + { + "cell_type": "code", + "source": [ + "from pprint import pprint\n", + "\n", + "metrics = trainer.evaluate(eval_dataset=cppe5[\"test\"], metric_key_prefix=\"test\")\n", + "pprint(metrics)" + ], + "metadata": { + "id": "maTIoC5ln4CE" + }, + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "source": [ + "These results can be further improved by adjusting the hyperparameters in [TrainingArguments](https://huggingface.co/docs/transformers/v4.44.2/en/main_classes/trainer#transformers.TrainingArguments). Give it a go!\n", + "\n" + ], + "metadata": { + "id": "sjbRpIFqn5rt" + } + }, + { + "cell_type": "markdown", + "source": [ + "## Inference" + ], + "metadata": { + "id": "yfZ59nikn9kv" + } + }, + { + "cell_type": "markdown", + "source": [ + "Now that you have finetuned a model, evaluated it, and uploaded it to the Hugging Face Hub, you can use it for inference.\n", + "\n" + ], + "metadata": { + "id": "HCa_YwdkoA00" + } + }, + { + "cell_type": "code", + "source": [ + "import torch\n", + "import requests\n", + "\n", + "from PIL import Image, ImageDraw\n", + "from transformers import AutoImageProcessor, AutoModelForObjectDetection\n", + "\n", + "url = \"https://images.pexels.com/photos/8413299/pexels-photo-8413299.jpeg?auto=compress&cs=tinysrgb&w=630&h=375&dpr=2\"\n", + "image = Image.open(requests.get(url, stream=True).raw)" + ], + "metadata": { + "id": "nYEc4L50n-mW" + }, + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "source": [ + "Load model and image processor from the Hugging Face Hub (skip to use already trained in this session):\n", + "\n" + ], + "metadata": { + "id": "qrWYfmu0oDnz" + } + }, + { + "cell_type": "code", + "source": [ + "device = \"cuda\"\n", + "model_repo = \"qubvel-hf/detr_finetuned_cppe5\"\n", + "\n", + "image_processor = AutoImageProcessor.from_pretrained(model_repo)\n", + "model = AutoModelForObjectDetection.from_pretrained(model_repo)\n", + "model = model.to(device)" + ], + "metadata": { + "id": "OmwZ-ltzoFSq" + }, + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "source": [ + "And detect bounding boxes:\n", + "\n" + ], + "metadata": { + "id": "DptFENNOoGoG" + } + }, + { + "cell_type": "code", + "source": [ + "with torch.no_grad():\n", + " inputs = image_processor(images=[image], return_tensors=\"pt\")\n", + " outputs = model(**inputs.to(device))\n", + " target_sizes = torch.tensor([[image.size[1], image.size[0]]])\n", + " results = image_processor.post_process_object_detection(outputs, threshold=0.3, target_sizes=target_sizes)[0]\n", + "\n", + "for score, label, box in zip(results[\"scores\"], results[\"labels\"], results[\"boxes\"]):\n", + " box = [round(i, 2) for i in box.tolist()]\n", + " print(\n", + " f\"Detected {model.config.id2label[label.item()]} with confidence \"\n", + " f\"{round(score.item(), 3)} at location {box}\"\n", + " )" + ], + "metadata": { + "id": "YlFWNFRxoHDI" + }, + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "source": [ + "Let’s plot the result:\n", + "\n" + ], + "metadata": { + "id": "j_m35fRzoJmV" + } + }, + { + "cell_type": "code", + "source": [ + "draw = ImageDraw.Draw(image)\n", + "\n", + "for score, label, box in zip(results[\"scores\"], results[\"labels\"], results[\"boxes\"]):\n", + " box = [round(i, 2) for i in box.tolist()]\n", + " x, y, x2, y2 = tuple(box)\n", + " draw.rectangle((x, y, x2, y2), outline=\"red\", width=1)\n", + " draw.text((x, y), model.config.id2label[label.item()], fill=\"white\")\n", + "\n", + "image" + ], + "metadata": { + "id": "ZuLuGKl2oJ9X" + }, + "execution_count": null, + "outputs": [] } - ], - "source": [ - "image_processor = AutoImageProcessor.from_pretrained(\"MariaK/detr-resnet-50_finetuned_cppe5\")\n", - "model = AutoModelForObjectDetection.from_pretrained(\"MariaK/detr-resnet-50_finetuned_cppe5\")\n", - "\n", - "with torch.no_grad():\n", - " inputs = image_processor(images=image, return_tensors=\"pt\")\n", - " outputs = model(**inputs)\n", - " target_sizes = torch.tensor([image.size[::-1]])\n", - " results = image_processor.post_process_object_detection(outputs, threshold=0.5, target_sizes=target_sizes)[0]\n", - "\n", - "for score, label, box in zip(results[\"scores\"], results[\"labels\"], results[\"boxes\"]):\n", - " box = [round(i, 2) for i in box.tolist()]\n", - " print(\n", - " f\"Detected {model.config.id2label[label.item()]} with confidence \"\n", - " f\"{round(score.item(), 3)} at location {box}\"\n", - " )" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Let's plot the result:" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "draw = ImageDraw.Draw(image)\n", - "\n", - "for score, label, box in zip(results[\"scores\"], results[\"labels\"], results[\"boxes\"]):\n", - " box = [round(i, 2) for i in box.tolist()]\n", - " x, y, x2, y2 = tuple(box)\n", - " draw.rectangle((x, y, x2, y2), outline=\"red\", width=1)\n", - " draw.text((x, y), model.config.id2label[label.item()], fill=\"white\")\n", - "\n", - "image" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "
\n", - " \"Object\n", - "
" - ] - } - ], - "metadata": {}, - "nbformat": 4, - "nbformat_minor": 4 -} + ], + "metadata": { + "colab": { + "provenance": [], + "toc_visible": true, + "gpuType": "T4" + }, + "language_info": { + "name": "python" + }, + "kernelspec": { + "name": "python3", + "display_name": "Python 3" + }, + "accelerator": "GPU" + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/transformers_doc/en/pytorch/object_detection.ipynb b/transformers_doc/en/pytorch/object_detection.ipynb index 934b1a96..ad3ba3cd 100644 --- a/transformers_doc/en/pytorch/object_detection.ipynb +++ b/transformers_doc/en/pytorch/object_detection.ipynb @@ -1,900 +1,977 @@ { - "cells": [ - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "# Transformers installation\n", - "! pip install transformers datasets\n", - "# To install from source instead of the last release, comment the command above and uncomment the following one.\n", - "# ! pip install git+https://github.com/huggingface/transformers.git" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "# Object detection" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Object detection is the computer vision task of detecting instances (such as humans, buildings, or cars) in an image. Object detection models receive an image as input and output\n", - "coordinates of the bounding boxes and associated labels of the detected objects. An image can contain multiple objects,\n", - "each with its own bounding box and a label (e.g. it can have a car and a building), and each object can\n", - "be present in different parts of an image (e.g. the image can have several cars).\n", - "This task is commonly used in autonomous driving for detecting things like pedestrians, road signs, and traffic lights.\n", - "Other applications include counting objects in images, image search, and more.\n", - "\n", - "In this guide, you will learn how to:\n", - "\n", - " 1. Finetune [DETR](https://huggingface.co/docs/transformers/model_doc/detr), a model that combines a convolutional\n", - " backbone with an encoder-decoder Transformer, on the [CPPE-5](https://huggingface.co/datasets/cppe-5)\n", - " dataset.\n", - " 2. Use your finetuned model for inference.\n", - "\n", - "\n", - "The task illustrated in this tutorial is supported by the following model architectures:\n", - "\n", - "\n", - "\n", - "[Conditional DETR](https://huggingface.co/docs/transformers/main/en/tasks/../model_doc/conditional_detr), [Deformable DETR](https://huggingface.co/docs/transformers/main/en/tasks/../model_doc/deformable_detr), [DETA](https://huggingface.co/docs/transformers/main/en/tasks/../model_doc/deta), [DETR](https://huggingface.co/docs/transformers/main/en/tasks/../model_doc/detr), [Table Transformer](https://huggingface.co/docs/transformers/main/en/tasks/../model_doc/table-transformer), [YOLOS](https://huggingface.co/docs/transformers/main/en/tasks/../model_doc/yolos)\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "Before you begin, make sure you have all the necessary libraries installed:\n", - "\n", - "```bash\n", - "pip install -q datasets transformers evaluate timm albumentations\n", - "```\n", - "\n", - "You'll use 🤗 Datasets to load a dataset from the Hugging Face Hub, 🤗 Transformers to train your model,\n", - "and `albumentations` to augment the data. `timm` is currently required to load a convolutional backbone for the DETR model.\n", - "\n", - "We encourage you to share your model with the community. Log in to your Hugging Face account to upload it to the Hub.\n", - "When prompted, enter your token to log in:" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "from huggingface_hub import notebook_login\n", - "\n", - "notebook_login()" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Load the CPPE-5 dataset" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "The [CPPE-5 dataset](https://huggingface.co/datasets/cppe-5) contains images with\n", - "annotations identifying medical personal protective equipment (PPE) in the context of the COVID-19 pandemic.\n", - "\n", - "Start by loading the dataset:" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "DatasetDict({\n", - " train: Dataset({\n", - " features: ['image_id', 'image', 'width', 'height', 'objects'],\n", - " num_rows: 1000\n", - " })\n", - " test: Dataset({\n", - " features: ['image_id', 'image', 'width', 'height', 'objects'],\n", - " num_rows: 29\n", - " })\n", - "})" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "from datasets import load_dataset\n", - "\n", - "cppe5 = load_dataset(\"cppe-5\")\n", - "cppe5" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "You'll see that this dataset already comes with a training set containing 1000 images and a test set with 29 images.\n", - "\n", - "To get familiar with the data, explore what the examples look like." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "{'image_id': 15,\n", - " 'image': ,\n", - " 'width': 943,\n", - " 'height': 663,\n", - " 'objects': {'id': [114, 115, 116, 117],\n", - " 'area': [3796, 1596, 152768, 81002],\n", - " 'bbox': [[302.0, 109.0, 73.0, 52.0],\n", - " [810.0, 100.0, 57.0, 28.0],\n", - " [160.0, 31.0, 248.0, 616.0],\n", - " [741.0, 68.0, 202.0, 401.0]],\n", - " 'category': [4, 4, 0, 0]}}" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "cppe5[\"train\"][0]" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "The examples in the dataset have the following fields:\n", - "- `image_id`: the example image id\n", - "- `image`: a `PIL.Image.Image` object containing the image\n", - "- `width`: width of the image\n", - "- `height`: height of the image\n", - "- `objects`: a dictionary containing bounding box metadata for the objects in the image:\n", - " - `id`: the annotation id\n", - " - `area`: the area of the bounding box\n", - " - `bbox`: the object's bounding box (in the [COCO format](https://albumentations.ai/docs/getting_started/bounding_boxes_augmentation/#coco) )\n", - " - `category`: the object's category, with possible values including `Coverall (0)`, `Face_Shield (1)`, `Gloves (2)`, `Goggles (3)` and `Mask (4)`\n", - "\n", - "You may notice that the `bbox` field follows the COCO format, which is the format that the DETR model expects.\n", - "However, the grouping of the fields inside `objects` differs from the annotation format DETR requires. You will\n", - "need to apply some preprocessing transformations before using this data for training.\n", - "\n", - "To get an even better understanding of the data, visualize an example in the dataset." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "import numpy as np\n", - "import os\n", - "from PIL import Image, ImageDraw\n", - "\n", - "image = cppe5[\"train\"][0][\"image\"]\n", - "annotations = cppe5[\"train\"][0][\"objects\"]\n", - "draw = ImageDraw.Draw(image)\n", - "\n", - "categories = cppe5[\"train\"].features[\"objects\"].feature[\"category\"].names\n", - "\n", - "id2label = {index: x for index, x in enumerate(categories, start=0)}\n", - "label2id = {v: k for k, v in id2label.items()}\n", - "\n", - "for i in range(len(annotations[\"id\"])):\n", - " box = annotations[\"bbox\"][i - 1]\n", - " class_idx = annotations[\"category\"][i - 1]\n", - " x, y, w, h = tuple(box)\n", - " draw.rectangle((x, y, x + w, y + h), outline=\"red\", width=1)\n", - " draw.text((x, y), id2label[class_idx], fill=\"white\")\n", - "\n", - "image" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "
\n", - " \"CPPE-5\n", - "
\n", - "\n", - "To visualize the bounding boxes with associated labels, you can get the labels from the dataset's metadata, specifically\n", - "the `category` field.\n", - "You'll also want to create dictionaries that map a label id to a label class (`id2label`) and the other way around (`label2id`).\n", - "You can use them later when setting up the model. Including these maps will make your model reusable by others if you share\n", - "it on the Hugging Face Hub.\n", - "\n", - "As a final step of getting familiar with the data, explore it for potential issues. One common problem with datasets for\n", - "object detection is bounding boxes that \"stretch\" beyond the edge of the image. Such \"runaway\" bounding boxes can raise\n", - "errors during training and should be addressed at this stage. There are a few examples with this issue in this dataset.\n", - "To keep things simple in this guide, we remove these images from the data." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "remove_idx = [590, 821, 822, 875, 876, 878, 879]\n", - "keep = [i for i in range(len(cppe5[\"train\"])) if i not in remove_idx]\n", - "cppe5[\"train\"] = cppe5[\"train\"].select(keep)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Preprocess the data" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "To finetune a model, you must preprocess the data you plan to use to match precisely the approach used for the pre-trained model.\n", - "[AutoImageProcessor](https://huggingface.co/docs/transformers/main/en/model_doc/auto#transformers.AutoImageProcessor) takes care of processing image data to create `pixel_values`, `pixel_mask`, and\n", - "`labels` that a DETR model can train with. The image processor has some attributes that you won't have to worry about:\n", - "\n", - "- `image_mean = [0.485, 0.456, 0.406 ]`\n", - "- `image_std = [0.229, 0.224, 0.225]`\n", - "\n", - "These are the mean and standard deviation used to normalize images during the model pre-training. These values are crucial\n", - "to replicate when doing inference or finetuning a pre-trained image model.\n", - "\n", - "Instantiate the image processor from the same checkpoint as the model you want to finetune." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "from transformers import AutoImageProcessor\n", - "\n", - "checkpoint = \"facebook/detr-resnet-50\"\n", - "image_processor = AutoImageProcessor.from_pretrained(checkpoint)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Before passing the images to the `image_processor`, apply two preprocessing transformations to the dataset:\n", - "- Augmenting images\n", - "- Reformatting annotations to meet DETR expectations\n", - "\n", - "First, to make sure the model does not overfit on the training data, you can apply image augmentation with any data augmentation library. Here we use [Albumentations](https://albumentations.ai/docs/) ...\n", - "This library ensures that transformations affect the image and update the bounding boxes accordingly.\n", - "The 🤗 Datasets library documentation has a detailed [guide on how to augment images for object detection](https://huggingface.co/docs/datasets/object_detection),\n", - "and it uses the exact same dataset as an example. Apply the same approach here, resize each image to (480, 480),\n", - "flip it horizontally, and brighten it:" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "import albumentations\n", - "import numpy as np\n", - "import torch\n", - "\n", - "transform = albumentations.Compose(\n", - " [\n", - " albumentations.Resize(480, 480),\n", - " albumentations.HorizontalFlip(p=1.0),\n", - " albumentations.RandomBrightnessContrast(p=1.0),\n", - " ],\n", - " bbox_params=albumentations.BboxParams(format=\"coco\", label_fields=[\"category\"]),\n", - ")" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "The `image_processor` expects the annotations to be in the following format: `{'image_id': int, 'annotations': List[Dict]}`,\n", - " where each dictionary is a COCO object annotation. Let's add a function to reformat annotations for a single example:" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "def formatted_anns(image_id, category, area, bbox):\n", - " annotations = []\n", - " for i in range(0, len(category)):\n", - " new_ann = {\n", - " \"image_id\": image_id,\n", - " \"category_id\": category[i],\n", - " \"isCrowd\": 0,\n", - " \"area\": area[i],\n", - " \"bbox\": list(bbox[i]),\n", - " }\n", - " annotations.append(new_ann)\n", - "\n", - " return annotations" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Now you can combine the image and annotation transformations to use on a batch of examples:" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "# transforming a batch\n", - "def transform_aug_ann(examples):\n", - " image_ids = examples[\"image_id\"]\n", - " images, bboxes, area, categories = [], [], [], []\n", - " for image, objects in zip(examples[\"image\"], examples[\"objects\"]):\n", - " image = np.array(image.convert(\"RGB\"))[:, :, ::-1]\n", - " out = transform(image=image, bboxes=objects[\"bbox\"], category=objects[\"category\"])\n", - "\n", - " area.append(objects[\"area\"])\n", - " images.append(out[\"image\"])\n", - " bboxes.append(out[\"bboxes\"])\n", - " categories.append(out[\"category\"])\n", - "\n", - " targets = [\n", - " {\"image_id\": id_, \"annotations\": formatted_anns(id_, cat_, ar_, box_)}\n", - " for id_, cat_, ar_, box_ in zip(image_ids, categories, area, bboxes)\n", - " ]\n", - "\n", - " return image_processor(images=images, annotations=targets, return_tensors=\"pt\")" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Apply this preprocessing function to the entire dataset using 🤗 Datasets [with_transform](https://huggingface.co/docs/datasets/main/en/package_reference/main_classes#datasets.Dataset.with_transform) method. This method applies\n", - "transformations on the fly when you load an element of the dataset.\n", - "\n", - "At this point, you can check what an example from the dataset looks like after the transformations. You should see a tensor\n", - "with `pixel_values`, a tensor with `pixel_mask`, and `labels`." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "{'pixel_values': tensor([[[ 0.9132, 0.9132, 0.9132, ..., -1.9809, -1.9809, -1.9809],\n", - " [ 0.9132, 0.9132, 0.9132, ..., -1.9809, -1.9809, -1.9809],\n", - " [ 0.9132, 0.9132, 0.9132, ..., -1.9638, -1.9638, -1.9638],\n", - " ...,\n", - " [-1.5699, -1.5699, -1.5699, ..., -1.9980, -1.9980, -1.9980],\n", - " [-1.5528, -1.5528, -1.5528, ..., -1.9980, -1.9809, -1.9809],\n", - " [-1.5528, -1.5528, -1.5528, ..., -1.9980, -1.9809, -1.9809]],\n", - "\n", - " [[ 1.3081, 1.3081, 1.3081, ..., -1.8431, -1.8431, -1.8431],\n", - " [ 1.3081, 1.3081, 1.3081, ..., -1.8431, -1.8431, -1.8431],\n", - " [ 1.3081, 1.3081, 1.3081, ..., -1.8256, -1.8256, -1.8256],\n", - " ...,\n", - " [-1.3179, -1.3179, -1.3179, ..., -1.8606, -1.8606, -1.8606],\n", - " [-1.3004, -1.3004, -1.3004, ..., -1.8606, -1.8431, -1.8431],\n", - " [-1.3004, -1.3004, -1.3004, ..., -1.8606, -1.8431, -1.8431]],\n", - "\n", - " [[ 1.4200, 1.4200, 1.4200, ..., -1.6476, -1.6476, -1.6476],\n", - " [ 1.4200, 1.4200, 1.4200, ..., -1.6476, -1.6476, -1.6476],\n", - " [ 1.4200, 1.4200, 1.4200, ..., -1.6302, -1.6302, -1.6302],\n", - " ...,\n", - " [-1.0201, -1.0201, -1.0201, ..., -1.5604, -1.5604, -1.5604],\n", - " [-1.0027, -1.0027, -1.0027, ..., -1.5604, -1.5430, -1.5430],\n", - " [-1.0027, -1.0027, -1.0027, ..., -1.5604, -1.5430, -1.5430]]]),\n", - " 'pixel_mask': tensor([[1, 1, 1, ..., 1, 1, 1],\n", - " [1, 1, 1, ..., 1, 1, 1],\n", - " [1, 1, 1, ..., 1, 1, 1],\n", - " ...,\n", - " [1, 1, 1, ..., 1, 1, 1],\n", - " [1, 1, 1, ..., 1, 1, 1],\n", - " [1, 1, 1, ..., 1, 1, 1]]),\n", - " 'labels': {'size': tensor([800, 800]), 'image_id': tensor([756]), 'class_labels': tensor([4]), 'boxes': tensor([[0.7340, 0.6986, 0.3414, 0.5944]]), 'area': tensor([519544.4375]), 'iscrowd': tensor([0]), 'orig_size': tensor([480, 480])}}" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "cppe5[\"train\"] = cppe5[\"train\"].with_transform(transform_aug_ann)\n", - "cppe5[\"train\"][15]" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "You have successfully augmented the individual images and prepared their annotations. However, preprocessing isn't\n", - "complete yet. In the final step, create a custom `collate_fn` to batch images together.\n", - "Pad images (which are now `pixel_values`) to the largest image in a batch, and create a corresponding `pixel_mask`\n", - "to indicate which pixels are real (1) and which are padding (0)." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "def collate_fn(batch):\n", - " pixel_values = [item[\"pixel_values\"] for item in batch]\n", - " encoding = image_processor.pad_and_create_pixel_mask(pixel_values, return_tensors=\"pt\")\n", - " labels = [item[\"labels\"] for item in batch]\n", - " batch = {}\n", - " batch[\"pixel_values\"] = encoding[\"pixel_values\"]\n", - " batch[\"pixel_mask\"] = encoding[\"pixel_mask\"]\n", - " batch[\"labels\"] = labels\n", - " return batch" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Training the DETR model" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "You have done most of the heavy lifting in the previous sections, so now you are ready to train your model!\n", - "The images in this dataset are still quite large, even after resizing. This means that finetuning this model will\n", - "require at least one GPU.\n", - "\n", - "Training involves the following steps:\n", - "1. Load the model with [AutoModelForObjectDetection](https://huggingface.co/docs/transformers/main/en/model_doc/auto#transformers.AutoModelForObjectDetection) using the same checkpoint as in the preprocessing.\n", - "2. Define your training hyperparameters in [TrainingArguments](https://huggingface.co/docs/transformers/main/en/main_classes/trainer#transformers.TrainingArguments).\n", - "3. Pass the training arguments to [Trainer](https://huggingface.co/docs/transformers/main/en/main_classes/trainer#transformers.Trainer) along with the model, dataset, image processor, and data collator.\n", - "4. Call [train()](https://huggingface.co/docs/transformers/main/en/main_classes/trainer#transformers.Trainer.train) to finetune your model.\n", - "\n", - "When loading the model from the same checkpoint that you used for the preprocessing, remember to pass the `label2id`\n", - "and `id2label` maps that you created earlier from the dataset's metadata. Additionally, we specify `ignore_mismatched_sizes=True` to replace the existing classification head with a new one." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "from transformers import AutoModelForObjectDetection\n", - "\n", - "model = AutoModelForObjectDetection.from_pretrained(\n", - " checkpoint,\n", - " id2label=id2label,\n", - " label2id=label2id,\n", - " ignore_mismatched_sizes=True,\n", - ")" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "In the [TrainingArguments](https://huggingface.co/docs/transformers/main/en/main_classes/trainer#transformers.TrainingArguments) use `output_dir` to specify where to save your model, then configure hyperparameters as you see fit.\n", - "It is important you do not remove unused columns because this will drop the image column. Without the image column, you\n", - "can't create `pixel_values`. For this reason, set `remove_unused_columns` to `False`.\n", - "If you wish to share your model by pushing to the Hub, set `push_to_hub` to `True` (you must be signed in to Hugging\n", - "Face to upload your model)." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "from transformers import TrainingArguments\n", - "\n", - "training_args = TrainingArguments(\n", - " output_dir=\"detr-resnet-50_finetuned_cppe5\",\n", - " per_device_train_batch_size=8,\n", - " num_train_epochs=10,\n", - " fp16=True,\n", - " save_steps=200,\n", - " logging_steps=50,\n", - " learning_rate=1e-5,\n", - " weight_decay=1e-4,\n", - " save_total_limit=2,\n", - " remove_unused_columns=False,\n", - " push_to_hub=True,\n", - ")" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Finally, bring everything together, and call [train()](https://huggingface.co/docs/transformers/main/en/main_classes/trainer#transformers.Trainer.train):" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "from transformers import Trainer\n", - "\n", - "trainer = Trainer(\n", - " model=model,\n", - " args=training_args,\n", - " data_collator=collate_fn,\n", - " train_dataset=cppe5[\"train\"],\n", - " tokenizer=image_processor,\n", - ")\n", - "\n", - "trainer.train()" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "If you have set `push_to_hub` to `True` in the `training_args`, the training checkpoints are pushed to the\n", - "Hugging Face Hub. Upon training completion, push the final model to the Hub as well by calling the [push_to_hub()](https://huggingface.co/docs/transformers/main/en/main_classes/trainer#transformers.Trainer.push_to_hub) method." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "trainer.push_to_hub()" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Evaluate" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Object detection models are commonly evaluated with a set of COCO-style metrics.\n", - "You can use one of the existing metrics implementations, but here you'll use the one from `torchvision` to evaluate the final\n", - "model that you pushed to the Hub.\n", - "\n", - "To use the `torchvision` evaluator, you'll need to prepare a ground truth COCO dataset. The API to build a COCO dataset\n", - "requires the data to be stored in a certain format, so you'll need to save images and annotations to disk first. Just like\n", - "when you prepared your data for training, the annotations from the `cppe5[\"test\"]` need to be formatted. However, images\n", - "should stay as they are.\n", - "\n", - "The evaluation step requires a bit of work, but it can be split in three major steps.\n", - "First, prepare the `cppe5[\"test\"]` set: format the annotations and save the data to disk." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "import json\n", - "\n", - "\n", - "# format annotations the same as for training, no need for data augmentation\n", - "def val_formatted_anns(image_id, objects):\n", - " annotations = []\n", - " for i in range(0, len(objects[\"id\"])):\n", - " new_ann = {\n", - " \"id\": objects[\"id\"][i],\n", - " \"category_id\": objects[\"category\"][i],\n", - " \"iscrowd\": 0,\n", - " \"image_id\": image_id,\n", - " \"area\": objects[\"area\"][i],\n", - " \"bbox\": objects[\"bbox\"][i],\n", - " }\n", - " annotations.append(new_ann)\n", - "\n", - " return annotations\n", - "\n", - "\n", - "# Save images and annotations into the files torchvision.datasets.CocoDetection expects\n", - "def save_cppe5_annotation_file_images(cppe5):\n", - " output_json = {}\n", - " path_output_cppe5 = f\"{os.getcwd()}/cppe5/\"\n", - "\n", - " if not os.path.exists(path_output_cppe5):\n", - " os.makedirs(path_output_cppe5)\n", - "\n", - " path_anno = os.path.join(path_output_cppe5, \"cppe5_ann.json\")\n", - " categories_json = [{\"supercategory\": \"none\", \"id\": id, \"name\": id2label[id]} for id in id2label]\n", - " output_json[\"images\"] = []\n", - " output_json[\"annotations\"] = []\n", - " for example in cppe5:\n", - " ann = val_formatted_anns(example[\"image_id\"], example[\"objects\"])\n", - " output_json[\"images\"].append(\n", - " {\n", - " \"id\": example[\"image_id\"],\n", - " \"width\": example[\"image\"].width,\n", - " \"height\": example[\"image\"].height,\n", - " \"file_name\": f\"{example['image_id']}.png\",\n", - " }\n", - " )\n", - " output_json[\"annotations\"].extend(ann)\n", - " output_json[\"categories\"] = categories_json\n", - "\n", - " with open(path_anno, \"w\") as file:\n", - " json.dump(output_json, file, ensure_ascii=False, indent=4)\n", - "\n", - " for im, img_id in zip(cppe5[\"image\"], cppe5[\"image_id\"]):\n", - " path_img = os.path.join(path_output_cppe5, f\"{img_id}.png\")\n", - " im.save(path_img)\n", - "\n", - " return path_output_cppe5, path_anno" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Next, prepare an instance of a `CocoDetection` class that can be used with `cocoevaluator`." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "import torchvision\n", - "\n", - "\n", - "class CocoDetection(torchvision.datasets.CocoDetection):\n", - " def __init__(self, img_folder, feature_extractor, ann_file):\n", - " super().__init__(img_folder, ann_file)\n", - " self.feature_extractor = feature_extractor\n", - "\n", - " def __getitem__(self, idx):\n", - " # read in PIL image and target in COCO format\n", - " img, target = super(CocoDetection, self).__getitem__(idx)\n", - "\n", - " # preprocess image and target: converting target to DETR format,\n", - " # resizing + normalization of both image and target)\n", - " image_id = self.ids[idx]\n", - " target = {\"image_id\": image_id, \"annotations\": target}\n", - " encoding = self.feature_extractor(images=img, annotations=target, return_tensors=\"pt\")\n", - " pixel_values = encoding[\"pixel_values\"].squeeze() # remove batch dimension\n", - " target = encoding[\"labels\"][0] # remove batch dimension\n", - "\n", - " return {\"pixel_values\": pixel_values, \"labels\": target}\n", - "\n", - "\n", - "im_processor = AutoImageProcessor.from_pretrained(\"MariaK/detr-resnet-50_finetuned_cppe5\")\n", - "\n", - "path_output_cppe5, path_anno = save_cppe5_annotation_file_images(cppe5[\"test\"])\n", - "test_ds_coco_format = CocoDetection(path_output_cppe5, im_processor, path_anno)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Finally, load the metrics and run the evaluation." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "Accumulating evaluation results...\n", - "DONE (t=0.08s).\n", - "IoU metric: bbox\n", - " Average Precision (AP) @[ IoU=0.50:0.95 | area= all | maxDets=100 ] = 0.150\n", - " Average Precision (AP) @[ IoU=0.50 | area= all | maxDets=100 ] = 0.280\n", - " Average Precision (AP) @[ IoU=0.75 | area= all | maxDets=100 ] = 0.130\n", - " Average Precision (AP) @[ IoU=0.50:0.95 | area= small | maxDets=100 ] = 0.038\n", - " Average Precision (AP) @[ IoU=0.50:0.95 | area=medium | maxDets=100 ] = 0.036\n", - " Average Precision (AP) @[ IoU=0.50:0.95 | area= large | maxDets=100 ] = 0.182\n", - " Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets= 1 ] = 0.166\n", - " Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets= 10 ] = 0.317\n", - " Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets=100 ] = 0.335\n", - " Average Recall (AR) @[ IoU=0.50:0.95 | area= small | maxDets=100 ] = 0.104\n", - " Average Recall (AR) @[ IoU=0.50:0.95 | area=medium | maxDets=100 ] = 0.146\n", - " Average Recall (AR) @[ IoU=0.50:0.95 | area= large | maxDets=100 ] = 0.382" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "import evaluate\n", - "from tqdm import tqdm\n", - "\n", - "model = AutoModelForObjectDetection.from_pretrained(\"MariaK/detr-resnet-50_finetuned_cppe5\")\n", - "module = evaluate.load(\"ybelkada/cocoevaluate\", coco=test_ds_coco_format.coco)\n", - "val_dataloader = torch.utils.data.DataLoader(\n", - " test_ds_coco_format, batch_size=8, shuffle=False, num_workers=4, collate_fn=collate_fn\n", - ")\n", - "\n", - "with torch.no_grad():\n", - " for idx, batch in enumerate(tqdm(val_dataloader)):\n", - " pixel_values = batch[\"pixel_values\"]\n", - " pixel_mask = batch[\"pixel_mask\"]\n", - "\n", - " labels = [\n", - " {k: v for k, v in t.items()} for t in batch[\"labels\"]\n", - " ] # these are in DETR format, resized + normalized\n", - "\n", - " # forward pass\n", - " outputs = model(pixel_values=pixel_values, pixel_mask=pixel_mask)\n", - "\n", - " orig_target_sizes = torch.stack([target[\"orig_size\"] for target in labels], dim=0)\n", - " results = im_processor.post_process(outputs, orig_target_sizes) # convert outputs of model to COCO api\n", - "\n", - " module.add(prediction=results, reference=labels)\n", - " del batch\n", - "\n", - "results = module.compute()\n", - "print(results)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "These results can be further improved by adjusting the hyperparameters in [TrainingArguments](https://huggingface.co/docs/transformers/main/en/main_classes/trainer#transformers.TrainingArguments). Give it a go!" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Inference" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Now that you have finetuned a DETR model, evaluated it, and uploaded it to the Hugging Face Hub, you can use it for inference.\n", - "The simplest way to try out your finetuned model for inference is to use it in a [Pipeline](https://huggingface.co/docs/transformers/main/en/main_classes/pipelines#transformers.Pipeline). Instantiate a pipeline\n", - "for object detection with your model, and pass an image to it:" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "from transformers import pipeline\n", - "import requests\n", - "\n", - "url = \"https://i.imgur.com/2lnWoly.jpg\"\n", - "image = Image.open(requests.get(url, stream=True).raw)\n", - "\n", - "obj_detector = pipeline(\"object-detection\", model=\"MariaK/detr-resnet-50_finetuned_cppe5\")\n", - "obj_detector(image)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "You can also manually replicate the results of the pipeline if you'd like:" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "Detected Coverall with confidence 0.566 at location [1215.32, 147.38, 4401.81, 3227.08]\n", - "Detected Mask with confidence 0.584 at location [2449.06, 823.19, 3256.43, 1413.9]" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" + "cells": [ + { + "cell_type": "markdown", + "metadata": { + "id": "RGZ_ixRwjRCs" + }, + "source": [ + "# Object detection" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "jszgZ7oEjRCt" + }, + "source": [ + "Object detection is the computer vision task of detecting instances (such as humans, buildings, or cars) in an image. Object detection models receive an image as input and output\n", + "coordinates of the bounding boxes and associated labels of the detected objects. An image can contain multiple objects,\n", + "each with its own bounding box and a label (e.g. it can have a car and a building), and each object can\n", + "be present in different parts of an image (e.g. the image can have several cars).\n", + "This task is commonly used in autonomous driving for detecting things like pedestrians, road signs, and traffic lights.\n", + "Other applications include counting objects in images, image search, and more.\n", + "\n", + "In this guide, you will learn how to:\n", + "\n", + " 1. Finetune [DETR](https://huggingface.co/docs/transformers/model_doc/detr), a model that combines a convolutional\n", + " backbone with an encoder-decoder Transformer, on the [CPPE-5](https://huggingface.co/datasets/cppe-5)\n", + " dataset.\n", + " 2. Use your finetuned model for inference.\n", + "\n", + "\n", + "The task illustrated in this tutorial is supported by the following model architectures:\n", + "\n", + "\n", + "\n", + "[Conditional DETR](https://huggingface.co/docs/transformers/main/en/tasks/../model_doc/conditional_detr), [Deformable DETR](https://huggingface.co/docs/transformers/main/en/tasks/../model_doc/deformable_detr), [DETA](https://huggingface.co/docs/transformers/main/en/tasks/../model_doc/deta), [DETR](https://huggingface.co/docs/transformers/main/en/tasks/../model_doc/detr), [Table Transformer](https://huggingface.co/docs/transformers/main/en/tasks/../model_doc/table-transformer), [YOLOS](https://huggingface.co/docs/transformers/main/en/tasks/../model_doc/yolos)\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "Before you begin, make sure you have all the necessary libraries installed:" + ] + }, + { + "cell_type": "code", + "source": [ + "!pip install -q datasets transformers accelerate timm\n", + "!pip install -q -U albumentations>=1.4.5 torchmetrics pycocotools" + ], + "metadata": { + "id": "1P6a3PSnksas" + }, + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "source": [ + "You'll use 🤗 Datasets to load a dataset from the Hugging Face Hub, 🤗 Transformers to train your model,\n", + "and `albumentations` to augment the data.\n", + "\n", + "We encourage you to share your model with the community. Log in to your Hugging Face account to upload it to the Hub.\n", + "When prompted, enter your token to log in:" + ], + "metadata": { + "id": "3yYvu7pZkzWW" + } + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "id": "_HsPYGtsjRCv" + }, + "outputs": [], + "source": [ + "from huggingface_hub import notebook_login\n", + "\n", + "notebook_login()" + ] + }, + { + "cell_type": "markdown", + "source": [ + "To get started, we’ll define global constants, namely the model name and image size. For this tutorial, we’ll use the conditional DETR model due to its faster convergence. Feel free to select any object detection model available in the `transformers` library." + ], + "metadata": { + "id": "HQkmL1BilBI3" + } + }, + { + "cell_type": "code", + "source": [ + "MODEL_NAME = \"microsoft/conditional-detr-resnet-50\" # or \"facebook/detr-resnet-50\"\n", + "IMAGE_SIZE = 480" + ], + "metadata": { + "id": "cjII16SilI9W" + }, + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "eBe33FwfjRCw" + }, + "source": [ + "## Load the CPPE-5 dataset" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "ibpJ2155jRCw" + }, + "source": [ + "The [CPPE-5 dataset](https://huggingface.co/datasets/cppe-5) contains images with\n", + "annotations identifying medical personal protective equipment (PPE) in the context of the COVID-19 pandemic.\n", + "\n", + "Start by loading the dataset and creating a `validation` split from `train`:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "id": "dO9QdPcyjRCx" + }, + "outputs": [], + "source": [ + "from datasets import load_dataset\n", + "\n", + "cppe5 = load_dataset(\"cppe-5\")\n", + "\n", + "if \"validation\" not in cppe5:\n", + " split = cppe5[\"train\"].train_test_split(0.15, seed=1337)\n", + " cppe5[\"train\"] = split[\"train\"]\n", + " cppe5[\"validation\"] = split[\"test\"]\n", + "\n", + "cppe5" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "0gJDWXTujRCy" + }, + "source": [ + "You'll see that this dataset already comes with a training set containing 1000 images and a test set with 29 images.\n", + "\n", + "To get familiar with the data, explore what the examples look like." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "id": "T_m_UlnWjRCz" + }, + "outputs": [], + "source": [ + "cppe5[\"train\"][0]" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "fm2sEEuTjRCz" + }, + "source": [ + "The examples in the dataset have the following fields:\n", + "- `image_id`: the example image id\n", + "- `image`: a `PIL.Image.Image` object containing the image\n", + "- `width`: width of the image\n", + "- `height`: height of the image\n", + "- `objects`: a dictionary containing bounding box metadata for the objects in the image:\n", + " - `id`: the annotation id\n", + " - `area`: the area of the bounding box\n", + " - `bbox`: the object's bounding box (in the [COCO format](https://albumentations.ai/docs/getting_started/bounding_boxes_augmentation/#coco) )\n", + " - `category`: the object's category, with possible values including `Coverall (0)`, `Face_Shield (1)`, `Gloves (2)`, `Goggles (3)` and `Mask (4)`\n", + "\n", + "You may notice that the `bbox` field follows the COCO format, which is the format that the DETR model expects.\n", + "However, the grouping of the fields inside `objects` differs from the annotation format DETR requires. You will\n", + "need to apply some preprocessing transformations before using this data for training.\n", + "\n", + "To get an even better understanding of the data, visualize an example in the dataset." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "id": "jsFt7kGRjRC0" + }, + "outputs": [], + "source": [ + "import numpy as np\n", + "import os\n", + "from PIL import Image, ImageDraw\n", + "\n", + "image = cppe5[\"train\"][2][\"image\"]\n", + "annotations = cppe5[\"train\"][2][\"objects\"]\n", + "draw = ImageDraw.Draw(image)\n", + "\n", + "categories = cppe5[\"train\"].features[\"objects\"].feature[\"category\"].names\n", + "\n", + "id2label = {index: x for index, x in enumerate(categories, start=0)}\n", + "label2id = {v: k for k, v in id2label.items()}\n", + "\n", + "for i in range(len(annotations[\"id\"])):\n", + " box = annotations[\"bbox\"][i]\n", + " class_idx = annotations[\"category\"][i]\n", + " x, y, w, h = tuple(box)\n", + " # Check if coordinates are normalized or not\n", + " if max(box) > 1.0:\n", + " # Coordinates are un-normalized, no need to re-scale them\n", + " x1, y1 = int(x), int(y)\n", + " x2, y2 = int(x + w), int(y + h)\n", + " else:\n", + " # Coordinates are normalized, re-scale them\n", + " x1 = int(x * width)\n", + " y1 = int(y * height)\n", + " x2 = int((x + w) * width)\n", + " y2 = int((y + h) * height)\n", + " draw.rectangle((x, y, x + w, y + h), outline=\"red\", width=1)\n", + " draw.text((x, y), id2label[class_idx], fill=\"white\")\n", + "\n", + "image" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "HnpNthhkjRC0" + }, + "source": [ + "
\n", + " \"CPPE-5\n", + "
\n", + "\n", + "To visualize the bounding boxes with associated labels, you can get the labels from the dataset’s metadata, specifically the category field. You’ll also want to create dictionaries that map a label id to a label class (`id2label`) and the other way around (`label2id`). You can use them later when setting up the model. Including these maps will make your model reusable by others if you share it on the Hugging Face Hub. Please note that, the part of above code that draws the bounding boxes assume that it is in COCO format (`x_min`, `y_min`, `width`, `height`). It has to be adjusted to work for other formats like (`x_min`, `y_min`, `x_max`, `y_max`).\n", + "\n", + "As a final step of getting familiar with the data, explore it for potential issues. One common problem with datasets for object detection is bounding boxes that “stretch” beyond the edge of the image. Such “runaway” bounding boxes can raise errors during training and should be addressed. There are a few examples with this issue in this dataset. To keep things simple in this guide, we will set `clip=True` for BboxParams in transformations below." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "ldq8KElAjRC1" + }, + "source": [ + "## Preprocess the data" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "e_fYpGfWjRC1" + }, + "source": [ + "To finetune a model, you must preprocess the data you plan to use to match precisely the approach used for the pre-trained model.\n", + "[AutoImageProcessor](https://huggingface.co/docs/transformers/main/en/model_doc/auto#transformers.AutoImageProcessor) takes care of processing image data to create `pixel_values`, `pixel_mask`, and\n", + "`labels` that a DETR model can train with. The image processor has some attributes that you won't have to worry about:\n", + "\n", + "- `image_mean = [0.485, 0.456, 0.406 ]`\n", + "- `image_std = [0.229, 0.224, 0.225]`\n", + "\n", + "These are the mean and standard deviation used to normalize images during the model pre-training. These values are crucial\n", + "to replicate when doing inference or finetuning a pre-trained image model.\n", + "\n", + "Instantiate the image processor from the same checkpoint as the model you want to finetune." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "id": "UdoN2AY9jRC1" + }, + "outputs": [], + "source": [ + "from transformers import AutoImageProcessor\n", + "\n", + "MAX_SIZE = IMAGE_SIZE\n", + "\n", + "image_processor = AutoImageProcessor.from_pretrained(\n", + " MODEL_NAME,\n", + " do_resize=True,\n", + " size={\"max_height\": MAX_SIZE, \"max_width\": MAX_SIZE},\n", + " do_pad=True,\n", + " pad_size={\"height\": MAX_SIZE, \"width\": MAX_SIZE},\n", + ")" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "Dd4q8oAYjRC1" + }, + "source": [ + "Before passing the images to the `image_processor`, apply two preprocessing transformations to the dataset:\n", + "- Augmenting images\n", + "- Reformatting annotations to meet DETR expectations\n", + "\n", + "First, to make sure the model does not overfit on the training data, you can apply image augmentation with any data augmentation library. Here we use [Albumentations](https://albumentations.ai/docs/). This library ensures that transformations affect the image and update the bounding boxes accordingly. The 🤗 Datasets library documentation has a detailed [guide on how to augment images for object detection](https://huggingface.co/docs/datasets/object_detection), and it uses the exact same dataset as an example. Apply some geometric and color transformations to the image. For additional augmentation options, explore the [Albumentations Demo Space](https://huggingface.co/spaces/qubvel-hf/albumentations-demo)." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "id": "fNUndKt4jRC2" + }, + "outputs": [], + "source": [ + "import albumentations as A\n", + "\n", + "train_augment_and_transform = A.Compose(\n", + " [\n", + " A.Perspective(p=0.1),\n", + " A.HorizontalFlip(p=0.5),\n", + " A.RandomBrightnessContrast(p=0.5),\n", + " A.HueSaturationValue(p=0.1),\n", + " ],\n", + " bbox_params=A.BboxParams(format=\"coco\", label_fields=[\"category\"], clip=True, min_area=25),\n", + ")\n", + "\n", + "validation_transform = A.Compose(\n", + " [A.NoOp()],\n", + " bbox_params=A.BboxParams(format=\"coco\", label_fields=[\"category\"], clip=True),\n", + ")" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "22sllfV-jRC2" + }, + "source": [ + "The `image_processor` expects the annotations to be in the following format: `{'image_id': int, 'annotations': List[Dict]}`,\n", + " where each dictionary is a COCO object annotation. Let's add a function to reformat annotations for a single example:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "id": "JY03a11pjRC2" + }, + "outputs": [], + "source": [ + "def format_image_annotations_as_coco(image_id, categories, areas, bboxes):\n", + " \"\"\"Format one set of image annotations to the COCO format\n", + "\n", + " Args:\n", + " image_id (str): image id. e.g. \"0001\"\n", + " categories (List[int]): list of categories/class labels corresponding to provided bounding boxes\n", + " areas (List[float]): list of corresponding areas to provided bounding boxes\n", + " bboxes (List[Tuple[float]]): list of bounding boxes provided in COCO format\n", + " ([center_x, center_y, width, height] in absolute coordinates)\n", + "\n", + " Returns:\n", + " dict: {\n", + " \"image_id\": image id,\n", + " \"annotations\": list of formatted annotations\n", + " }\n", + " \"\"\"\n", + " annotations = []\n", + " for category, area, bbox in zip(categories, areas, bboxes):\n", + " formatted_annotation = {\n", + " \"image_id\": image_id,\n", + " \"category_id\": category,\n", + " \"iscrowd\": 0,\n", + " \"area\": area,\n", + " \"bbox\": list(bbox),\n", + " }\n", + " annotations.append(formatted_annotation)\n", + "\n", + " return {\n", + " \"image_id\": image_id,\n", + " \"annotations\": annotations,\n", + " }\n" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "CFc5loLwjRC2" + }, + "source": [ + "Now you can combine the image and annotation transformations to use on a batch of examples:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "id": "FVD6SfzNjRC2" + }, + "outputs": [], + "source": [ + "def augment_and_transform_batch(examples, transform, image_processor, return_pixel_mask=False):\n", + " \"\"\"Apply augmentations and format annotations in COCO format for object detection task\"\"\"\n", + "\n", + " images = []\n", + " annotations = []\n", + " for image_id, image, objects in zip(examples[\"image_id\"], examples[\"image\"], examples[\"objects\"]):\n", + " image = np.array(image.convert(\"RGB\"))\n", + "\n", + " # apply augmentations\n", + " output = transform(image=image, bboxes=objects[\"bbox\"], category=objects[\"category\"])\n", + " images.append(output[\"image\"])\n", + "\n", + " # format annotations in COCO format\n", + " formatted_annotations = format_image_annotations_as_coco(\n", + " image_id, output[\"category\"], objects[\"area\"], output[\"bboxes\"]\n", + " )\n", + " annotations.append(formatted_annotations)\n", + "\n", + " # Apply the image processor transformations: resizing, rescaling, normalization\n", + " result = image_processor(images=images, annotations=annotations, return_tensors=\"pt\")\n", + "\n", + " if not return_pixel_mask:\n", + " result.pop(\"pixel_mask\", None)\n", + "\n", + " return result" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "glo-4364jRC3" + }, + "source": [ + "Apply this preprocessing function to the entire dataset using 🤗 Datasets [with_transform](https://huggingface.co/docs/datasets/main/en/package_reference/main_classes#datasets.Dataset.with_transform) method. This method applies\n", + "transformations on the fly when you load an element of the dataset.\n", + "\n", + "At this point, you can check what an example from the dataset looks like after the transformations. You should see a tensor\n", + "with `pixel_values`, a tensor with `pixel_mask`, and `labels`." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "id": "gCpLY48BjRC3" + }, + "outputs": [], + "source": [ + "from functools import partial\n", + "\n", + "# Make transform functions for batch and apply for dataset splits\n", + "train_transform_batch = partial(\n", + " augment_and_transform_batch, transform=train_augment_and_transform, image_processor=image_processor\n", + ")\n", + "validation_transform_batch = partial(\n", + " augment_and_transform_batch, transform=validation_transform, image_processor=image_processor\n", + ")\n", + "\n", + "cppe5[\"train\"] = cppe5[\"train\"].with_transform(train_transform_batch)\n", + "cppe5[\"validation\"] = cppe5[\"validation\"].with_transform(validation_transform_batch)\n", + "cppe5[\"test\"] = cppe5[\"test\"].with_transform(validation_transform_batch)\n", + "\n", + "cppe5[\"train\"][15]" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "6fU4KuKBjRC3" + }, + "source": [ + "You have successfully augmented the individual images and prepared their annotations. However, preprocessing isn't\n", + "complete yet. In the final step, create a custom `collate_fn` to batch images together.\n", + "Pad images (which are now `pixel_values`) to the largest image in a batch, and create a corresponding `pixel_mask`\n", + "to indicate which pixels are real (1) and which are padding (0)." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "id": "BePJFLoIjRC3" + }, + "outputs": [], + "source": [ + "import torch\n", + "\n", + "def collate_fn(batch):\n", + " data = {}\n", + " data[\"pixel_values\"] = torch.stack([x[\"pixel_values\"] for x in batch])\n", + " data[\"labels\"] = [x[\"labels\"] for x in batch]\n", + " if \"pixel_mask\" in batch[0]:\n", + " data[\"pixel_mask\"] = torch.stack([x[\"pixel_mask\"] for x in batch])\n", + " return data\n" + ] + }, + { + "cell_type": "markdown", + "source": [ + "## Preparing function to compute mAP" + ], + "metadata": { + "id": "xqy6XSavm5w6" + } + }, + { + "cell_type": "markdown", + "source": [ + "Object detection models are commonly evaluated with a set of [COCO-style](https://cocodataset.org/#detection-eval) metrics. We are going to use `torchmetrics` to compute `mAP` (mean average precision) and `mAR` (mean average recall) metrics and will wrap it to `compute_metrics` function in order to use in [Trainer](https://huggingface.co/docs/transformers/v4.44.2/en/main_classes/trainer#transformers.Trainer) for evaluation.\n", + "\n", + "Intermediate format of boxes used for training is YOLO (normalized) but we will compute metrics for boxes in `Pascal VOC` (absolute) format in order to correctly handle box areas. Let’s define a function that converts bounding boxes to `Pascal VOC` format:" + ], + "metadata": { + "id": "ar_FF5dOm8P_" + } + }, + { + "cell_type": "code", + "source": [ + "from transformers.image_transforms import center_to_corners_format\n", + "\n", + "def convert_bbox_yolo_to_pascal(boxes, image_size):\n", + " \"\"\"\n", + " Convert bounding boxes from YOLO format (x_center, y_center, width, height) in range [0, 1]\n", + " to Pascal VOC format (x_min, y_min, x_max, y_max) in absolute coordinates.\n", + "\n", + " Args:\n", + " boxes (torch.Tensor): Bounding boxes in YOLO format\n", + " image_size (Tuple[int, int]): Image size in format (height, width)\n", + "\n", + " Returns:\n", + " torch.Tensor: Bounding boxes in Pascal VOC format (x_min, y_min, x_max, y_max)\n", + " \"\"\"\n", + " # convert center to corners format\n", + " boxes = center_to_corners_format(boxes)\n", + "\n", + " # convert to absolute coordinates\n", + " height, width = image_size\n", + " boxes = boxes * torch.tensor([[width, height, width, height]])\n", + "\n", + " return boxes" + ], + "metadata": { + "id": "zjQcKfc5nNub" + }, + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "source": [ + "Then, in `compute_metrics` function we collect `predicted` and `target` bounding boxes, scores and labels from evaluation loop results and pass it to the scoring function.\n", + "\n" + ], + "metadata": { + "id": "0fCnOE7lnQEr" + } + }, + { + "cell_type": "code", + "source": [ + "import numpy as np\n", + "from dataclasses import dataclass\n", + "from torchmetrics.detection.mean_ap import MeanAveragePrecision\n", + "\n", + "\n", + "@dataclass\n", + "class ModelOutput:\n", + " logits: torch.Tensor\n", + " pred_boxes: torch.Tensor\n", + "\n", + "\n", + "@torch.no_grad()\n", + "def compute_metrics(evaluation_results, image_processor, threshold=0.0, id2label=None):\n", + " \"\"\"\n", + " Compute mean average mAP, mAR and their variants for the object detection task.\n", + "\n", + " Args:\n", + " evaluation_results (EvalPrediction): Predictions and targets from evaluation.\n", + " threshold (float, optional): Threshold to filter predicted boxes by confidence. Defaults to 0.0.\n", + " id2label (Optional[dict], optional): Mapping from class id to class name. Defaults to None.\n", + "\n", + " Returns:\n", + " Mapping[str, float]: Metrics in a form of dictionary {: }\n", + " \"\"\"\n", + "\n", + " predictions, targets = evaluation_results.predictions, evaluation_results.label_ids\n", + "\n", + " # For metric computation we need to provide:\n", + " # - targets in a form of list of dictionaries with keys \"boxes\", \"labels\"\n", + " # - predictions in a form of list of dictionaries with keys \"boxes\", \"scores\", \"labels\"\n", + "\n", + " image_sizes = []\n", + " post_processed_targets = []\n", + " post_processed_predictions = []\n", + "\n", + " # Collect targets in the required format for metric computation\n", + " for batch in targets:\n", + " # collect image sizes, we will need them for predictions post processing\n", + " batch_image_sizes = torch.tensor(np.array([x[\"orig_size\"] for x in batch]))\n", + " image_sizes.append(batch_image_sizes)\n", + " # collect targets in the required format for metric computation\n", + " # boxes were converted to YOLO format needed for model training\n", + " # here we will convert them to Pascal VOC format (x_min, y_min, x_max, y_max)\n", + " for image_target in batch:\n", + " boxes = torch.tensor(image_target[\"boxes\"])\n", + " boxes = convert_bbox_yolo_to_pascal(boxes, image_target[\"orig_size\"])\n", + " labels = torch.tensor(image_target[\"class_labels\"])\n", + " post_processed_targets.append({\"boxes\": boxes, \"labels\": labels})\n", + "\n", + " # Collect predictions in the required format for metric computation,\n", + " # model produce boxes in YOLO format, then image_processor convert them to Pascal VOC format\n", + " for batch, target_sizes in zip(predictions, image_sizes):\n", + " batch_logits, batch_boxes = batch[1], batch[2]\n", + " output = ModelOutput(logits=torch.tensor(batch_logits), pred_boxes=torch.tensor(batch_boxes))\n", + " post_processed_output = image_processor.post_process_object_detection(\n", + " output, threshold=threshold, target_sizes=target_sizes\n", + " )\n", + " post_processed_predictions.extend(post_processed_output)\n", + "\n", + " # Compute metrics\n", + " metric = MeanAveragePrecision(box_format=\"xyxy\", class_metrics=True)\n", + " metric.update(post_processed_predictions, post_processed_targets)\n", + " metrics = metric.compute()\n", + "\n", + " # Replace list of per class metrics with separate metric for each class\n", + " classes = metrics.pop(\"classes\")\n", + " map_per_class = metrics.pop(\"map_per_class\")\n", + " mar_100_per_class = metrics.pop(\"mar_100_per_class\")\n", + " for class_id, class_map, class_mar in zip(classes, map_per_class, mar_100_per_class):\n", + " class_name = id2label[class_id.item()] if id2label is not None else class_id.item()\n", + " metrics[f\"map_{class_name}\"] = class_map\n", + " metrics[f\"mar_100_{class_name}\"] = class_mar\n", + "\n", + " metrics = {k: round(v.item(), 4) for k, v in metrics.items()}\n", + "\n", + " return metrics\n", + "\n", + "\n", + "eval_compute_metrics_fn = partial(\n", + " compute_metrics, image_processor=image_processor, id2label=id2label, threshold=0.0\n", + ")" + ], + "metadata": { + "id": "CzwJvhGRnS3B" + }, + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "0UxzYsMnjRC4" + }, + "source": [ + "## Training the detection model" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "_l19Rj6DjRC4" + }, + "source": [ + "You have done most of the heavy lifting in the previous sections, so now you are ready to train your model!\n", + "The images in this dataset are still quite large, even after resizing. This means that finetuning this model will\n", + "require at least one GPU.\n", + "\n", + "Training involves the following steps:\n", + "1. Load the model with [AutoModelForObjectDetection](https://huggingface.co/docs/transformers/main/en/model_doc/auto#transformers.AutoModelForObjectDetection) using the same checkpoint as in the preprocessing.\n", + "2. Define your training hyperparameters in [TrainingArguments](https://huggingface.co/docs/transformers/main/en/main_classes/trainer#transformers.TrainingArguments).\n", + "3. Pass the training arguments to [Trainer](https://huggingface.co/docs/transformers/main/en/main_classes/trainer#transformers.Trainer) along with the model, dataset, image processor, and data collator.\n", + "4. Call [train()](https://huggingface.co/docs/transformers/main/en/main_classes/trainer#transformers.Trainer.train) to finetune your model.\n", + "\n", + "When loading the model from the same checkpoint that you used for the preprocessing, remember to pass the `label2id`\n", + "and `id2label` maps that you created earlier from the dataset's metadata. Additionally, we specify `ignore_mismatched_sizes=True` to replace the existing classification head with a new one." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "id": "oltzA-rFjRC4" + }, + "outputs": [], + "source": [ + "from transformers import AutoModelForObjectDetection\n", + "\n", + "model = AutoModelForObjectDetection.from_pretrained(\n", + " MODEL_NAME,\n", + " id2label=id2label,\n", + " label2id=label2id,\n", + " ignore_mismatched_sizes=True,\n", + ")" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "Qxizsg6DjRC4" + }, + "source": [ + "In the [TrainingArguments](https://huggingface.co/docs/transformers/v4.44.2/en/main_classes/trainer#transformers.TrainingArguments) use `output_dir` to specify where to save your model, then configure hyperparameters as you see fit. For `num_train_epochs=30` training will take about 35 minutes in Google Colab T4 GPU, increase the number of epoch to get better results.\n", + "\n", + "Important notes:\n", + "\n", + "* Do not remove unused columns because this will drop the image column. Without the image column, you can’t create pixel_values. For this reason, set `remove_unused_columns` to False.\n", + "* Set `eval_do_concat_batches=False` to get proper evaluation results. Images have different number of target boxes, if batches are concatenated we will not be able to determine which boxes belongs to particular image.\n", + "\n", + "If you wish to share your model by pushing to the Hub, set `push_to_hub` to `True` (you must be signed in to Hugging Face to upload your model)." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "id": "Pxo6N6mRjRC4" + }, + "outputs": [], + "source": [ + "from transformers import TrainingArguments\n", + "\n", + "training_args = TrainingArguments(\n", + " output_dir=\"detr_finetuned_cppe5\",\n", + " num_train_epochs=30,\n", + " fp16=False,\n", + " per_device_train_batch_size=8,\n", + " dataloader_num_workers=4,\n", + " learning_rate=5e-5,\n", + " lr_scheduler_type=\"cosine\",\n", + " weight_decay=1e-4,\n", + " max_grad_norm=0.01,\n", + " metric_for_best_model=\"eval_map\",\n", + " greater_is_better=True,\n", + " load_best_model_at_end=True,\n", + " eval_strategy=\"epoch\",\n", + " save_strategy=\"epoch\",\n", + " save_total_limit=2,\n", + " remove_unused_columns=False,\n", + " eval_do_concat_batches=False,\n", + " push_to_hub=True,\n", + ")" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "6x5DqV79jRC5" + }, + "source": [ + "Finally, bring everything together, and call [train()](https://huggingface.co/docs/transformers/main/en/main_classes/trainer#transformers.Trainer.train):" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "id": "xh288Qz_jRC5" + }, + "outputs": [], + "source": [ + "from transformers import Trainer\n", + "\n", + "trainer = Trainer(\n", + " model=model,\n", + " args=training_args,\n", + " train_dataset=cppe5[\"train\"],\n", + " eval_dataset=cppe5[\"validation\"],\n", + " tokenizer=image_processor,\n", + " data_collator=collate_fn,\n", + " compute_metrics=eval_compute_metrics_fn,\n", + ")\n", + "\n", + "trainer.train()" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "y-EBN0HpjRC6" + }, + "source": [ + "If you have set `push_to_hub` to `True` in the `training_args`, the training checkpoints are pushed to the\n", + "Hugging Face Hub. Upon training completion, push the final model to the Hub as well by calling the [push_to_hub()](https://huggingface.co/docs/transformers/main/en/main_classes/trainer#transformers.Trainer.push_to_hub) method." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "id": "9P8AhLUBjRC6" + }, + "outputs": [], + "source": [ + "trainer.push_to_hub()" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "iqHN9RJvjRC6" + }, + "source": [ + "## Evaluate" + ] + }, + { + "cell_type": "code", + "source": [ + "from pprint import pprint\n", + "\n", + "metrics = trainer.evaluate(eval_dataset=cppe5[\"test\"], metric_key_prefix=\"test\")\n", + "pprint(metrics)" + ], + "metadata": { + "id": "maTIoC5ln4CE" + }, + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "source": [ + "These results can be further improved by adjusting the hyperparameters in [TrainingArguments](https://huggingface.co/docs/transformers/v4.44.2/en/main_classes/trainer#transformers.TrainingArguments). Give it a go!\n", + "\n" + ], + "metadata": { + "id": "sjbRpIFqn5rt" + } + }, + { + "cell_type": "markdown", + "source": [ + "## Inference" + ], + "metadata": { + "id": "yfZ59nikn9kv" + } + }, + { + "cell_type": "markdown", + "source": [ + "Now that you have finetuned a model, evaluated it, and uploaded it to the Hugging Face Hub, you can use it for inference.\n", + "\n" + ], + "metadata": { + "id": "HCa_YwdkoA00" + } + }, + { + "cell_type": "code", + "source": [ + "import torch\n", + "import requests\n", + "\n", + "from PIL import Image, ImageDraw\n", + "from transformers import AutoImageProcessor, AutoModelForObjectDetection\n", + "\n", + "url = \"https://images.pexels.com/photos/8413299/pexels-photo-8413299.jpeg?auto=compress&cs=tinysrgb&w=630&h=375&dpr=2\"\n", + "image = Image.open(requests.get(url, stream=True).raw)" + ], + "metadata": { + "id": "nYEc4L50n-mW" + }, + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "source": [ + "Load model and image processor from the Hugging Face Hub (skip to use already trained in this session):\n", + "\n" + ], + "metadata": { + "id": "qrWYfmu0oDnz" + } + }, + { + "cell_type": "code", + "source": [ + "device = \"cuda\"\n", + "model_repo = \"qubvel-hf/detr_finetuned_cppe5\"\n", + "\n", + "image_processor = AutoImageProcessor.from_pretrained(model_repo)\n", + "model = AutoModelForObjectDetection.from_pretrained(model_repo)\n", + "model = model.to(device)" + ], + "metadata": { + "id": "OmwZ-ltzoFSq" + }, + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "source": [ + "And detect bounding boxes:\n", + "\n" + ], + "metadata": { + "id": "DptFENNOoGoG" + } + }, + { + "cell_type": "code", + "source": [ + "with torch.no_grad():\n", + " inputs = image_processor(images=[image], return_tensors=\"pt\")\n", + " outputs = model(**inputs.to(device))\n", + " target_sizes = torch.tensor([[image.size[1], image.size[0]]])\n", + " results = image_processor.post_process_object_detection(outputs, threshold=0.3, target_sizes=target_sizes)[0]\n", + "\n", + "for score, label, box in zip(results[\"scores\"], results[\"labels\"], results[\"boxes\"]):\n", + " box = [round(i, 2) for i in box.tolist()]\n", + " print(\n", + " f\"Detected {model.config.id2label[label.item()]} with confidence \"\n", + " f\"{round(score.item(), 3)} at location {box}\"\n", + " )" + ], + "metadata": { + "id": "YlFWNFRxoHDI" + }, + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "source": [ + "Let’s plot the result:\n", + "\n" + ], + "metadata": { + "id": "j_m35fRzoJmV" + } + }, + { + "cell_type": "code", + "source": [ + "draw = ImageDraw.Draw(image)\n", + "\n", + "for score, label, box in zip(results[\"scores\"], results[\"labels\"], results[\"boxes\"]):\n", + " box = [round(i, 2) for i in box.tolist()]\n", + " x, y, x2, y2 = tuple(box)\n", + " draw.rectangle((x, y, x2, y2), outline=\"red\", width=1)\n", + " draw.text((x, y), model.config.id2label[label.item()], fill=\"white\")\n", + "\n", + "image" + ], + "metadata": { + "id": "ZuLuGKl2oJ9X" + }, + "execution_count": null, + "outputs": [] } - ], - "source": [ - "image_processor = AutoImageProcessor.from_pretrained(\"MariaK/detr-resnet-50_finetuned_cppe5\")\n", - "model = AutoModelForObjectDetection.from_pretrained(\"MariaK/detr-resnet-50_finetuned_cppe5\")\n", - "\n", - "with torch.no_grad():\n", - " inputs = image_processor(images=image, return_tensors=\"pt\")\n", - " outputs = model(**inputs)\n", - " target_sizes = torch.tensor([image.size[::-1]])\n", - " results = image_processor.post_process_object_detection(outputs, threshold=0.5, target_sizes=target_sizes)[0]\n", - "\n", - "for score, label, box in zip(results[\"scores\"], results[\"labels\"], results[\"boxes\"]):\n", - " box = [round(i, 2) for i in box.tolist()]\n", - " print(\n", - " f\"Detected {model.config.id2label[label.item()]} with confidence \"\n", - " f\"{round(score.item(), 3)} at location {box}\"\n", - " )" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Let's plot the result:" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "draw = ImageDraw.Draw(image)\n", - "\n", - "for score, label, box in zip(results[\"scores\"], results[\"labels\"], results[\"boxes\"]):\n", - " box = [round(i, 2) for i in box.tolist()]\n", - " x, y, x2, y2 = tuple(box)\n", - " draw.rectangle((x, y, x2, y2), outline=\"red\", width=1)\n", - " draw.text((x, y), model.config.id2label[label.item()], fill=\"white\")\n", - "\n", - "image" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "
\n", - " \"Object\n", - "
" - ] - } - ], - "metadata": {}, - "nbformat": 4, - "nbformat_minor": 4 -} + ], + "metadata": { + "colab": { + "provenance": [], + "toc_visible": true, + "gpuType": "T4" + }, + "language_info": { + "name": "python" + }, + "kernelspec": { + "name": "python3", + "display_name": "Python 3" + }, + "accelerator": "GPU" + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/transformers_doc/en/tensorflow/object_detection.ipynb b/transformers_doc/en/tensorflow/object_detection.ipynb index 934b1a96..ad3ba3cd 100644 --- a/transformers_doc/en/tensorflow/object_detection.ipynb +++ b/transformers_doc/en/tensorflow/object_detection.ipynb @@ -1,900 +1,977 @@ { - "cells": [ - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "# Transformers installation\n", - "! pip install transformers datasets\n", - "# To install from source instead of the last release, comment the command above and uncomment the following one.\n", - "# ! pip install git+https://github.com/huggingface/transformers.git" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "# Object detection" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Object detection is the computer vision task of detecting instances (such as humans, buildings, or cars) in an image. Object detection models receive an image as input and output\n", - "coordinates of the bounding boxes and associated labels of the detected objects. An image can contain multiple objects,\n", - "each with its own bounding box and a label (e.g. it can have a car and a building), and each object can\n", - "be present in different parts of an image (e.g. the image can have several cars).\n", - "This task is commonly used in autonomous driving for detecting things like pedestrians, road signs, and traffic lights.\n", - "Other applications include counting objects in images, image search, and more.\n", - "\n", - "In this guide, you will learn how to:\n", - "\n", - " 1. Finetune [DETR](https://huggingface.co/docs/transformers/model_doc/detr), a model that combines a convolutional\n", - " backbone with an encoder-decoder Transformer, on the [CPPE-5](https://huggingface.co/datasets/cppe-5)\n", - " dataset.\n", - " 2. Use your finetuned model for inference.\n", - "\n", - "\n", - "The task illustrated in this tutorial is supported by the following model architectures:\n", - "\n", - "\n", - "\n", - "[Conditional DETR](https://huggingface.co/docs/transformers/main/en/tasks/../model_doc/conditional_detr), [Deformable DETR](https://huggingface.co/docs/transformers/main/en/tasks/../model_doc/deformable_detr), [DETA](https://huggingface.co/docs/transformers/main/en/tasks/../model_doc/deta), [DETR](https://huggingface.co/docs/transformers/main/en/tasks/../model_doc/detr), [Table Transformer](https://huggingface.co/docs/transformers/main/en/tasks/../model_doc/table-transformer), [YOLOS](https://huggingface.co/docs/transformers/main/en/tasks/../model_doc/yolos)\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "Before you begin, make sure you have all the necessary libraries installed:\n", - "\n", - "```bash\n", - "pip install -q datasets transformers evaluate timm albumentations\n", - "```\n", - "\n", - "You'll use 🤗 Datasets to load a dataset from the Hugging Face Hub, 🤗 Transformers to train your model,\n", - "and `albumentations` to augment the data. `timm` is currently required to load a convolutional backbone for the DETR model.\n", - "\n", - "We encourage you to share your model with the community. Log in to your Hugging Face account to upload it to the Hub.\n", - "When prompted, enter your token to log in:" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "from huggingface_hub import notebook_login\n", - "\n", - "notebook_login()" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Load the CPPE-5 dataset" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "The [CPPE-5 dataset](https://huggingface.co/datasets/cppe-5) contains images with\n", - "annotations identifying medical personal protective equipment (PPE) in the context of the COVID-19 pandemic.\n", - "\n", - "Start by loading the dataset:" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "DatasetDict({\n", - " train: Dataset({\n", - " features: ['image_id', 'image', 'width', 'height', 'objects'],\n", - " num_rows: 1000\n", - " })\n", - " test: Dataset({\n", - " features: ['image_id', 'image', 'width', 'height', 'objects'],\n", - " num_rows: 29\n", - " })\n", - "})" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "from datasets import load_dataset\n", - "\n", - "cppe5 = load_dataset(\"cppe-5\")\n", - "cppe5" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "You'll see that this dataset already comes with a training set containing 1000 images and a test set with 29 images.\n", - "\n", - "To get familiar with the data, explore what the examples look like." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "{'image_id': 15,\n", - " 'image': ,\n", - " 'width': 943,\n", - " 'height': 663,\n", - " 'objects': {'id': [114, 115, 116, 117],\n", - " 'area': [3796, 1596, 152768, 81002],\n", - " 'bbox': [[302.0, 109.0, 73.0, 52.0],\n", - " [810.0, 100.0, 57.0, 28.0],\n", - " [160.0, 31.0, 248.0, 616.0],\n", - " [741.0, 68.0, 202.0, 401.0]],\n", - " 'category': [4, 4, 0, 0]}}" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "cppe5[\"train\"][0]" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "The examples in the dataset have the following fields:\n", - "- `image_id`: the example image id\n", - "- `image`: a `PIL.Image.Image` object containing the image\n", - "- `width`: width of the image\n", - "- `height`: height of the image\n", - "- `objects`: a dictionary containing bounding box metadata for the objects in the image:\n", - " - `id`: the annotation id\n", - " - `area`: the area of the bounding box\n", - " - `bbox`: the object's bounding box (in the [COCO format](https://albumentations.ai/docs/getting_started/bounding_boxes_augmentation/#coco) )\n", - " - `category`: the object's category, with possible values including `Coverall (0)`, `Face_Shield (1)`, `Gloves (2)`, `Goggles (3)` and `Mask (4)`\n", - "\n", - "You may notice that the `bbox` field follows the COCO format, which is the format that the DETR model expects.\n", - "However, the grouping of the fields inside `objects` differs from the annotation format DETR requires. You will\n", - "need to apply some preprocessing transformations before using this data for training.\n", - "\n", - "To get an even better understanding of the data, visualize an example in the dataset." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "import numpy as np\n", - "import os\n", - "from PIL import Image, ImageDraw\n", - "\n", - "image = cppe5[\"train\"][0][\"image\"]\n", - "annotations = cppe5[\"train\"][0][\"objects\"]\n", - "draw = ImageDraw.Draw(image)\n", - "\n", - "categories = cppe5[\"train\"].features[\"objects\"].feature[\"category\"].names\n", - "\n", - "id2label = {index: x for index, x in enumerate(categories, start=0)}\n", - "label2id = {v: k for k, v in id2label.items()}\n", - "\n", - "for i in range(len(annotations[\"id\"])):\n", - " box = annotations[\"bbox\"][i - 1]\n", - " class_idx = annotations[\"category\"][i - 1]\n", - " x, y, w, h = tuple(box)\n", - " draw.rectangle((x, y, x + w, y + h), outline=\"red\", width=1)\n", - " draw.text((x, y), id2label[class_idx], fill=\"white\")\n", - "\n", - "image" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "
\n", - " \"CPPE-5\n", - "
\n", - "\n", - "To visualize the bounding boxes with associated labels, you can get the labels from the dataset's metadata, specifically\n", - "the `category` field.\n", - "You'll also want to create dictionaries that map a label id to a label class (`id2label`) and the other way around (`label2id`).\n", - "You can use them later when setting up the model. Including these maps will make your model reusable by others if you share\n", - "it on the Hugging Face Hub.\n", - "\n", - "As a final step of getting familiar with the data, explore it for potential issues. One common problem with datasets for\n", - "object detection is bounding boxes that \"stretch\" beyond the edge of the image. Such \"runaway\" bounding boxes can raise\n", - "errors during training and should be addressed at this stage. There are a few examples with this issue in this dataset.\n", - "To keep things simple in this guide, we remove these images from the data." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "remove_idx = [590, 821, 822, 875, 876, 878, 879]\n", - "keep = [i for i in range(len(cppe5[\"train\"])) if i not in remove_idx]\n", - "cppe5[\"train\"] = cppe5[\"train\"].select(keep)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Preprocess the data" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "To finetune a model, you must preprocess the data you plan to use to match precisely the approach used for the pre-trained model.\n", - "[AutoImageProcessor](https://huggingface.co/docs/transformers/main/en/model_doc/auto#transformers.AutoImageProcessor) takes care of processing image data to create `pixel_values`, `pixel_mask`, and\n", - "`labels` that a DETR model can train with. The image processor has some attributes that you won't have to worry about:\n", - "\n", - "- `image_mean = [0.485, 0.456, 0.406 ]`\n", - "- `image_std = [0.229, 0.224, 0.225]`\n", - "\n", - "These are the mean and standard deviation used to normalize images during the model pre-training. These values are crucial\n", - "to replicate when doing inference or finetuning a pre-trained image model.\n", - "\n", - "Instantiate the image processor from the same checkpoint as the model you want to finetune." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "from transformers import AutoImageProcessor\n", - "\n", - "checkpoint = \"facebook/detr-resnet-50\"\n", - "image_processor = AutoImageProcessor.from_pretrained(checkpoint)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Before passing the images to the `image_processor`, apply two preprocessing transformations to the dataset:\n", - "- Augmenting images\n", - "- Reformatting annotations to meet DETR expectations\n", - "\n", - "First, to make sure the model does not overfit on the training data, you can apply image augmentation with any data augmentation library. Here we use [Albumentations](https://albumentations.ai/docs/) ...\n", - "This library ensures that transformations affect the image and update the bounding boxes accordingly.\n", - "The 🤗 Datasets library documentation has a detailed [guide on how to augment images for object detection](https://huggingface.co/docs/datasets/object_detection),\n", - "and it uses the exact same dataset as an example. Apply the same approach here, resize each image to (480, 480),\n", - "flip it horizontally, and brighten it:" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "import albumentations\n", - "import numpy as np\n", - "import torch\n", - "\n", - "transform = albumentations.Compose(\n", - " [\n", - " albumentations.Resize(480, 480),\n", - " albumentations.HorizontalFlip(p=1.0),\n", - " albumentations.RandomBrightnessContrast(p=1.0),\n", - " ],\n", - " bbox_params=albumentations.BboxParams(format=\"coco\", label_fields=[\"category\"]),\n", - ")" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "The `image_processor` expects the annotations to be in the following format: `{'image_id': int, 'annotations': List[Dict]}`,\n", - " where each dictionary is a COCO object annotation. Let's add a function to reformat annotations for a single example:" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "def formatted_anns(image_id, category, area, bbox):\n", - " annotations = []\n", - " for i in range(0, len(category)):\n", - " new_ann = {\n", - " \"image_id\": image_id,\n", - " \"category_id\": category[i],\n", - " \"isCrowd\": 0,\n", - " \"area\": area[i],\n", - " \"bbox\": list(bbox[i]),\n", - " }\n", - " annotations.append(new_ann)\n", - "\n", - " return annotations" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Now you can combine the image and annotation transformations to use on a batch of examples:" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "# transforming a batch\n", - "def transform_aug_ann(examples):\n", - " image_ids = examples[\"image_id\"]\n", - " images, bboxes, area, categories = [], [], [], []\n", - " for image, objects in zip(examples[\"image\"], examples[\"objects\"]):\n", - " image = np.array(image.convert(\"RGB\"))[:, :, ::-1]\n", - " out = transform(image=image, bboxes=objects[\"bbox\"], category=objects[\"category\"])\n", - "\n", - " area.append(objects[\"area\"])\n", - " images.append(out[\"image\"])\n", - " bboxes.append(out[\"bboxes\"])\n", - " categories.append(out[\"category\"])\n", - "\n", - " targets = [\n", - " {\"image_id\": id_, \"annotations\": formatted_anns(id_, cat_, ar_, box_)}\n", - " for id_, cat_, ar_, box_ in zip(image_ids, categories, area, bboxes)\n", - " ]\n", - "\n", - " return image_processor(images=images, annotations=targets, return_tensors=\"pt\")" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Apply this preprocessing function to the entire dataset using 🤗 Datasets [with_transform](https://huggingface.co/docs/datasets/main/en/package_reference/main_classes#datasets.Dataset.with_transform) method. This method applies\n", - "transformations on the fly when you load an element of the dataset.\n", - "\n", - "At this point, you can check what an example from the dataset looks like after the transformations. You should see a tensor\n", - "with `pixel_values`, a tensor with `pixel_mask`, and `labels`." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "{'pixel_values': tensor([[[ 0.9132, 0.9132, 0.9132, ..., -1.9809, -1.9809, -1.9809],\n", - " [ 0.9132, 0.9132, 0.9132, ..., -1.9809, -1.9809, -1.9809],\n", - " [ 0.9132, 0.9132, 0.9132, ..., -1.9638, -1.9638, -1.9638],\n", - " ...,\n", - " [-1.5699, -1.5699, -1.5699, ..., -1.9980, -1.9980, -1.9980],\n", - " [-1.5528, -1.5528, -1.5528, ..., -1.9980, -1.9809, -1.9809],\n", - " [-1.5528, -1.5528, -1.5528, ..., -1.9980, -1.9809, -1.9809]],\n", - "\n", - " [[ 1.3081, 1.3081, 1.3081, ..., -1.8431, -1.8431, -1.8431],\n", - " [ 1.3081, 1.3081, 1.3081, ..., -1.8431, -1.8431, -1.8431],\n", - " [ 1.3081, 1.3081, 1.3081, ..., -1.8256, -1.8256, -1.8256],\n", - " ...,\n", - " [-1.3179, -1.3179, -1.3179, ..., -1.8606, -1.8606, -1.8606],\n", - " [-1.3004, -1.3004, -1.3004, ..., -1.8606, -1.8431, -1.8431],\n", - " [-1.3004, -1.3004, -1.3004, ..., -1.8606, -1.8431, -1.8431]],\n", - "\n", - " [[ 1.4200, 1.4200, 1.4200, ..., -1.6476, -1.6476, -1.6476],\n", - " [ 1.4200, 1.4200, 1.4200, ..., -1.6476, -1.6476, -1.6476],\n", - " [ 1.4200, 1.4200, 1.4200, ..., -1.6302, -1.6302, -1.6302],\n", - " ...,\n", - " [-1.0201, -1.0201, -1.0201, ..., -1.5604, -1.5604, -1.5604],\n", - " [-1.0027, -1.0027, -1.0027, ..., -1.5604, -1.5430, -1.5430],\n", - " [-1.0027, -1.0027, -1.0027, ..., -1.5604, -1.5430, -1.5430]]]),\n", - " 'pixel_mask': tensor([[1, 1, 1, ..., 1, 1, 1],\n", - " [1, 1, 1, ..., 1, 1, 1],\n", - " [1, 1, 1, ..., 1, 1, 1],\n", - " ...,\n", - " [1, 1, 1, ..., 1, 1, 1],\n", - " [1, 1, 1, ..., 1, 1, 1],\n", - " [1, 1, 1, ..., 1, 1, 1]]),\n", - " 'labels': {'size': tensor([800, 800]), 'image_id': tensor([756]), 'class_labels': tensor([4]), 'boxes': tensor([[0.7340, 0.6986, 0.3414, 0.5944]]), 'area': tensor([519544.4375]), 'iscrowd': tensor([0]), 'orig_size': tensor([480, 480])}}" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "cppe5[\"train\"] = cppe5[\"train\"].with_transform(transform_aug_ann)\n", - "cppe5[\"train\"][15]" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "You have successfully augmented the individual images and prepared their annotations. However, preprocessing isn't\n", - "complete yet. In the final step, create a custom `collate_fn` to batch images together.\n", - "Pad images (which are now `pixel_values`) to the largest image in a batch, and create a corresponding `pixel_mask`\n", - "to indicate which pixels are real (1) and which are padding (0)." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "def collate_fn(batch):\n", - " pixel_values = [item[\"pixel_values\"] for item in batch]\n", - " encoding = image_processor.pad_and_create_pixel_mask(pixel_values, return_tensors=\"pt\")\n", - " labels = [item[\"labels\"] for item in batch]\n", - " batch = {}\n", - " batch[\"pixel_values\"] = encoding[\"pixel_values\"]\n", - " batch[\"pixel_mask\"] = encoding[\"pixel_mask\"]\n", - " batch[\"labels\"] = labels\n", - " return batch" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Training the DETR model" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "You have done most of the heavy lifting in the previous sections, so now you are ready to train your model!\n", - "The images in this dataset are still quite large, even after resizing. This means that finetuning this model will\n", - "require at least one GPU.\n", - "\n", - "Training involves the following steps:\n", - "1. Load the model with [AutoModelForObjectDetection](https://huggingface.co/docs/transformers/main/en/model_doc/auto#transformers.AutoModelForObjectDetection) using the same checkpoint as in the preprocessing.\n", - "2. Define your training hyperparameters in [TrainingArguments](https://huggingface.co/docs/transformers/main/en/main_classes/trainer#transformers.TrainingArguments).\n", - "3. Pass the training arguments to [Trainer](https://huggingface.co/docs/transformers/main/en/main_classes/trainer#transformers.Trainer) along with the model, dataset, image processor, and data collator.\n", - "4. Call [train()](https://huggingface.co/docs/transformers/main/en/main_classes/trainer#transformers.Trainer.train) to finetune your model.\n", - "\n", - "When loading the model from the same checkpoint that you used for the preprocessing, remember to pass the `label2id`\n", - "and `id2label` maps that you created earlier from the dataset's metadata. Additionally, we specify `ignore_mismatched_sizes=True` to replace the existing classification head with a new one." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "from transformers import AutoModelForObjectDetection\n", - "\n", - "model = AutoModelForObjectDetection.from_pretrained(\n", - " checkpoint,\n", - " id2label=id2label,\n", - " label2id=label2id,\n", - " ignore_mismatched_sizes=True,\n", - ")" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "In the [TrainingArguments](https://huggingface.co/docs/transformers/main/en/main_classes/trainer#transformers.TrainingArguments) use `output_dir` to specify where to save your model, then configure hyperparameters as you see fit.\n", - "It is important you do not remove unused columns because this will drop the image column. Without the image column, you\n", - "can't create `pixel_values`. For this reason, set `remove_unused_columns` to `False`.\n", - "If you wish to share your model by pushing to the Hub, set `push_to_hub` to `True` (you must be signed in to Hugging\n", - "Face to upload your model)." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "from transformers import TrainingArguments\n", - "\n", - "training_args = TrainingArguments(\n", - " output_dir=\"detr-resnet-50_finetuned_cppe5\",\n", - " per_device_train_batch_size=8,\n", - " num_train_epochs=10,\n", - " fp16=True,\n", - " save_steps=200,\n", - " logging_steps=50,\n", - " learning_rate=1e-5,\n", - " weight_decay=1e-4,\n", - " save_total_limit=2,\n", - " remove_unused_columns=False,\n", - " push_to_hub=True,\n", - ")" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Finally, bring everything together, and call [train()](https://huggingface.co/docs/transformers/main/en/main_classes/trainer#transformers.Trainer.train):" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "from transformers import Trainer\n", - "\n", - "trainer = Trainer(\n", - " model=model,\n", - " args=training_args,\n", - " data_collator=collate_fn,\n", - " train_dataset=cppe5[\"train\"],\n", - " tokenizer=image_processor,\n", - ")\n", - "\n", - "trainer.train()" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "If you have set `push_to_hub` to `True` in the `training_args`, the training checkpoints are pushed to the\n", - "Hugging Face Hub. Upon training completion, push the final model to the Hub as well by calling the [push_to_hub()](https://huggingface.co/docs/transformers/main/en/main_classes/trainer#transformers.Trainer.push_to_hub) method." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "trainer.push_to_hub()" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Evaluate" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Object detection models are commonly evaluated with a set of COCO-style metrics.\n", - "You can use one of the existing metrics implementations, but here you'll use the one from `torchvision` to evaluate the final\n", - "model that you pushed to the Hub.\n", - "\n", - "To use the `torchvision` evaluator, you'll need to prepare a ground truth COCO dataset. The API to build a COCO dataset\n", - "requires the data to be stored in a certain format, so you'll need to save images and annotations to disk first. Just like\n", - "when you prepared your data for training, the annotations from the `cppe5[\"test\"]` need to be formatted. However, images\n", - "should stay as they are.\n", - "\n", - "The evaluation step requires a bit of work, but it can be split in three major steps.\n", - "First, prepare the `cppe5[\"test\"]` set: format the annotations and save the data to disk." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "import json\n", - "\n", - "\n", - "# format annotations the same as for training, no need for data augmentation\n", - "def val_formatted_anns(image_id, objects):\n", - " annotations = []\n", - " for i in range(0, len(objects[\"id\"])):\n", - " new_ann = {\n", - " \"id\": objects[\"id\"][i],\n", - " \"category_id\": objects[\"category\"][i],\n", - " \"iscrowd\": 0,\n", - " \"image_id\": image_id,\n", - " \"area\": objects[\"area\"][i],\n", - " \"bbox\": objects[\"bbox\"][i],\n", - " }\n", - " annotations.append(new_ann)\n", - "\n", - " return annotations\n", - "\n", - "\n", - "# Save images and annotations into the files torchvision.datasets.CocoDetection expects\n", - "def save_cppe5_annotation_file_images(cppe5):\n", - " output_json = {}\n", - " path_output_cppe5 = f\"{os.getcwd()}/cppe5/\"\n", - "\n", - " if not os.path.exists(path_output_cppe5):\n", - " os.makedirs(path_output_cppe5)\n", - "\n", - " path_anno = os.path.join(path_output_cppe5, \"cppe5_ann.json\")\n", - " categories_json = [{\"supercategory\": \"none\", \"id\": id, \"name\": id2label[id]} for id in id2label]\n", - " output_json[\"images\"] = []\n", - " output_json[\"annotations\"] = []\n", - " for example in cppe5:\n", - " ann = val_formatted_anns(example[\"image_id\"], example[\"objects\"])\n", - " output_json[\"images\"].append(\n", - " {\n", - " \"id\": example[\"image_id\"],\n", - " \"width\": example[\"image\"].width,\n", - " \"height\": example[\"image\"].height,\n", - " \"file_name\": f\"{example['image_id']}.png\",\n", - " }\n", - " )\n", - " output_json[\"annotations\"].extend(ann)\n", - " output_json[\"categories\"] = categories_json\n", - "\n", - " with open(path_anno, \"w\") as file:\n", - " json.dump(output_json, file, ensure_ascii=False, indent=4)\n", - "\n", - " for im, img_id in zip(cppe5[\"image\"], cppe5[\"image_id\"]):\n", - " path_img = os.path.join(path_output_cppe5, f\"{img_id}.png\")\n", - " im.save(path_img)\n", - "\n", - " return path_output_cppe5, path_anno" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Next, prepare an instance of a `CocoDetection` class that can be used with `cocoevaluator`." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "import torchvision\n", - "\n", - "\n", - "class CocoDetection(torchvision.datasets.CocoDetection):\n", - " def __init__(self, img_folder, feature_extractor, ann_file):\n", - " super().__init__(img_folder, ann_file)\n", - " self.feature_extractor = feature_extractor\n", - "\n", - " def __getitem__(self, idx):\n", - " # read in PIL image and target in COCO format\n", - " img, target = super(CocoDetection, self).__getitem__(idx)\n", - "\n", - " # preprocess image and target: converting target to DETR format,\n", - " # resizing + normalization of both image and target)\n", - " image_id = self.ids[idx]\n", - " target = {\"image_id\": image_id, \"annotations\": target}\n", - " encoding = self.feature_extractor(images=img, annotations=target, return_tensors=\"pt\")\n", - " pixel_values = encoding[\"pixel_values\"].squeeze() # remove batch dimension\n", - " target = encoding[\"labels\"][0] # remove batch dimension\n", - "\n", - " return {\"pixel_values\": pixel_values, \"labels\": target}\n", - "\n", - "\n", - "im_processor = AutoImageProcessor.from_pretrained(\"MariaK/detr-resnet-50_finetuned_cppe5\")\n", - "\n", - "path_output_cppe5, path_anno = save_cppe5_annotation_file_images(cppe5[\"test\"])\n", - "test_ds_coco_format = CocoDetection(path_output_cppe5, im_processor, path_anno)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Finally, load the metrics and run the evaluation." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "Accumulating evaluation results...\n", - "DONE (t=0.08s).\n", - "IoU metric: bbox\n", - " Average Precision (AP) @[ IoU=0.50:0.95 | area= all | maxDets=100 ] = 0.150\n", - " Average Precision (AP) @[ IoU=0.50 | area= all | maxDets=100 ] = 0.280\n", - " Average Precision (AP) @[ IoU=0.75 | area= all | maxDets=100 ] = 0.130\n", - " Average Precision (AP) @[ IoU=0.50:0.95 | area= small | maxDets=100 ] = 0.038\n", - " Average Precision (AP) @[ IoU=0.50:0.95 | area=medium | maxDets=100 ] = 0.036\n", - " Average Precision (AP) @[ IoU=0.50:0.95 | area= large | maxDets=100 ] = 0.182\n", - " Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets= 1 ] = 0.166\n", - " Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets= 10 ] = 0.317\n", - " Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets=100 ] = 0.335\n", - " Average Recall (AR) @[ IoU=0.50:0.95 | area= small | maxDets=100 ] = 0.104\n", - " Average Recall (AR) @[ IoU=0.50:0.95 | area=medium | maxDets=100 ] = 0.146\n", - " Average Recall (AR) @[ IoU=0.50:0.95 | area= large | maxDets=100 ] = 0.382" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "import evaluate\n", - "from tqdm import tqdm\n", - "\n", - "model = AutoModelForObjectDetection.from_pretrained(\"MariaK/detr-resnet-50_finetuned_cppe5\")\n", - "module = evaluate.load(\"ybelkada/cocoevaluate\", coco=test_ds_coco_format.coco)\n", - "val_dataloader = torch.utils.data.DataLoader(\n", - " test_ds_coco_format, batch_size=8, shuffle=False, num_workers=4, collate_fn=collate_fn\n", - ")\n", - "\n", - "with torch.no_grad():\n", - " for idx, batch in enumerate(tqdm(val_dataloader)):\n", - " pixel_values = batch[\"pixel_values\"]\n", - " pixel_mask = batch[\"pixel_mask\"]\n", - "\n", - " labels = [\n", - " {k: v for k, v in t.items()} for t in batch[\"labels\"]\n", - " ] # these are in DETR format, resized + normalized\n", - "\n", - " # forward pass\n", - " outputs = model(pixel_values=pixel_values, pixel_mask=pixel_mask)\n", - "\n", - " orig_target_sizes = torch.stack([target[\"orig_size\"] for target in labels], dim=0)\n", - " results = im_processor.post_process(outputs, orig_target_sizes) # convert outputs of model to COCO api\n", - "\n", - " module.add(prediction=results, reference=labels)\n", - " del batch\n", - "\n", - "results = module.compute()\n", - "print(results)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "These results can be further improved by adjusting the hyperparameters in [TrainingArguments](https://huggingface.co/docs/transformers/main/en/main_classes/trainer#transformers.TrainingArguments). Give it a go!" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Inference" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Now that you have finetuned a DETR model, evaluated it, and uploaded it to the Hugging Face Hub, you can use it for inference.\n", - "The simplest way to try out your finetuned model for inference is to use it in a [Pipeline](https://huggingface.co/docs/transformers/main/en/main_classes/pipelines#transformers.Pipeline). Instantiate a pipeline\n", - "for object detection with your model, and pass an image to it:" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "from transformers import pipeline\n", - "import requests\n", - "\n", - "url = \"https://i.imgur.com/2lnWoly.jpg\"\n", - "image = Image.open(requests.get(url, stream=True).raw)\n", - "\n", - "obj_detector = pipeline(\"object-detection\", model=\"MariaK/detr-resnet-50_finetuned_cppe5\")\n", - "obj_detector(image)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "You can also manually replicate the results of the pipeline if you'd like:" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "Detected Coverall with confidence 0.566 at location [1215.32, 147.38, 4401.81, 3227.08]\n", - "Detected Mask with confidence 0.584 at location [2449.06, 823.19, 3256.43, 1413.9]" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" + "cells": [ + { + "cell_type": "markdown", + "metadata": { + "id": "RGZ_ixRwjRCs" + }, + "source": [ + "# Object detection" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "jszgZ7oEjRCt" + }, + "source": [ + "Object detection is the computer vision task of detecting instances (such as humans, buildings, or cars) in an image. Object detection models receive an image as input and output\n", + "coordinates of the bounding boxes and associated labels of the detected objects. An image can contain multiple objects,\n", + "each with its own bounding box and a label (e.g. it can have a car and a building), and each object can\n", + "be present in different parts of an image (e.g. the image can have several cars).\n", + "This task is commonly used in autonomous driving for detecting things like pedestrians, road signs, and traffic lights.\n", + "Other applications include counting objects in images, image search, and more.\n", + "\n", + "In this guide, you will learn how to:\n", + "\n", + " 1. Finetune [DETR](https://huggingface.co/docs/transformers/model_doc/detr), a model that combines a convolutional\n", + " backbone with an encoder-decoder Transformer, on the [CPPE-5](https://huggingface.co/datasets/cppe-5)\n", + " dataset.\n", + " 2. Use your finetuned model for inference.\n", + "\n", + "\n", + "The task illustrated in this tutorial is supported by the following model architectures:\n", + "\n", + "\n", + "\n", + "[Conditional DETR](https://huggingface.co/docs/transformers/main/en/tasks/../model_doc/conditional_detr), [Deformable DETR](https://huggingface.co/docs/transformers/main/en/tasks/../model_doc/deformable_detr), [DETA](https://huggingface.co/docs/transformers/main/en/tasks/../model_doc/deta), [DETR](https://huggingface.co/docs/transformers/main/en/tasks/../model_doc/detr), [Table Transformer](https://huggingface.co/docs/transformers/main/en/tasks/../model_doc/table-transformer), [YOLOS](https://huggingface.co/docs/transformers/main/en/tasks/../model_doc/yolos)\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "Before you begin, make sure you have all the necessary libraries installed:" + ] + }, + { + "cell_type": "code", + "source": [ + "!pip install -q datasets transformers accelerate timm\n", + "!pip install -q -U albumentations>=1.4.5 torchmetrics pycocotools" + ], + "metadata": { + "id": "1P6a3PSnksas" + }, + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "source": [ + "You'll use 🤗 Datasets to load a dataset from the Hugging Face Hub, 🤗 Transformers to train your model,\n", + "and `albumentations` to augment the data.\n", + "\n", + "We encourage you to share your model with the community. Log in to your Hugging Face account to upload it to the Hub.\n", + "When prompted, enter your token to log in:" + ], + "metadata": { + "id": "3yYvu7pZkzWW" + } + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "id": "_HsPYGtsjRCv" + }, + "outputs": [], + "source": [ + "from huggingface_hub import notebook_login\n", + "\n", + "notebook_login()" + ] + }, + { + "cell_type": "markdown", + "source": [ + "To get started, we’ll define global constants, namely the model name and image size. For this tutorial, we’ll use the conditional DETR model due to its faster convergence. Feel free to select any object detection model available in the `transformers` library." + ], + "metadata": { + "id": "HQkmL1BilBI3" + } + }, + { + "cell_type": "code", + "source": [ + "MODEL_NAME = \"microsoft/conditional-detr-resnet-50\" # or \"facebook/detr-resnet-50\"\n", + "IMAGE_SIZE = 480" + ], + "metadata": { + "id": "cjII16SilI9W" + }, + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "eBe33FwfjRCw" + }, + "source": [ + "## Load the CPPE-5 dataset" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "ibpJ2155jRCw" + }, + "source": [ + "The [CPPE-5 dataset](https://huggingface.co/datasets/cppe-5) contains images with\n", + "annotations identifying medical personal protective equipment (PPE) in the context of the COVID-19 pandemic.\n", + "\n", + "Start by loading the dataset and creating a `validation` split from `train`:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "id": "dO9QdPcyjRCx" + }, + "outputs": [], + "source": [ + "from datasets import load_dataset\n", + "\n", + "cppe5 = load_dataset(\"cppe-5\")\n", + "\n", + "if \"validation\" not in cppe5:\n", + " split = cppe5[\"train\"].train_test_split(0.15, seed=1337)\n", + " cppe5[\"train\"] = split[\"train\"]\n", + " cppe5[\"validation\"] = split[\"test\"]\n", + "\n", + "cppe5" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "0gJDWXTujRCy" + }, + "source": [ + "You'll see that this dataset already comes with a training set containing 1000 images and a test set with 29 images.\n", + "\n", + "To get familiar with the data, explore what the examples look like." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "id": "T_m_UlnWjRCz" + }, + "outputs": [], + "source": [ + "cppe5[\"train\"][0]" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "fm2sEEuTjRCz" + }, + "source": [ + "The examples in the dataset have the following fields:\n", + "- `image_id`: the example image id\n", + "- `image`: a `PIL.Image.Image` object containing the image\n", + "- `width`: width of the image\n", + "- `height`: height of the image\n", + "- `objects`: a dictionary containing bounding box metadata for the objects in the image:\n", + " - `id`: the annotation id\n", + " - `area`: the area of the bounding box\n", + " - `bbox`: the object's bounding box (in the [COCO format](https://albumentations.ai/docs/getting_started/bounding_boxes_augmentation/#coco) )\n", + " - `category`: the object's category, with possible values including `Coverall (0)`, `Face_Shield (1)`, `Gloves (2)`, `Goggles (3)` and `Mask (4)`\n", + "\n", + "You may notice that the `bbox` field follows the COCO format, which is the format that the DETR model expects.\n", + "However, the grouping of the fields inside `objects` differs from the annotation format DETR requires. You will\n", + "need to apply some preprocessing transformations before using this data for training.\n", + "\n", + "To get an even better understanding of the data, visualize an example in the dataset." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "id": "jsFt7kGRjRC0" + }, + "outputs": [], + "source": [ + "import numpy as np\n", + "import os\n", + "from PIL import Image, ImageDraw\n", + "\n", + "image = cppe5[\"train\"][2][\"image\"]\n", + "annotations = cppe5[\"train\"][2][\"objects\"]\n", + "draw = ImageDraw.Draw(image)\n", + "\n", + "categories = cppe5[\"train\"].features[\"objects\"].feature[\"category\"].names\n", + "\n", + "id2label = {index: x for index, x in enumerate(categories, start=0)}\n", + "label2id = {v: k for k, v in id2label.items()}\n", + "\n", + "for i in range(len(annotations[\"id\"])):\n", + " box = annotations[\"bbox\"][i]\n", + " class_idx = annotations[\"category\"][i]\n", + " x, y, w, h = tuple(box)\n", + " # Check if coordinates are normalized or not\n", + " if max(box) > 1.0:\n", + " # Coordinates are un-normalized, no need to re-scale them\n", + " x1, y1 = int(x), int(y)\n", + " x2, y2 = int(x + w), int(y + h)\n", + " else:\n", + " # Coordinates are normalized, re-scale them\n", + " x1 = int(x * width)\n", + " y1 = int(y * height)\n", + " x2 = int((x + w) * width)\n", + " y2 = int((y + h) * height)\n", + " draw.rectangle((x, y, x + w, y + h), outline=\"red\", width=1)\n", + " draw.text((x, y), id2label[class_idx], fill=\"white\")\n", + "\n", + "image" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "HnpNthhkjRC0" + }, + "source": [ + "
\n", + " \"CPPE-5\n", + "
\n", + "\n", + "To visualize the bounding boxes with associated labels, you can get the labels from the dataset’s metadata, specifically the category field. You’ll also want to create dictionaries that map a label id to a label class (`id2label`) and the other way around (`label2id`). You can use them later when setting up the model. Including these maps will make your model reusable by others if you share it on the Hugging Face Hub. Please note that, the part of above code that draws the bounding boxes assume that it is in COCO format (`x_min`, `y_min`, `width`, `height`). It has to be adjusted to work for other formats like (`x_min`, `y_min`, `x_max`, `y_max`).\n", + "\n", + "As a final step of getting familiar with the data, explore it for potential issues. One common problem with datasets for object detection is bounding boxes that “stretch” beyond the edge of the image. Such “runaway” bounding boxes can raise errors during training and should be addressed. There are a few examples with this issue in this dataset. To keep things simple in this guide, we will set `clip=True` for BboxParams in transformations below." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "ldq8KElAjRC1" + }, + "source": [ + "## Preprocess the data" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "e_fYpGfWjRC1" + }, + "source": [ + "To finetune a model, you must preprocess the data you plan to use to match precisely the approach used for the pre-trained model.\n", + "[AutoImageProcessor](https://huggingface.co/docs/transformers/main/en/model_doc/auto#transformers.AutoImageProcessor) takes care of processing image data to create `pixel_values`, `pixel_mask`, and\n", + "`labels` that a DETR model can train with. The image processor has some attributes that you won't have to worry about:\n", + "\n", + "- `image_mean = [0.485, 0.456, 0.406 ]`\n", + "- `image_std = [0.229, 0.224, 0.225]`\n", + "\n", + "These are the mean and standard deviation used to normalize images during the model pre-training. These values are crucial\n", + "to replicate when doing inference or finetuning a pre-trained image model.\n", + "\n", + "Instantiate the image processor from the same checkpoint as the model you want to finetune." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "id": "UdoN2AY9jRC1" + }, + "outputs": [], + "source": [ + "from transformers import AutoImageProcessor\n", + "\n", + "MAX_SIZE = IMAGE_SIZE\n", + "\n", + "image_processor = AutoImageProcessor.from_pretrained(\n", + " MODEL_NAME,\n", + " do_resize=True,\n", + " size={\"max_height\": MAX_SIZE, \"max_width\": MAX_SIZE},\n", + " do_pad=True,\n", + " pad_size={\"height\": MAX_SIZE, \"width\": MAX_SIZE},\n", + ")" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "Dd4q8oAYjRC1" + }, + "source": [ + "Before passing the images to the `image_processor`, apply two preprocessing transformations to the dataset:\n", + "- Augmenting images\n", + "- Reformatting annotations to meet DETR expectations\n", + "\n", + "First, to make sure the model does not overfit on the training data, you can apply image augmentation with any data augmentation library. Here we use [Albumentations](https://albumentations.ai/docs/). This library ensures that transformations affect the image and update the bounding boxes accordingly. The 🤗 Datasets library documentation has a detailed [guide on how to augment images for object detection](https://huggingface.co/docs/datasets/object_detection), and it uses the exact same dataset as an example. Apply some geometric and color transformations to the image. For additional augmentation options, explore the [Albumentations Demo Space](https://huggingface.co/spaces/qubvel-hf/albumentations-demo)." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "id": "fNUndKt4jRC2" + }, + "outputs": [], + "source": [ + "import albumentations as A\n", + "\n", + "train_augment_and_transform = A.Compose(\n", + " [\n", + " A.Perspective(p=0.1),\n", + " A.HorizontalFlip(p=0.5),\n", + " A.RandomBrightnessContrast(p=0.5),\n", + " A.HueSaturationValue(p=0.1),\n", + " ],\n", + " bbox_params=A.BboxParams(format=\"coco\", label_fields=[\"category\"], clip=True, min_area=25),\n", + ")\n", + "\n", + "validation_transform = A.Compose(\n", + " [A.NoOp()],\n", + " bbox_params=A.BboxParams(format=\"coco\", label_fields=[\"category\"], clip=True),\n", + ")" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "22sllfV-jRC2" + }, + "source": [ + "The `image_processor` expects the annotations to be in the following format: `{'image_id': int, 'annotations': List[Dict]}`,\n", + " where each dictionary is a COCO object annotation. Let's add a function to reformat annotations for a single example:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "id": "JY03a11pjRC2" + }, + "outputs": [], + "source": [ + "def format_image_annotations_as_coco(image_id, categories, areas, bboxes):\n", + " \"\"\"Format one set of image annotations to the COCO format\n", + "\n", + " Args:\n", + " image_id (str): image id. e.g. \"0001\"\n", + " categories (List[int]): list of categories/class labels corresponding to provided bounding boxes\n", + " areas (List[float]): list of corresponding areas to provided bounding boxes\n", + " bboxes (List[Tuple[float]]): list of bounding boxes provided in COCO format\n", + " ([center_x, center_y, width, height] in absolute coordinates)\n", + "\n", + " Returns:\n", + " dict: {\n", + " \"image_id\": image id,\n", + " \"annotations\": list of formatted annotations\n", + " }\n", + " \"\"\"\n", + " annotations = []\n", + " for category, area, bbox in zip(categories, areas, bboxes):\n", + " formatted_annotation = {\n", + " \"image_id\": image_id,\n", + " \"category_id\": category,\n", + " \"iscrowd\": 0,\n", + " \"area\": area,\n", + " \"bbox\": list(bbox),\n", + " }\n", + " annotations.append(formatted_annotation)\n", + "\n", + " return {\n", + " \"image_id\": image_id,\n", + " \"annotations\": annotations,\n", + " }\n" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "CFc5loLwjRC2" + }, + "source": [ + "Now you can combine the image and annotation transformations to use on a batch of examples:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "id": "FVD6SfzNjRC2" + }, + "outputs": [], + "source": [ + "def augment_and_transform_batch(examples, transform, image_processor, return_pixel_mask=False):\n", + " \"\"\"Apply augmentations and format annotations in COCO format for object detection task\"\"\"\n", + "\n", + " images = []\n", + " annotations = []\n", + " for image_id, image, objects in zip(examples[\"image_id\"], examples[\"image\"], examples[\"objects\"]):\n", + " image = np.array(image.convert(\"RGB\"))\n", + "\n", + " # apply augmentations\n", + " output = transform(image=image, bboxes=objects[\"bbox\"], category=objects[\"category\"])\n", + " images.append(output[\"image\"])\n", + "\n", + " # format annotations in COCO format\n", + " formatted_annotations = format_image_annotations_as_coco(\n", + " image_id, output[\"category\"], objects[\"area\"], output[\"bboxes\"]\n", + " )\n", + " annotations.append(formatted_annotations)\n", + "\n", + " # Apply the image processor transformations: resizing, rescaling, normalization\n", + " result = image_processor(images=images, annotations=annotations, return_tensors=\"pt\")\n", + "\n", + " if not return_pixel_mask:\n", + " result.pop(\"pixel_mask\", None)\n", + "\n", + " return result" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "glo-4364jRC3" + }, + "source": [ + "Apply this preprocessing function to the entire dataset using 🤗 Datasets [with_transform](https://huggingface.co/docs/datasets/main/en/package_reference/main_classes#datasets.Dataset.with_transform) method. This method applies\n", + "transformations on the fly when you load an element of the dataset.\n", + "\n", + "At this point, you can check what an example from the dataset looks like after the transformations. You should see a tensor\n", + "with `pixel_values`, a tensor with `pixel_mask`, and `labels`." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "id": "gCpLY48BjRC3" + }, + "outputs": [], + "source": [ + "from functools import partial\n", + "\n", + "# Make transform functions for batch and apply for dataset splits\n", + "train_transform_batch = partial(\n", + " augment_and_transform_batch, transform=train_augment_and_transform, image_processor=image_processor\n", + ")\n", + "validation_transform_batch = partial(\n", + " augment_and_transform_batch, transform=validation_transform, image_processor=image_processor\n", + ")\n", + "\n", + "cppe5[\"train\"] = cppe5[\"train\"].with_transform(train_transform_batch)\n", + "cppe5[\"validation\"] = cppe5[\"validation\"].with_transform(validation_transform_batch)\n", + "cppe5[\"test\"] = cppe5[\"test\"].with_transform(validation_transform_batch)\n", + "\n", + "cppe5[\"train\"][15]" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "6fU4KuKBjRC3" + }, + "source": [ + "You have successfully augmented the individual images and prepared their annotations. However, preprocessing isn't\n", + "complete yet. In the final step, create a custom `collate_fn` to batch images together.\n", + "Pad images (which are now `pixel_values`) to the largest image in a batch, and create a corresponding `pixel_mask`\n", + "to indicate which pixels are real (1) and which are padding (0)." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "id": "BePJFLoIjRC3" + }, + "outputs": [], + "source": [ + "import torch\n", + "\n", + "def collate_fn(batch):\n", + " data = {}\n", + " data[\"pixel_values\"] = torch.stack([x[\"pixel_values\"] for x in batch])\n", + " data[\"labels\"] = [x[\"labels\"] for x in batch]\n", + " if \"pixel_mask\" in batch[0]:\n", + " data[\"pixel_mask\"] = torch.stack([x[\"pixel_mask\"] for x in batch])\n", + " return data\n" + ] + }, + { + "cell_type": "markdown", + "source": [ + "## Preparing function to compute mAP" + ], + "metadata": { + "id": "xqy6XSavm5w6" + } + }, + { + "cell_type": "markdown", + "source": [ + "Object detection models are commonly evaluated with a set of [COCO-style](https://cocodataset.org/#detection-eval) metrics. We are going to use `torchmetrics` to compute `mAP` (mean average precision) and `mAR` (mean average recall) metrics and will wrap it to `compute_metrics` function in order to use in [Trainer](https://huggingface.co/docs/transformers/v4.44.2/en/main_classes/trainer#transformers.Trainer) for evaluation.\n", + "\n", + "Intermediate format of boxes used for training is YOLO (normalized) but we will compute metrics for boxes in `Pascal VOC` (absolute) format in order to correctly handle box areas. Let’s define a function that converts bounding boxes to `Pascal VOC` format:" + ], + "metadata": { + "id": "ar_FF5dOm8P_" + } + }, + { + "cell_type": "code", + "source": [ + "from transformers.image_transforms import center_to_corners_format\n", + "\n", + "def convert_bbox_yolo_to_pascal(boxes, image_size):\n", + " \"\"\"\n", + " Convert bounding boxes from YOLO format (x_center, y_center, width, height) in range [0, 1]\n", + " to Pascal VOC format (x_min, y_min, x_max, y_max) in absolute coordinates.\n", + "\n", + " Args:\n", + " boxes (torch.Tensor): Bounding boxes in YOLO format\n", + " image_size (Tuple[int, int]): Image size in format (height, width)\n", + "\n", + " Returns:\n", + " torch.Tensor: Bounding boxes in Pascal VOC format (x_min, y_min, x_max, y_max)\n", + " \"\"\"\n", + " # convert center to corners format\n", + " boxes = center_to_corners_format(boxes)\n", + "\n", + " # convert to absolute coordinates\n", + " height, width = image_size\n", + " boxes = boxes * torch.tensor([[width, height, width, height]])\n", + "\n", + " return boxes" + ], + "metadata": { + "id": "zjQcKfc5nNub" + }, + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "source": [ + "Then, in `compute_metrics` function we collect `predicted` and `target` bounding boxes, scores and labels from evaluation loop results and pass it to the scoring function.\n", + "\n" + ], + "metadata": { + "id": "0fCnOE7lnQEr" + } + }, + { + "cell_type": "code", + "source": [ + "import numpy as np\n", + "from dataclasses import dataclass\n", + "from torchmetrics.detection.mean_ap import MeanAveragePrecision\n", + "\n", + "\n", + "@dataclass\n", + "class ModelOutput:\n", + " logits: torch.Tensor\n", + " pred_boxes: torch.Tensor\n", + "\n", + "\n", + "@torch.no_grad()\n", + "def compute_metrics(evaluation_results, image_processor, threshold=0.0, id2label=None):\n", + " \"\"\"\n", + " Compute mean average mAP, mAR and their variants for the object detection task.\n", + "\n", + " Args:\n", + " evaluation_results (EvalPrediction): Predictions and targets from evaluation.\n", + " threshold (float, optional): Threshold to filter predicted boxes by confidence. Defaults to 0.0.\n", + " id2label (Optional[dict], optional): Mapping from class id to class name. Defaults to None.\n", + "\n", + " Returns:\n", + " Mapping[str, float]: Metrics in a form of dictionary {: }\n", + " \"\"\"\n", + "\n", + " predictions, targets = evaluation_results.predictions, evaluation_results.label_ids\n", + "\n", + " # For metric computation we need to provide:\n", + " # - targets in a form of list of dictionaries with keys \"boxes\", \"labels\"\n", + " # - predictions in a form of list of dictionaries with keys \"boxes\", \"scores\", \"labels\"\n", + "\n", + " image_sizes = []\n", + " post_processed_targets = []\n", + " post_processed_predictions = []\n", + "\n", + " # Collect targets in the required format for metric computation\n", + " for batch in targets:\n", + " # collect image sizes, we will need them for predictions post processing\n", + " batch_image_sizes = torch.tensor(np.array([x[\"orig_size\"] for x in batch]))\n", + " image_sizes.append(batch_image_sizes)\n", + " # collect targets in the required format for metric computation\n", + " # boxes were converted to YOLO format needed for model training\n", + " # here we will convert them to Pascal VOC format (x_min, y_min, x_max, y_max)\n", + " for image_target in batch:\n", + " boxes = torch.tensor(image_target[\"boxes\"])\n", + " boxes = convert_bbox_yolo_to_pascal(boxes, image_target[\"orig_size\"])\n", + " labels = torch.tensor(image_target[\"class_labels\"])\n", + " post_processed_targets.append({\"boxes\": boxes, \"labels\": labels})\n", + "\n", + " # Collect predictions in the required format for metric computation,\n", + " # model produce boxes in YOLO format, then image_processor convert them to Pascal VOC format\n", + " for batch, target_sizes in zip(predictions, image_sizes):\n", + " batch_logits, batch_boxes = batch[1], batch[2]\n", + " output = ModelOutput(logits=torch.tensor(batch_logits), pred_boxes=torch.tensor(batch_boxes))\n", + " post_processed_output = image_processor.post_process_object_detection(\n", + " output, threshold=threshold, target_sizes=target_sizes\n", + " )\n", + " post_processed_predictions.extend(post_processed_output)\n", + "\n", + " # Compute metrics\n", + " metric = MeanAveragePrecision(box_format=\"xyxy\", class_metrics=True)\n", + " metric.update(post_processed_predictions, post_processed_targets)\n", + " metrics = metric.compute()\n", + "\n", + " # Replace list of per class metrics with separate metric for each class\n", + " classes = metrics.pop(\"classes\")\n", + " map_per_class = metrics.pop(\"map_per_class\")\n", + " mar_100_per_class = metrics.pop(\"mar_100_per_class\")\n", + " for class_id, class_map, class_mar in zip(classes, map_per_class, mar_100_per_class):\n", + " class_name = id2label[class_id.item()] if id2label is not None else class_id.item()\n", + " metrics[f\"map_{class_name}\"] = class_map\n", + " metrics[f\"mar_100_{class_name}\"] = class_mar\n", + "\n", + " metrics = {k: round(v.item(), 4) for k, v in metrics.items()}\n", + "\n", + " return metrics\n", + "\n", + "\n", + "eval_compute_metrics_fn = partial(\n", + " compute_metrics, image_processor=image_processor, id2label=id2label, threshold=0.0\n", + ")" + ], + "metadata": { + "id": "CzwJvhGRnS3B" + }, + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "0UxzYsMnjRC4" + }, + "source": [ + "## Training the detection model" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "_l19Rj6DjRC4" + }, + "source": [ + "You have done most of the heavy lifting in the previous sections, so now you are ready to train your model!\n", + "The images in this dataset are still quite large, even after resizing. This means that finetuning this model will\n", + "require at least one GPU.\n", + "\n", + "Training involves the following steps:\n", + "1. Load the model with [AutoModelForObjectDetection](https://huggingface.co/docs/transformers/main/en/model_doc/auto#transformers.AutoModelForObjectDetection) using the same checkpoint as in the preprocessing.\n", + "2. Define your training hyperparameters in [TrainingArguments](https://huggingface.co/docs/transformers/main/en/main_classes/trainer#transformers.TrainingArguments).\n", + "3. Pass the training arguments to [Trainer](https://huggingface.co/docs/transformers/main/en/main_classes/trainer#transformers.Trainer) along with the model, dataset, image processor, and data collator.\n", + "4. Call [train()](https://huggingface.co/docs/transformers/main/en/main_classes/trainer#transformers.Trainer.train) to finetune your model.\n", + "\n", + "When loading the model from the same checkpoint that you used for the preprocessing, remember to pass the `label2id`\n", + "and `id2label` maps that you created earlier from the dataset's metadata. Additionally, we specify `ignore_mismatched_sizes=True` to replace the existing classification head with a new one." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "id": "oltzA-rFjRC4" + }, + "outputs": [], + "source": [ + "from transformers import AutoModelForObjectDetection\n", + "\n", + "model = AutoModelForObjectDetection.from_pretrained(\n", + " MODEL_NAME,\n", + " id2label=id2label,\n", + " label2id=label2id,\n", + " ignore_mismatched_sizes=True,\n", + ")" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "Qxizsg6DjRC4" + }, + "source": [ + "In the [TrainingArguments](https://huggingface.co/docs/transformers/v4.44.2/en/main_classes/trainer#transformers.TrainingArguments) use `output_dir` to specify where to save your model, then configure hyperparameters as you see fit. For `num_train_epochs=30` training will take about 35 minutes in Google Colab T4 GPU, increase the number of epoch to get better results.\n", + "\n", + "Important notes:\n", + "\n", + "* Do not remove unused columns because this will drop the image column. Without the image column, you can’t create pixel_values. For this reason, set `remove_unused_columns` to False.\n", + "* Set `eval_do_concat_batches=False` to get proper evaluation results. Images have different number of target boxes, if batches are concatenated we will not be able to determine which boxes belongs to particular image.\n", + "\n", + "If you wish to share your model by pushing to the Hub, set `push_to_hub` to `True` (you must be signed in to Hugging Face to upload your model)." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "id": "Pxo6N6mRjRC4" + }, + "outputs": [], + "source": [ + "from transformers import TrainingArguments\n", + "\n", + "training_args = TrainingArguments(\n", + " output_dir=\"detr_finetuned_cppe5\",\n", + " num_train_epochs=30,\n", + " fp16=False,\n", + " per_device_train_batch_size=8,\n", + " dataloader_num_workers=4,\n", + " learning_rate=5e-5,\n", + " lr_scheduler_type=\"cosine\",\n", + " weight_decay=1e-4,\n", + " max_grad_norm=0.01,\n", + " metric_for_best_model=\"eval_map\",\n", + " greater_is_better=True,\n", + " load_best_model_at_end=True,\n", + " eval_strategy=\"epoch\",\n", + " save_strategy=\"epoch\",\n", + " save_total_limit=2,\n", + " remove_unused_columns=False,\n", + " eval_do_concat_batches=False,\n", + " push_to_hub=True,\n", + ")" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "6x5DqV79jRC5" + }, + "source": [ + "Finally, bring everything together, and call [train()](https://huggingface.co/docs/transformers/main/en/main_classes/trainer#transformers.Trainer.train):" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "id": "xh288Qz_jRC5" + }, + "outputs": [], + "source": [ + "from transformers import Trainer\n", + "\n", + "trainer = Trainer(\n", + " model=model,\n", + " args=training_args,\n", + " train_dataset=cppe5[\"train\"],\n", + " eval_dataset=cppe5[\"validation\"],\n", + " tokenizer=image_processor,\n", + " data_collator=collate_fn,\n", + " compute_metrics=eval_compute_metrics_fn,\n", + ")\n", + "\n", + "trainer.train()" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "y-EBN0HpjRC6" + }, + "source": [ + "If you have set `push_to_hub` to `True` in the `training_args`, the training checkpoints are pushed to the\n", + "Hugging Face Hub. Upon training completion, push the final model to the Hub as well by calling the [push_to_hub()](https://huggingface.co/docs/transformers/main/en/main_classes/trainer#transformers.Trainer.push_to_hub) method." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "id": "9P8AhLUBjRC6" + }, + "outputs": [], + "source": [ + "trainer.push_to_hub()" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "iqHN9RJvjRC6" + }, + "source": [ + "## Evaluate" + ] + }, + { + "cell_type": "code", + "source": [ + "from pprint import pprint\n", + "\n", + "metrics = trainer.evaluate(eval_dataset=cppe5[\"test\"], metric_key_prefix=\"test\")\n", + "pprint(metrics)" + ], + "metadata": { + "id": "maTIoC5ln4CE" + }, + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "source": [ + "These results can be further improved by adjusting the hyperparameters in [TrainingArguments](https://huggingface.co/docs/transformers/v4.44.2/en/main_classes/trainer#transformers.TrainingArguments). Give it a go!\n", + "\n" + ], + "metadata": { + "id": "sjbRpIFqn5rt" + } + }, + { + "cell_type": "markdown", + "source": [ + "## Inference" + ], + "metadata": { + "id": "yfZ59nikn9kv" + } + }, + { + "cell_type": "markdown", + "source": [ + "Now that you have finetuned a model, evaluated it, and uploaded it to the Hugging Face Hub, you can use it for inference.\n", + "\n" + ], + "metadata": { + "id": "HCa_YwdkoA00" + } + }, + { + "cell_type": "code", + "source": [ + "import torch\n", + "import requests\n", + "\n", + "from PIL import Image, ImageDraw\n", + "from transformers import AutoImageProcessor, AutoModelForObjectDetection\n", + "\n", + "url = \"https://images.pexels.com/photos/8413299/pexels-photo-8413299.jpeg?auto=compress&cs=tinysrgb&w=630&h=375&dpr=2\"\n", + "image = Image.open(requests.get(url, stream=True).raw)" + ], + "metadata": { + "id": "nYEc4L50n-mW" + }, + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "source": [ + "Load model and image processor from the Hugging Face Hub (skip to use already trained in this session):\n", + "\n" + ], + "metadata": { + "id": "qrWYfmu0oDnz" + } + }, + { + "cell_type": "code", + "source": [ + "device = \"cuda\"\n", + "model_repo = \"qubvel-hf/detr_finetuned_cppe5\"\n", + "\n", + "image_processor = AutoImageProcessor.from_pretrained(model_repo)\n", + "model = AutoModelForObjectDetection.from_pretrained(model_repo)\n", + "model = model.to(device)" + ], + "metadata": { + "id": "OmwZ-ltzoFSq" + }, + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "source": [ + "And detect bounding boxes:\n", + "\n" + ], + "metadata": { + "id": "DptFENNOoGoG" + } + }, + { + "cell_type": "code", + "source": [ + "with torch.no_grad():\n", + " inputs = image_processor(images=[image], return_tensors=\"pt\")\n", + " outputs = model(**inputs.to(device))\n", + " target_sizes = torch.tensor([[image.size[1], image.size[0]]])\n", + " results = image_processor.post_process_object_detection(outputs, threshold=0.3, target_sizes=target_sizes)[0]\n", + "\n", + "for score, label, box in zip(results[\"scores\"], results[\"labels\"], results[\"boxes\"]):\n", + " box = [round(i, 2) for i in box.tolist()]\n", + " print(\n", + " f\"Detected {model.config.id2label[label.item()]} with confidence \"\n", + " f\"{round(score.item(), 3)} at location {box}\"\n", + " )" + ], + "metadata": { + "id": "YlFWNFRxoHDI" + }, + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "source": [ + "Let’s plot the result:\n", + "\n" + ], + "metadata": { + "id": "j_m35fRzoJmV" + } + }, + { + "cell_type": "code", + "source": [ + "draw = ImageDraw.Draw(image)\n", + "\n", + "for score, label, box in zip(results[\"scores\"], results[\"labels\"], results[\"boxes\"]):\n", + " box = [round(i, 2) for i in box.tolist()]\n", + " x, y, x2, y2 = tuple(box)\n", + " draw.rectangle((x, y, x2, y2), outline=\"red\", width=1)\n", + " draw.text((x, y), model.config.id2label[label.item()], fill=\"white\")\n", + "\n", + "image" + ], + "metadata": { + "id": "ZuLuGKl2oJ9X" + }, + "execution_count": null, + "outputs": [] } - ], - "source": [ - "image_processor = AutoImageProcessor.from_pretrained(\"MariaK/detr-resnet-50_finetuned_cppe5\")\n", - "model = AutoModelForObjectDetection.from_pretrained(\"MariaK/detr-resnet-50_finetuned_cppe5\")\n", - "\n", - "with torch.no_grad():\n", - " inputs = image_processor(images=image, return_tensors=\"pt\")\n", - " outputs = model(**inputs)\n", - " target_sizes = torch.tensor([image.size[::-1]])\n", - " results = image_processor.post_process_object_detection(outputs, threshold=0.5, target_sizes=target_sizes)[0]\n", - "\n", - "for score, label, box in zip(results[\"scores\"], results[\"labels\"], results[\"boxes\"]):\n", - " box = [round(i, 2) for i in box.tolist()]\n", - " print(\n", - " f\"Detected {model.config.id2label[label.item()]} with confidence \"\n", - " f\"{round(score.item(), 3)} at location {box}\"\n", - " )" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Let's plot the result:" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "draw = ImageDraw.Draw(image)\n", - "\n", - "for score, label, box in zip(results[\"scores\"], results[\"labels\"], results[\"boxes\"]):\n", - " box = [round(i, 2) for i in box.tolist()]\n", - " x, y, x2, y2 = tuple(box)\n", - " draw.rectangle((x, y, x2, y2), outline=\"red\", width=1)\n", - " draw.text((x, y), model.config.id2label[label.item()], fill=\"white\")\n", - "\n", - "image" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "
\n", - " \"Object\n", - "
" - ] - } - ], - "metadata": {}, - "nbformat": 4, - "nbformat_minor": 4 -} + ], + "metadata": { + "colab": { + "provenance": [], + "toc_visible": true, + "gpuType": "T4" + }, + "language_info": { + "name": "python" + }, + "kernelspec": { + "name": "python3", + "display_name": "Python 3" + }, + "accelerator": "GPU" + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file