diff --git a/docs/source/en/tasks/object_detection.md b/docs/source/en/tasks/object_detection.md index 0d640ca459cc26..aebac36c90c29f 100644 --- a/docs/source/en/tasks/object_detection.md +++ b/docs/source/en/tasks/object_detection.md @@ -41,7 +41,8 @@ To see all architectures and checkpoints compatible with this task, we recommend Before you begin, make sure you have all the necessary libraries installed: ```bash -pip install -q datasets transformers accelerate evaluate albumentations +pip install -q datasets transformers accelerate timm +pip install -q -U albumentations>=1.4.5 torchmetrics pycocotools ``` You'll use 🤗 Datasets to load a dataset from the Hugging Face Hub, 🤗 Transformers to train your model, @@ -56,47 +57,67 @@ When prompted, enter your token to log in: >>> notebook_login() ``` +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. + +```py +>>> MODEL_NAME = "microsoft/conditional-detr-resnet-50" # or "facebook/detr-resnet-50" +>>> IMAGE_SIZE = 480 +``` + ## Load the CPPE-5 dataset The [CPPE-5 dataset](https://huggingface.co/datasets/cppe-5) contains images with annotations identifying medical personal protective equipment (PPE) in the context of the COVID-19 pandemic. -Start by loading the dataset: +Start by loading the dataset and creating a `validation` split from `train`: ```py >>> from datasets import load_dataset >>> cppe5 = load_dataset("cppe-5") + +>>> if "validation" not in cppe5: +... split = cppe5["train"].train_test_split(0.15, seed=1337) +... cppe5["train"] = split["train"] +... cppe5["validation"] = split["test"] + >>> cppe5 DatasetDict({ train: Dataset({ features: ['image_id', 'image', 'width', 'height', 'objects'], - num_rows: 1000 + num_rows: 850 }) test: Dataset({ features: ['image_id', 'image', 'width', 'height', 'objects'], num_rows: 29 }) + validation: Dataset({ + features: ['image_id', 'image', 'width', 'height', 'objects'], + num_rows: 150 + }) }) ``` -You'll see that this dataset already comes with a training set containing 1000 images and a test set with 29 images. +You'll see that this dataset has 1000 images for train and validation sets and a test set with 29 images. To get familiar with the data, explore what the examples look like. ```py >>> cppe5["train"][0] -{'image_id': 15, - 'image': , - 'width': 943, - 'height': 663, - 'objects': {'id': [114, 115, 116, 117], - 'area': [3796, 1596, 152768, 81002], - 'bbox': [[302.0, 109.0, 73.0, 52.0], - [810.0, 100.0, 57.0, 28.0], - [160.0, 31.0, 248.0, 616.0], - [741.0, 68.0, 202.0, 401.0]], - 'category': [4, 4, 0, 0]}} +{ + 'image_id': 366, + 'image': , + 'width': 500, + 'height': 500, + 'objects': { + 'id': [1932, 1933, 1934], + 'area': [27063, 34200, 32431], + 'bbox': [[29.0, 11.0, 97.0, 279.0], + [201.0, 1.0, 120.0, 285.0], + [382.0, 0.0, 113.0, 287.0]], + 'category': [0, 0, 0] + } +} ``` The examples in the dataset have the following fields: @@ -121,8 +142,8 @@ To get an even better understanding of the data, visualize an example in the dat >>> import os >>> from PIL import Image, ImageDraw ->>> image = cppe5["train"][0]["image"] ->>> annotations = cppe5["train"][0]["objects"] +>>> image = cppe5["train"][2]["image"] +>>> annotations = cppe5["train"][2]["objects"] >>> draw = ImageDraw.Draw(image) >>> categories = cppe5["train"].features["objects"].feature["category"].names @@ -150,27 +171,21 @@ To get an even better understanding of the data, visualize an example in the dat >>> image ``` -
- CPPE-5 Image Example + CPPE-5 Image Example
+ 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 `XYWH` (x,y co-ordinates and width and height of the box) format. It might not work for other formats like `(x1, y1, x2, y2)`. +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)`. 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 at this stage. There are a few examples with this issue in this dataset. -To keep things simple in this guide, we remove these images from the data. - -```py ->>> remove_idx = [590, 821, 822, 875, 876, 878, 879] ->>> keep = [i for i in range(len(cppe5["train"])) if i not in remove_idx] ->>> cppe5["train"] = cppe5["train"].select(keep) -``` +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. ## Preprocess the data @@ -189,8 +204,13 @@ Instantiate the image processor from the same checkpoint as the model you want t ```py >>> from transformers import AutoImageProcessor ->>> checkpoint = "facebook/detr-resnet-50" ->>> image_processor = AutoImageProcessor.from_pretrained(checkpoint) +>>> image_processor = AutoImageProcessor.from_pretrained( +... MODEL_NAME, +... # At this moment we recommend using external transform to pad and resize images. +... # It`s faster and yields better results for object-detection models. +... do_pad=False, +... do_resize=False, +... ) ``` Before passing the images to the `image_processor`, apply two preprocessing transformations to the dataset: @@ -201,20 +221,35 @@ First, to make sure the model does not overfit on the training data, you can app 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 the same approach here, resize each image to (480, 480), -flip it horizontally, and brighten it: +flip it horizontally, and brighten it. For additional augmentation options, explore the [Albumentations Demo Space](https://huggingface.co/spaces/qubvel-hf/albumentations-demo). ```py ->>> import albumentations ->>> import numpy as np ->>> import torch +>>> import albumentations as A + +>>> max_size = IMAGE_SIZE + +>>> # Resize image longest edge to 480 and then pad image to square 480x480. +>>> # This padding and resizing strategy give better results, see +>>> # https://github.com/huggingface/transformers/pull/30422#discussion_r1584647408 +>>> basic_transforms = [ +... A.LongestMaxSize(max_size=max_size), +... A.PadIfNeeded(max_size, max_size, border_mode=0, value=(128, 128, 128), position="top_left"), +... ] ->>> transform = albumentations.Compose( +>>> train_augment_and_transform = A.Compose( ... [ -... albumentations.Resize(480, 480), -... albumentations.HorizontalFlip(p=1.0), -... albumentations.RandomBrightnessContrast(p=1.0), +... A.Perspective(p=0.1), +... A.HorizontalFlip(p=0.5), +... A.RandomBrightnessContrast(p=0.5), +... A.HueSaturationValue(p=0.1), +... *basic_transforms, ... ], -... bbox_params=albumentations.BboxParams(format="coco", label_fields=["category"]), +... bbox_params=A.BboxParams(format="coco", label_fields=["category"], clip=True, min_area=25), +... ) + +>>> validation_transform = A.Compose( +... basic_transforms, +... bbox_params=A.BboxParams(format="coco", label_fields=["category"], clip=True), ... ) ``` @@ -222,43 +257,65 @@ The `image_processor` expects the annotations to be in the following format: `{' where each dictionary is a COCO object annotation. Let's add a function to reformat annotations for a single example: ```py ->>> def formatted_anns(image_id, category, area, bbox): +>>> def format_image_annotations_as_coco(image_id, categories, areas, bboxes): +... """Format one set of image annotations to the COCO format + +... Args: +... image_id (str): image id. e.g. "0001" +... categories (List[int]): list of categories/class labels corresponding to provided bounding boxes +... areas (List[float]): list of corresponding areas to provided bounding boxes +... bboxes (List[Tuple[float]]): list of bounding boxes provided in COCO format +... ([center_x, center_y, width, height] in absolute coordinates) + +... Returns: +... dict: { +... "image_id": image id, +... "annotations": list of formatted annotations +... } +... """ ... annotations = [] -... for i in range(0, len(category)): -... new_ann = { +... for category, area, bbox in zip(categories, areas, bboxes): +... formatted_annotation = { ... "image_id": image_id, -... "category_id": category[i], -... "isCrowd": 0, -... "area": area[i], -... "bbox": list(bbox[i]), +... "category_id": category, +... "iscrowd": 0, +... "area": area, +... "bbox": list(bbox), ... } -... annotations.append(new_ann) +... annotations.append(formatted_annotation) + +... return { +... "image_id": image_id, +... "annotations": annotations, +... } -... return annotations ``` Now you can combine the image and annotation transformations to use on a batch of examples: ```py ->>> # transforming a batch ->>> def transform_aug_ann(examples): -... image_ids = examples["image_id"] -... images, bboxes, area, categories = [], [], [], [] -... for image, objects in zip(examples["image"], examples["objects"]): -... image = np.array(image.convert("RGB"))[:, :, ::-1] -... out = transform(image=image, bboxes=objects["bbox"], category=objects["category"]) - -... area.append(objects["area"]) -... images.append(out["image"]) -... bboxes.append(out["bboxes"]) -... categories.append(out["category"]) - -... targets = [ -... {"image_id": id_, "annotations": formatted_anns(id_, cat_, ar_, box_)} -... for id_, cat_, ar_, box_ in zip(image_ids, categories, area, bboxes) -... ] - -... return image_processor(images=images, annotations=targets, return_tensors="pt") +>>> def augment_and_transform_batch(examples, transform, image_processor): +... """Apply augmentations and format annotations in COCO format for object detection task""" + +... images = [] +... annotations = [] +... for image_id, image, objects in zip(examples["image_id"], examples["image"], examples["objects"]): +... image = np.array(image.convert("RGB")) + +... # apply augmentations +... output = transform(image=image, bboxes=objects["bbox"], category=objects["category"]) +... images.append(output["image"]) + +... # format annotations in COCO format +... formatted_annotations = format_image_annotations_as_coco( +... image_id, output["category"], objects["area"], output["bboxes"] +... ) +... annotations.append(formatted_annotations) + +... # Apply the image processor transformations: resizing, rescaling, normalization +... result = image_processor(images=images, annotations=annotations, return_tensors="pt") + +... return result ``` Apply this preprocessing function to the entire dataset using 🤗 Datasets [`~datasets.Dataset.with_transform`] method. This method applies @@ -268,39 +325,49 @@ At this point, you can check what an example from the dataset looks like after t with `pixel_values`, a tensor with `pixel_mask`, and `labels`. ```py ->>> cppe5["train"] = cppe5["train"].with_transform(transform_aug_ann) +>>> from functools import partial + +>>> # Make transform functions for batch and apply for dataset splits +>>> train_transform_batch = partial( +... augment_and_transform_batch, transform=train_augment_and_transform, image_processor=image_processor +... ) +>>> validation_transform_batch = partial( +... augment_and_transform_batch, transform=validation_transform, image_processor=image_processor +... ) + +>>> cppe5["train"] = cppe5["train"].with_transform(train_transform_batch) +>>> cppe5["validation"] = cppe5["validation"].with_transform(validation_transform_batch) +>>> cppe5["test"] = cppe5["test"].with_transform(validation_transform_batch) + >>> cppe5["train"][15] -{'pixel_values': tensor([[[ 0.9132, 0.9132, 0.9132, ..., -1.9809, -1.9809, -1.9809], - [ 0.9132, 0.9132, 0.9132, ..., -1.9809, -1.9809, -1.9809], - [ 0.9132, 0.9132, 0.9132, ..., -1.9638, -1.9638, -1.9638], +{'pixel_values': tensor([[[ 1.9235, 1.9407, 1.9749, ..., -0.7822, -0.7479, -0.6965], + [ 1.9578, 1.9749, 1.9920, ..., -0.7993, -0.7650, -0.7308], + [ 2.0092, 2.0092, 2.0263, ..., -0.8507, -0.8164, -0.7822], ..., - [-1.5699, -1.5699, -1.5699, ..., -1.9980, -1.9980, -1.9980], - [-1.5528, -1.5528, -1.5528, ..., -1.9980, -1.9809, -1.9809], - [-1.5528, -1.5528, -1.5528, ..., -1.9980, -1.9809, -1.9809]], - - [[ 1.3081, 1.3081, 1.3081, ..., -1.8431, -1.8431, -1.8431], - [ 1.3081, 1.3081, 1.3081, ..., -1.8431, -1.8431, -1.8431], - [ 1.3081, 1.3081, 1.3081, ..., -1.8256, -1.8256, -1.8256], + [ 0.0741, 0.0741, 0.0741, ..., 0.0741, 0.0741, 0.0741], + [ 0.0741, 0.0741, 0.0741, ..., 0.0741, 0.0741, 0.0741], + [ 0.0741, 0.0741, 0.0741, ..., 0.0741, 0.0741, 0.0741]], + + [[ 1.6232, 1.6408, 1.6583, ..., 0.8704, 1.0105, 1.1331], + [ 1.6408, 1.6583, 1.6758, ..., 0.8529, 0.9930, 1.0980], + [ 1.6933, 1.6933, 1.7108, ..., 0.8179, 0.9580, 1.0630], ..., - [-1.3179, -1.3179, -1.3179, ..., -1.8606, -1.8606, -1.8606], - [-1.3004, -1.3004, -1.3004, ..., -1.8606, -1.8431, -1.8431], - [-1.3004, -1.3004, -1.3004, ..., -1.8606, -1.8431, -1.8431]], - - [[ 1.4200, 1.4200, 1.4200, ..., -1.6476, -1.6476, -1.6476], - [ 1.4200, 1.4200, 1.4200, ..., -1.6476, -1.6476, -1.6476], - [ 1.4200, 1.4200, 1.4200, ..., -1.6302, -1.6302, -1.6302], + [ 0.2052, 0.2052, 0.2052, ..., 0.2052, 0.2052, 0.2052], + [ 0.2052, 0.2052, 0.2052, ..., 0.2052, 0.2052, 0.2052], + [ 0.2052, 0.2052, 0.2052, ..., 0.2052, 0.2052, 0.2052]], + + [[ 1.8905, 1.9080, 1.9428, ..., -0.1487, -0.0964, -0.0615], + [ 1.9254, 1.9428, 1.9603, ..., -0.1661, -0.1138, -0.0790], + [ 1.9777, 1.9777, 1.9951, ..., -0.2010, -0.1138, -0.0790], ..., - [-1.0201, -1.0201, -1.0201, ..., -1.5604, -1.5604, -1.5604], - [-1.0027, -1.0027, -1.0027, ..., -1.5604, -1.5430, -1.5430], - [-1.0027, -1.0027, -1.0027, ..., -1.5604, -1.5430, -1.5430]]]), - 'pixel_mask': tensor([[1, 1, 1, ..., 1, 1, 1], - [1, 1, 1, ..., 1, 1, 1], - [1, 1, 1, ..., 1, 1, 1], - ..., - [1, 1, 1, ..., 1, 1, 1], - [1, 1, 1, ..., 1, 1, 1], - [1, 1, 1, ..., 1, 1, 1]]), - '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])}} + [ 0.4265, 0.4265, 0.4265, ..., 0.4265, 0.4265, 0.4265], + [ 0.4265, 0.4265, 0.4265, ..., 0.4265, 0.4265, 0.4265], + [ 0.4265, 0.4265, 0.4265, ..., 0.4265, 0.4265, 0.4265]]]), + 'labels': {'image_id': tensor([688]), 'class_labels': tensor([3, 4, 2, 0, 0]), 'boxes': tensor([[0.4700, 0.1933, 0.1467, 0.0767], + [0.4858, 0.2600, 0.1150, 0.1000], + [0.4042, 0.4517, 0.1217, 0.1300], + [0.4242, 0.3217, 0.3617, 0.5567], + [0.6617, 0.4033, 0.5400, 0.4533]]), 'area': tensor([ 4048., 4140., 5694., 72478., 88128.]), 'iscrowd': tensor([0, 0, 0, 0, 0]), 'orig_size': tensor([480, 480])}} ``` You have successfully augmented the individual images and prepared their annotations. However, preprocessing isn't @@ -309,18 +376,137 @@ Pad images (which are now `pixel_values`) to the largest image in a batch, and c to indicate which pixels are real (1) and which are padding (0). ```py +>>> import torch + >>> def collate_fn(batch): -... pixel_values = [item["pixel_values"] for item in batch] -... encoding = image_processor.pad(pixel_values, return_tensors="pt") -... labels = [item["labels"] for item in batch] -... batch = {} -... batch["pixel_values"] = encoding["pixel_values"] -... batch["pixel_mask"] = encoding["pixel_mask"] -... batch["labels"] = labels -... return batch +... data = {} +... data["pixel_values"] = torch.stack([x["pixel_values"] for x in batch]) +... data["labels"] = [x["labels"] for x in batch] +... if "pixel_mask" in batch[0]: +... data["pixel_mask"] = torch.stack([x["pixel_mask"] for x in batch]) +... return data + +``` + +## Preparing function to compute mAP + +Object detection models are commonly evaluated with a set of COCO-style 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`] for evaluation. + +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: + +```py +>>> from transformers.image_transforms import center_to_corners_format + +>>> def convert_bbox_yolo_to_pascal(boxes, image_size): +... """ +... Convert bounding boxes from YOLO format (x_center, y_center, width, height) in range [0, 1] +... to Pascal VOC format (x_min, y_min, x_max, y_max) in absolute coordinates. + +... Args: +... boxes (torch.Tensor): Bounding boxes in YOLO format +... image_size (Tuple[int, int]): Image size in format (height, width) + +... Returns: +... torch.Tensor: Bounding boxes in Pascal VOC format (x_min, y_min, x_max, y_max) +... """ +... # convert center to corners format +... boxes = center_to_corners_format(boxes) + +... # convert to absolute coordinates +... height, width = image_size +... boxes = boxes * torch.tensor([[width, height, width, height]]) + +... return boxes +``` + +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. + +```py +>>> import numpy as np +>>> from dataclasses import dataclass +>>> from torchmetrics.detection.mean_ap import MeanAveragePrecision + + +>>> @dataclass +>>> class ModelOutput: +... logits: torch.Tensor +... pred_boxes: torch.Tensor + + +>>> @torch.no_grad() +>>> def compute_metrics(evaluation_results, image_processor, threshold=0.0, id2label=None): +... """ +... Compute mean average mAP, mAR and their variants for the object detection task. + +... Args: +... evaluation_results (EvalPrediction): Predictions and targets from evaluation. +... threshold (float, optional): Threshold to filter predicted boxes by confidence. Defaults to 0.0. +... id2label (Optional[dict], optional): Mapping from class id to class name. Defaults to None. + +... Returns: +... Mapping[str, float]: Metrics in a form of dictionary {: } +... """ + +... predictions, targets = evaluation_results.predictions, evaluation_results.label_ids + +... # For metric computation we need to provide: +... # - targets in a form of list of dictionaries with keys "boxes", "labels" +... # - predictions in a form of list of dictionaries with keys "boxes", "scores", "labels" + +... image_sizes = [] +... post_processed_targets = [] +... post_processed_predictions = [] + +... # Collect targets in the required format for metric computation +... for batch in targets: +... # collect image sizes, we will need them for predictions post processing +... batch_image_sizes = torch.tensor(np.array([x["orig_size"] for x in batch])) +... image_sizes.append(batch_image_sizes) +... # collect targets in the required format for metric computation +... # boxes were converted to YOLO format needed for model training +... # here we will convert them to Pascal VOC format (x_min, y_min, x_max, y_max) +... for image_target in batch: +... boxes = torch.tensor(image_target["boxes"]) +... boxes = convert_bbox_yolo_to_pascal(boxes, image_target["orig_size"]) +... labels = torch.tensor(image_target["class_labels"]) +... post_processed_targets.append({"boxes": boxes, "labels": labels}) + +... # Collect predictions in the required format for metric computation, +... # model produce boxes in YOLO format, then image_processor convert them to Pascal VOC format +... for batch, target_sizes in zip(predictions, image_sizes): +... batch_logits, batch_boxes = batch[1], batch[2] +... output = ModelOutput(logits=torch.tensor(batch_logits), pred_boxes=torch.tensor(batch_boxes)) +... post_processed_output = image_processor.post_process_object_detection( +... output, threshold=threshold, target_sizes=target_sizes +... ) +... post_processed_predictions.extend(post_processed_output) + +... # Compute metrics +... metric = MeanAveragePrecision(box_format="xyxy", class_metrics=True) +... metric.update(post_processed_predictions, post_processed_targets) +... metrics = metric.compute() + +... # Replace list of per class metrics with separate metric for each class +... classes = metrics.pop("classes") +... map_per_class = metrics.pop("map_per_class") +... mar_100_per_class = metrics.pop("mar_100_per_class") +... for class_id, class_map, class_mar in zip(classes, map_per_class, mar_100_per_class): +... class_name = id2label[class_id.item()] if id2label is not None else class_id.item() +... metrics[f"map_{class_name}"] = class_map +... metrics[f"mar_100_{class_name}"] = class_mar + +... metrics = {k: round(v.item(), 4) for k, v in metrics.items()} + +... return metrics + + +>>> eval_compute_metrics_fn = partial( +... compute_metrics, image_processor=image_processor, id2label=id2label, threshold=0.0 +... ) ``` -## Training the DETR model +## Training the detection model + You have done most of the heavy lifting in the previous sections, so now you are ready to train your model! The images in this dataset are still quite large, even after resizing. This means that finetuning this model will require at least one GPU. @@ -338,17 +524,20 @@ and `id2label` maps that you created earlier from the dataset's metadata. Additi >>> from transformers import AutoModelForObjectDetection >>> model = AutoModelForObjectDetection.from_pretrained( -... checkpoint, +... MODEL_NAME, ... id2label=id2label, ... label2id=label2id, ... ignore_mismatched_sizes=True, -... revision="no_timm", # DETR models can be loaded without timm ... ) ``` -In the [`TrainingArguments`] use `output_dir` to specify where to save your model, then configure hyperparameters as you see fit. -It is important you do not remove unused columns because this will drop the image column. Without the image column, you +In the [`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. + +Important notes: + - 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`. + - 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. + 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). @@ -356,16 +545,23 @@ Face to upload your model). >>> from transformers import TrainingArguments >>> training_args = TrainingArguments( -... output_dir="detr-resnet-50_finetuned_cppe5", +... output_dir="detr_finetuned_cppe5", +... num_train_epochs=30, +... fp16=False, ... per_device_train_batch_size=8, -... num_train_epochs=100, -... fp16=True, -... save_steps=200, -... logging_steps=50, -... learning_rate=1e-5, +... dataloader_num_workers=4, +... learning_rate=5e-5, +... lr_scheduler_type="cosine", ... weight_decay=1e-4, +... max_grad_norm=0.01, +... metric_for_best_model="eval_map", +... greater_is_better=True, +... load_best_model_at_end=True, +... eval_strategy="epoch", +... save_strategy="epoch", ... save_total_limit=2, ... remove_unused_columns=False, +... eval_do_concat_batches=False, ... push_to_hub=True, ... ) ``` @@ -378,13 +574,864 @@ Finally, bring everything together, and call [`~transformers.Trainer.train`]: >>> trainer = Trainer( ... model=model, ... args=training_args, -... data_collator=collate_fn, ... train_dataset=cppe5["train"], +... eval_dataset=cppe5["validation"], ... tokenizer=image_processor, +... data_collator=collate_fn, +... compute_metrics=eval_compute_metrics_fn, ... ) >>> trainer.train() ``` +
+ + + [3210/3210 26:07, Epoch 30/30] +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
EpochTraining LossValidation LossMapMap 50Map 75Map SmallMap MediumMap LargeMar 1Mar 10Mar 100Mar SmallMar MediumMar LargeMap CoverallMar 100 CoverallMap Face ShieldMar 100 Face ShieldMap GlovesMar 100 GlovesMap GogglesMar 100 GogglesMap MaskMar 100 Mask
1No log2.6299030.0089000.0232000.0065000.0013000.0028000.0205000.0215000.0704000.1014000.0076000.1062000.0961000.0367000.2320000.0003000.0190000.0039000.1254000.0001000.0031000.0035000.127600
2No log3.4798640.0148000.0346000.0108000.0086000.0117000.0125000.0411000.0987000.1300000.0560000.0622000.1119000.0535000.4473000.0106000.1000000.0002000.0228000.0001000.0154000.0097000.064400
3No log2.1076220.0417000.0940000.0343000.0241000.0264000.0474000.0915000.1828000.2258000.0872000.1994000.2106000.1509000.5712000.0173000.1013000.0073000.1804000.0021000.0262000.0310000.250200
4No log2.0312420.0559000.1206000.0469000.0138000.0381000.0903000.1059000.2256000.2661000.1302000.2281000.3300000.1910000.5721000.0106000.1570000.0146000.2353000.0017000.0523000.0618000.313800
53.8894001.8834330.0897000.2018000.0673000.0228000.0653000.1295000.1360000.2722000.3037000.1129000.3125000.4246000.3002000.5851000.0327000.2025000.0313000.2710000.0087000.1262000.0755000.333800
63.8894001.8075030.1185000.2709000.0902000.0349000.0767000.1525000.1461000.2978000.3254000.1717000.2837000.5459000.3969000.5545000.0430000.2620000.0545000.2719000.0203000.2308000.0776000.308000
73.8894001.7161690.1435000.3077000.1232000.0458000.0978000.2583000.1653000.3277000.3526000.1409000.3367000.5994000.4429000.6207000.0694000.3013000.0816000.2920000.0110000.2308000.1127000.318200
83.8894001.6790140.1530000.3558000.1279000.0387000.1156000.2916000.1760000.3225000.3497000.1356000.3261000.6437000.4317000.5829000.0698000.2658000.0886000.2746000.0283000.2800000.1467000.345300
93.8894001.6182390.1721000.3753000.1376000.0461000.1417000.3085000.1940000.3562000.3862000.1624000.3592000.6777000.4698000.6239000.1021000.3177000.0991000.2902000.0293000.3354000.1602000.364000
101.5997001.5725120.1795000.4004000.1472000.0565000.1417000.3167000.2131000.3576000.3813000.1979000.3443000.6385000.4669000.6239000.1013000.3114000.1047000.2795000.0516000.3385000.1730000.353300
111.5997001.5288890.1922000.4150000.1608000.0537000.1505000.3780000.2115000.3717000.3978000.2049000.3746000.6848000.4919000.6324000.1312000.3468000.1220000.3009000.0384000.3446000.1775000.364400
121.5997001.5175320.1983000.4298000.1598000.0664000.1629000.3833000.2207000.3821000.4054000.2148000.3832000.6729000.4690000.6104000.1678000.3797000.1197000.3071000.0381000.3354000.1968000.394200
131.5997001.4888490.2098000.4523000.1723000.0949000.1711000.4378000.2220000.3798000.4115000.2038000.3973000.7075000.4707000.6207000.1869000.4076000.1242000.3067000.0593000.3554000.2077000.367100
141.5997001.4822100.2289000.4826000.1878000.0836000.1918000.4441000.2259000.3769000.4074000.1825000.3848000.7006000.5121000.6401000.1750000.3633000.1443000.3000000.0831000.3631000.2299000.370700
151.3268001.4751980.2163000.4556000.1749000.0885000.1835000.4244000.2269000.3734000.4043000.1992000.3964000.6778000.4963000.6338000.1663000.3924000.1289000.3129000.0852000.3123000.2050000.370200
161.3268001.4596970.2332000.5042000.1922000.0960000.2020000.4308000.2391000.3824000.4126000.2195000.4031000.6704000.4852000.6252000.1965000.4101000.1357000.2996000.1231000.3569000.2253000.371100
171.3268001.4073400.2434000.5119000.2045000.1210000.2157000.4680000.2462000.3946000.4242000.2259000.4161000.7052000.4949000.6383000.2249000.4304000.1572000.3179000.1157000.3692000.2242000.365300
181.3268001.4195220.2451000.5215000.2100000.1161000.2115000.4899000.2554000.3916000.4197000.1988000.4212000.7014000.5018000.6342000.2267000.4101000.1544000.3214000.1059000.3523000.2367000.380400
191.1586001.3987640.2536000.5192000.2136000.1352000.2077000.4919000.2573000.3973000.4280000.2414000.4018000.7035000.5097000.6311000.2367000.4418000.1559000.3308000.1281000.3523000.2375000.384000
201.1586001.3905910.2488000.5202000.2166000.1275000.2114000.4719000.2583000.4070000.4291000.2403000.4076000.7085000.5058000.6234000.2355000.4316000.1500000.3250000.1257000.3754000.2272000.390200
211.1586001.3606080.2627000.5448000.2221000.1347000.2300000.4875000.2695000.4133000.4363000.2362000.4191000.7093000.5141000.6374000.2572000.4506000.1651000.3384000.1394000.3723000.2377000.382700
221.1586001.3682960.2628000.5424000.2364000.1374000.2281000.4985000.2665000.4090000.4330000.2399000.4185000.6975000.5205000.6410000.2575000.4557000.1626000.3348000.1402000.3538000.2332000.379600
231.1586001.3681760.2648000.5411000.2331000.1382000.2239000.4987000.2723000.4074000.4344000.2331000.4183000.7020000.5244000.6423000.2623000.4443000.1597000.3353000.1405000.3662000.2369000.384000
241.0497001.3552710.2697000.5492000.2391000.1347000.2299000.5192000.2748000.4127000.4376000.2454000.4172000.7112000.5232000.6441000.2721000.4405000.1667000.3415000.1377000.3738000.2490000.388000
251.0497001.3551800.2725000.5479000.2438000.1497000.2299000.5231000.2725000.4157000.4422000.2562000.4202000.7058000.5239000.6396000.2717000.4519000.1663000.3469000.1537000.3831000.2470000.389300
261.0497001.3493370.2756000.5563000.2464000.1467000.2348000.5163000.2742000.4183000.4409000.2487000.4189000.7058000.5232000.6365000.2747000.4405000.1724000.3491000.1556000.3846000.2523000.393800
271.0497001.3507820.2752000.5487000.2468000.1473000.2364000.5272000.2801000.4162000.4426000.2534000.4240000.7103000.5266000.6401000.2732000.4456000.1670000.3469000.1601000.3877000.2492000.392900
281.0497001.3465330.2770000.5528000.2529000.1474000.2400000.5276000.2809000.4209000.4441000.2555000.4245000.7112000.5302000.6468000.2774000.4418000.1709000.3469000.1566000.3892000.2496000.396000
290.9937001.3465750.2771000.5548000.2529000.1484000.2397000.5236000.2784000.4200000.4433000.2563000.4240000.7056000.5296000.6473000.2739000.4392000.1743000.3487000.1576000.3862000.2501000.395100
300.9937001.3464460.2774000.5547000.2527000.1479000.2408000.5236000.2788000.4204000.4433000.2561000.4242000.7055000.5301000.6468000.2756000.4405000.1745000.3487000.1573000.3862000.2492000.394200

If you have set `push_to_hub` to `True` in the `training_args`, the training checkpoints are pushed to the Hugging Face Hub. Upon training completion, push the final model to the Hub as well by calling the [`~transformers.Trainer.push_to_hub`] method. @@ -394,187 +1441,91 @@ Hugging Face Hub. Upon training completion, push the final model to the Hub as w ``` ## Evaluate -Object detection models are commonly evaluated with a set of COCO-style metrics. -You can use one of the existing metrics implementations, but here you'll use the one from `torchvision` to evaluate the final -model that you pushed to the Hub. - -To use the `torchvision` evaluator, you'll need to prepare a ground truth COCO dataset. The API to build a COCO dataset -requires the data to be stored in a certain format, so you'll need to save images and annotations to disk first. Just like -when you prepared your data for training, the annotations from the `cppe5["test"]` need to be formatted. However, images -should stay as they are. - -The evaluation step requires a bit of work, but it can be split in three major steps. -First, prepare the `cppe5["test"]` set: format the annotations and save the data to disk. ```py ->>> import json - - ->>> # format annotations the same as for training, no need for data augmentation ->>> def val_formatted_anns(image_id, objects): -... annotations = [] -... for i in range(0, len(objects["id"])): -... new_ann = { -... "id": objects["id"][i], -... "category_id": objects["category"][i], -... "iscrowd": 0, -... "image_id": image_id, -... "area": objects["area"][i], -... "bbox": objects["bbox"][i], -... } -... annotations.append(new_ann) - -... return annotations - - ->>> # Save images and annotations into the files torchvision.datasets.CocoDetection expects ->>> def save_cppe5_annotation_file_images(cppe5): -... output_json = {} -... path_output_cppe5 = f"{os.getcwd()}/cppe5/" - -... if not os.path.exists(path_output_cppe5): -... os.makedirs(path_output_cppe5) - -... path_anno = os.path.join(path_output_cppe5, "cppe5_ann.json") -... categories_json = [{"supercategory": "none", "id": id, "name": id2label[id]} for id in id2label] -... output_json["images"] = [] -... output_json["annotations"] = [] -... for example in cppe5: -... ann = val_formatted_anns(example["image_id"], example["objects"]) -... output_json["images"].append( -... { -... "id": example["image_id"], -... "width": example["image"].width, -... "height": example["image"].height, -... "file_name": f"{example['image_id']}.png", -... } -... ) -... output_json["annotations"].extend(ann) -... output_json["categories"] = categories_json - -... with open(path_anno, "w") as file: -... json.dump(output_json, file, ensure_ascii=False, indent=4) - -... for im, img_id in zip(cppe5["image"], cppe5["image_id"]): -... path_img = os.path.join(path_output_cppe5, f"{img_id}.png") -... im.save(path_img) - -... return path_output_cppe5, path_anno +>>> from pprint import pprint + +>>> metrics = trainer.evaluate(eval_dataset=cppe5["test"], metric_key_prefix="test") +>>> pprint(metrics) +{'epoch': 30.0, + 'test_loss': 1.0877351760864258, + 'test_map': 0.4116, + 'test_map_50': 0.741, + 'test_map_75': 0.3663, + 'test_map_Coverall': 0.5937, + 'test_map_Face_Shield': 0.5863, + 'test_map_Gloves': 0.3416, + 'test_map_Goggles': 0.1468, + 'test_map_Mask': 0.3894, + 'test_map_large': 0.5637, + 'test_map_medium': 0.3257, + 'test_map_small': 0.3589, + 'test_mar_1': 0.323, + 'test_mar_10': 0.5237, + 'test_mar_100': 0.5587, + 'test_mar_100_Coverall': 0.6756, + 'test_mar_100_Face_Shield': 0.7294, + 'test_mar_100_Gloves': 0.4721, + 'test_mar_100_Goggles': 0.4125, + 'test_mar_100_Mask': 0.5038, + 'test_mar_large': 0.7283, + 'test_mar_medium': 0.4901, + 'test_mar_small': 0.4469, + 'test_runtime': 1.6526, + 'test_samples_per_second': 17.548, + 'test_steps_per_second': 2.42} ``` -Next, prepare an instance of a `CocoDetection` class that can be used with `cocoevaluator`. - -```py ->>> import torchvision - - ->>> class CocoDetection(torchvision.datasets.CocoDetection): -... def __init__(self, img_folder, image_processor, ann_file): -... super().__init__(img_folder, ann_file) -... self.image_processor = image_processor - -... def __getitem__(self, idx): -... # read in PIL image and target in COCO format -... img, target = super(CocoDetection, self).__getitem__(idx) - -... # preprocess image and target: converting target to DETR format, -... # resizing + normalization of both image and target) -... image_id = self.ids[idx] -... target = {"image_id": image_id, "annotations": target} -... encoding = self.image_processor(images=img, annotations=target, return_tensors="pt") -... pixel_values = encoding["pixel_values"].squeeze() # remove batch dimension -... target = encoding["labels"][0] # remove batch dimension +These results can be further improved by adjusting the hyperparameters in [`TrainingArguments`]. Give it a go! -... return {"pixel_values": pixel_values, "labels": target} - - ->>> image_processor = AutoImageProcessor.from_pretrained("devonho/detr-resnet-50_finetuned_cppe5") - ->>> path_output_cppe5, path_anno = save_cppe5_annotation_file_images(cppe5["test"]) ->>> test_ds_coco_format = CocoDetection(path_output_cppe5, image_processor, path_anno) -``` +## Inference -Finally, load the metrics and run the evaluation. +Now that you have finetuned a model, evaluated it, and uploaded it to the Hugging Face Hub, you can use it for inference. ```py ->>> import evaluate ->>> from tqdm import tqdm +>>> import torch +>>> import requests +>>> import numpy as np +>>> import albumentations as A ->>> model = AutoModelForObjectDetection.from_pretrained("devonho/detr-resnet-50_finetuned_cppe5") ->>> module = evaluate.load("ybelkada/cocoevaluate", coco=test_ds_coco_format.coco) ->>> val_dataloader = torch.utils.data.DataLoader( -... test_ds_coco_format, batch_size=8, shuffle=False, num_workers=4, collate_fn=collate_fn -... ) +>>> from PIL import Image +>>> from transformers import AutoImageProcessor, AutoModelForObjectDetection ->>> device = torch.device("cuda") if torch.cuda.is_available() else "cpu" ->>> model.to(device) +>>> url = "https://images.pexels.com/photos/8413299/pexels-photo-8413299.jpeg?auto=compress&cs=tinysrgb&w=630&h=375&dpr=2" +>>> image = Image.open(requests.get(url, stream=True).raw) ->>> with torch.no_grad(): -... for idx, batch in enumerate(tqdm(val_dataloader)): -... pixel_values = batch["pixel_values"].to(device) -... pixel_mask = batch["pixel_mask"].to(device) - -... labels = [ -... {k: v for k, v in t.items()} for t in batch["labels"] -... ] # these are in DETR format, resized + normalized - -... # forward pass -... outputs = model(pixel_values=pixel_values, pixel_mask=pixel_mask) - -... orig_target_sizes = torch.stack([target["orig_size"] for target in labels], dim=0) -... # convert outputs of model to Pascal VOC format (xmin, ymin, xmax, ymax) -... results = image_processor.post_process_object_detection(outputs, threshold=0, target_sizes=orig_target_sizes) -... -... module.add(prediction=results, reference=labels) -... del batch - ->>> results = module.compute() ->>> print(results) -Accumulating evaluation results... -DONE (t=0.08s). -IoU metric: bbox - Average Precision (AP) @[ IoU=0.50:0.95 | area= all | maxDets=100 ] = 0.352 - Average Precision (AP) @[ IoU=0.50 | area= all | maxDets=100 ] = 0.681 - Average Precision (AP) @[ IoU=0.75 | area= all | maxDets=100 ] = 0.292 - Average Precision (AP) @[ IoU=0.50:0.95 | area= small | maxDets=100 ] = 0.168 - Average Precision (AP) @[ IoU=0.50:0.95 | area=medium | maxDets=100 ] = 0.208 - Average Precision (AP) @[ IoU=0.50:0.95 | area= large | maxDets=100 ] = 0.429 - Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets= 1 ] = 0.274 - Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets= 10 ] = 0.484 - Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets=100 ] = 0.501 - Average Recall (AR) @[ IoU=0.50:0.95 | area= small | maxDets=100 ] = 0.191 - Average Recall (AR) @[ IoU=0.50:0.95 | area=medium | maxDets=100 ] = 0.323 - Average Recall (AR) @[ IoU=0.50:0.95 | area= large | maxDets=100 ] = 0.590 -``` -These results can be further improved by adjusting the hyperparameters in [`~transformers.TrainingArguments`]. Give it a go! +>>> # Define transformations for inference +>>> resize_and_pad = A.Compose([ +... A.LongestMaxSize(max_size=max_size), +... A.PadIfNeeded(max_size, max_size, border_mode=0, value=(128, 128, 128), position="top_left"), +... ]) -## Inference -Now that you have finetuned a DETR model, evaluated it, and uploaded it to the Hugging Face Hub, you can use it for inference. -The simplest way to try out your finetuned model for inference is to use it in a [`Pipeline`]. Instantiate a pipeline -for object detection with your model, and pass an image to it: +>>> # This one is for visualization with no padding +>>> resize_only = A.Compose([ +... A.LongestMaxSize(max_size=max_size), +... ]) +``` +Load model and image processor from the Hugging Face Hub (skip to use already trained in this session): ```py ->>> from transformers import pipeline ->>> import requests - ->>> url = "https://i.imgur.com/2lnWoly.jpg" ->>> image = Image.open(requests.get(url, stream=True).raw) +>>> device = "cuda" +>>> model_repo = "qubvel-hf/detr_finetuned_cppe5" ->>> obj_detector = pipeline("object-detection", model="devonho/detr-resnet-50_finetuned_cppe5") ->>> obj_detector(image) +>>> image_processor = AutoImageProcessor.from_pretrained(model_repo) +>>> model = AutoModelForObjectDetection.from_pretrained(model_repo) +>>> model = model.to(device) ``` -You can also manually replicate the results of the pipeline if you'd like: +And detect bounding boxes: ```py ->>> image_processor = AutoImageProcessor.from_pretrained("devonho/detr-resnet-50_finetuned_cppe5") ->>> model = AutoModelForObjectDetection.from_pretrained("devonho/detr-resnet-50_finetuned_cppe5") +>>> np_preprocessed_image = resize_and_pad(image=np.array(image))["image"] >>> with torch.no_grad(): -... inputs = image_processor(images=image, return_tensors="pt") -... outputs = model(**inputs) -... target_sizes = torch.tensor([image.size[::-1]]) -... results = image_processor.post_process_object_detection(outputs, threshold=0.5, target_sizes=target_sizes)[0] +... inputs = image_processor(images=[np_preprocessed_image], return_tensors="pt") +... outputs = model(inputs["pixel_values"].to(device)) +... target_sizes = torch.tensor([np_preprocessed_image.shape[:2]]) +... results = image_processor.post_process_object_detection(outputs, threshold=0.3, target_sizes=target_sizes)[0] >>> for score, label, box in zip(results["scores"], results["labels"], results["boxes"]): ... box = [round(i, 2) for i in box.tolist()] @@ -582,13 +1533,19 @@ You can also manually replicate the results of the pipeline if you'd like: ... f"Detected {model.config.id2label[label.item()]} with confidence " ... f"{round(score.item(), 3)} at location {box}" ... ) -Detected Coverall with confidence 0.566 at location [1215.32, 147.38, 4401.81, 3227.08] -Detected Mask with confidence 0.584 at location [2449.06, 823.19, 3256.43, 1413.9] +Detected Gloves with confidence 0.683 at location [244.58, 124.33, 300.35, 185.13] +Detected Mask with confidence 0.517 at location [143.73, 64.58, 219.57, 125.89] +Detected Gloves with confidence 0.425 at location [179.15, 155.57, 262.4, 226.35] +Detected Coverall with confidence 0.407 at location [307.13, -1.18, 477.82, 318.06] +Detected Coverall with confidence 0.391 at location [68.61, 126.66, 309.03, 318.89] ``` Let's plot the result: + ```py ->>> draw = ImageDraw.Draw(image) +>>> resized_image = resize_only(image=np.array(image))["image"] +>>> resized_image = Image.fromarray(resized_image) +>>> draw = ImageDraw.Draw(resized_image) >>> for score, label, box in zip(results["scores"], results["labels"], results["boxes"]): ... box = [round(i, 2) for i in box.tolist()] @@ -596,9 +1553,9 @@ Let's plot the result: ... draw.rectangle((x, y, x2, y2), outline="red", width=1) ... draw.text((x, y), model.config.id2label[label.item()], fill="white") ->>> image +>>> resized_image ```

- Object detection result on a new image + Object detection result on a new image