transformers_doc/ja/object_detection.ipynb (874 lines of code) (raw):
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Object detection"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"オブジェクト検出は、画像内のインスタンス (人間、建物、車など) を検出するコンピューター ビジョン タスクです。物体検出モデルは画像を入力および出力として受け取ります\n",
"検出されたオブジェクトの境界ボックスと関連するラベルの座標。画像には複数のオブジェクトを含めることができます。\n",
"それぞれに独自の境界ボックスとラベルがあり (例: 車と建物を持つことができます)、各オブジェクトは\n",
"画像のさまざまな部分に存在する必要があります (たとえば、画像には複数の車が含まれている可能性があります)。\n",
"このタスクは、歩行者、道路標識、信号機などを検出するために自動運転で一般的に使用されます。\n",
"他のアプリケーションには、画像内のオブジェクトのカウント、画像検索などが含まれます。\n",
"\n",
"このガイドでは、次の方法を学習します。\n",
"\n",
" 1. Finetune [DETR](https://huggingface.co/docs/transformers/model_doc/detr)、畳み込みアルゴリズムを組み合わせたモデル\n",
" [CPPE-5](https://huggingface.co/datasets/cppe-5) 上のエンコーダー/デコーダー トランスフォーマーを備えたバックボーン\n",
" データセット。\n",
" 2. 微調整したモデルを推論に使用します。\n",
"\n",
"<Tip>\n",
"\n",
"このタスクと互換性のあるすべてのアーキテクチャとチェックポイントを確認するには、[タスクページ](https://huggingface.co/tasks/object-detection) を確認することをお勧めします。\n",
"\n",
"</Tip>\n",
"\n",
"始める前に、必要なライブラリがすべてインストールされていることを確認してください。\n",
"\n",
"\n",
"```bash\n",
"pip install -q datasets transformers evaluate timm albumentations\n",
"```\n",
"\n",
"🤗 データセットを使用して Hugging Face Hub からデータセットをロードし、🤗 トランスフォーマーを使用してモデルをトレーニングします。\n",
"データを増強するための`albumentations`。 `timm` は現在、DETR モデルの畳み込みバックボーンをロードするために必要です。\n",
"\n",
"モデルをコミュニティと共有することをお勧めします。 Hugging Face アカウントにログインして、ハブにアップロードします。\n",
"プロンプトが表示されたら、トークンを入力してログインします。"
]
},
{
"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": [
"[CPPE-5 データセット](https://huggingface.co/datasets/cppe-5) には、次の画像が含まれています。\n",
"新型コロナウイルス感染症のパンデミックにおける医療用個人保護具 (PPE) を識別する注釈。\n",
"\n",
"データセットをロードすることから始めます。"
]
},
{
"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": [
"このデータセットには、1000 枚の画像を含むトレーニング セットと 29 枚の画像を含むテスト セットがすでに付属していることがわかります。\n",
"\n",
"データに慣れるために、例がどのようなものかを調べてください。"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"{'image_id': 15,\n",
" 'image': <PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=943x663 at 0x7F9EC9E77C10>,\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": [
"データセット内の例には次のフィールドがあります。\n",
"- `image_id`: サンプルの画像ID\n",
"- `image`: 画像を含む `PIL.Image.Image` オブジェクト\n",
"- `width`: 画像の幅\n",
"- `height`: 画像の高さ\n",
"- `objects`: 画像内のオブジェクトの境界ボックスのメタデータを含む辞書:\n",
" - `id`: アノテーションID\n",
" - `area`: 境界ボックスの領域\n",
" - `bbox`: オブジェクトの境界ボックス ([COCO 形式](https://albumentations.ai/docs/getting_started/bounding_boxes_augmentation/#coco) )\n",
" - `category`: オブジェクトのカテゴリー。可能な値には、`Coverall (0)`、`Face_Shield (1)`、`Gloves (2)`、`Goggles (3)`、および `Mask (4)` が含まれます。\n",
"\n",
"`bbox`フィールドが COCO 形式に従っていることに気づくかもしれません。これは DETR モデルが予期する形式です。\n",
"ただし、「オブジェクト」内のフィールドのグループ化は、DETR が必要とする注釈形式とは異なります。あなたはするであろう\n",
"このデータをトレーニングに使用する前に、いくつかの前処理変換を適用する必要があります。\n",
"\n",
"データをさらに深く理解するには、データセット内の例を視覚化します。"
]
},
{
"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]\n",
" class_idx = annotations[\"category\"][i]\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": [
"<div class=\"flex justify-center\">\n",
" <img src=\"https://i.imgur.com/TdaqPJO.png\" alt=\"CPPE-5 Image Example\"/>\n",
"</div>\n",
"\n",
"関連付けられたラベルを使用して境界ボックスを視覚化するには、データセットのメタデータからラベルを取得します。\n",
"`category`フィールド。\n",
"また、ラベル ID をラベル クラスにマッピングする辞書 (`id2label`) やその逆 (`label2id`) を作成することもできます。\n",
"これらは、後でモデルをセットアップするときに使用できます。これらのマップを含めると、共有した場合に他の人がモデルを再利用できるようになります。\n",
"ハグフェイスハブに取り付けます。\n",
"\n",
"データに慣れるための最後のステップとして、潜在的な問題がないかデータを調査します。データセットに関する一般的な問題の 1 つは、\n",
"オブジェクト検出は、画像の端を越えて「伸びる」境界ボックスです。このような「暴走」境界ボックスは、\n",
"トレーニング中にエラーが発生するため、この段階で対処する必要があります。このデータセットには、この問題に関する例がいくつかあります。\n",
"このガイドでは内容をわかりやすくするために、これらの画像をデータから削除します。"
]
},
{
"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": [
"モデルを微調整するには、事前トレーニングされたモデルに使用されるアプローチと正確に一致するように、使用する予定のデータを前処理する必要があります。\n",
"[AutoImageProcessor](https://huggingface.co/docs/transformers/main/ja/model_doc/auto#transformers.AutoImageProcessor) は、画像データを処理して `pixel_values`、`pixel_mask`、および\n",
"DETR モデルをトレーニングできる「ラベル」。画像プロセッサには、心配する必要のないいくつかの属性があります。\n",
"\n",
"- `image_mean = [0.485, 0.456, 0.406 ]`\n",
"- `image_std = [0.229, 0.224, 0.225]`\n",
"\n",
"これらは、モデルの事前トレーニング中に画像を正規化するために使用される平均と標準偏差です。これらの価値観は非常に重要です\n",
"事前にトレーニングされた画像モデルを推論または微調整するときに複製します。\n",
"\n",
"微調整するモデルと同じチェックポイントからイメージ プロセッサをインスタンス化します。"
]
},
{
"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": [
"画像を`image_processor`に渡す前に、2 つの前処理変換をデータセットに適用します。\n",
"- 画像の拡張\n",
"- DETR の期待に応えるための注釈の再フォーマット\n",
"\n",
"まず、モデルがトレーニング データにオーバーフィットしないようにするために、任意のデータ拡張ライブラリを使用して画像拡張を適用できます。ここでは[Albumentations](https://albumentations.ai/docs/)を使用します...\n",
"このライブラリは、変換が画像に影響を与え、それに応じて境界ボックスを更新することを保証します。\n",
"🤗 データセット ライブラリのドキュメントには、詳細な [物体検出用に画像を拡張する方法に関するガイド](https://huggingface.co/docs/datasets/object_detection) が記載されています。\n",
"例としてまったく同じデータセットを使用しています。ここでも同じアプローチを適用し、各画像のサイズを (480, 480) に変更します。\n",
"水平に反転して明るくします。"
]
},
{
"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": [
"`image_processor` は、注釈が次の形式であることを期待します: `{'image_id': int, 'annotations': list[Dict]}`,\n",
" ここで、各辞書は COCO オブジェクトの注釈です。 1 つの例として、注釈を再フォーマットする関数を追加してみましょう。\n",
"\n",
" ```py\n",
">>> 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\n",
"```\n",
"\n",
"これで、画像と注釈の変換を組み合わせてサンプルのバッチで使用できるようになりました。"
]
},
{
"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": [
"🤗 Datasets `with_transform` メソッドを使用して、この前処理関数をデータセット全体に適用します。この方法が適用されるのは、\n",
"データセットの要素を読み込むときに、その場で変換します。\n",
"\n",
"この時点で、データセットの例が変換後にどのようになるかを確認できます。テンソルが表示されるはずです\n",
"`pixel_values`、テンソルと `pixel_mask`、および `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": [
"個々の画像を正常に拡張し、それらの注釈を準備しました。ただし、前処理はそうではありません。\n",
"まだ完成しています。最後のステップでは、画像をバッチ処理するためのカスタム `collate_fn` を作成します。\n",
"画像 (現在は `pixel_values`) をバッチ内の最大の画像にパディングし、対応する `pixel_mask` を作成します\n",
"どのピクセルが実数 (1) で、どのピクセルがパディング (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(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": [
"前のセクションで重労働のほとんどを完了したので、モデルをトレーニングする準備が整いました。\n",
"このデータセット内の画像は、サイズを変更した後でも依然として非常に大きいです。これは、このモデルを微調整すると、\n",
"少なくとも 1 つの GPU が必要です。\n",
"\n",
"トレーニングには次の手順が含まれます。\n",
"1. 前処理と同じチェックポイントを使用して、[AutoModelForObjectDetection](https://huggingface.co/docs/transformers/main/ja/model_doc/auto#transformers.AutoModelForObjectDetection) でモデルを読み込みます。\n",
"2. [TrainingArguments](https://huggingface.co/docs/transformers/main/ja/main_classes/trainer#transformers.TrainingArguments) でトレーニング ハイパーパラメータを定義します。\n",
"3. トレーニング引数をモデル、データセット、画像プロセッサ、データ照合器とともに [Trainer](https://huggingface.co/docs/transformers/main/ja/main_classes/trainer#transformers.Trainer) に渡します。\n",
"4. [train()](https://huggingface.co/docs/transformers/main/ja/main_classes/trainer#transformers.Trainer.train) を呼び出してモデルを微調整します。\n",
"\n",
"前処理に使用したのと同じチェックポイントからモデルをロードするときは、必ず`label2id`を渡してください。\n",
"および `id2label` マップは、以前にデータセットのメタデータから作成したものです。さらに、`ignore_mismatched_sizes=True`を指定して、既存の分類頭部を新しい分類頭部に置き換えます。"
]
},
{
"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": [
"[TrainingArguments](https://huggingface.co/docs/transformers/main/ja/main_classes/trainer#transformers.TrainingArguments) で、`output_dir` を使用してモデルの保存場所を指定し、必要に応じてハイパーパラメーターを構成します。\n",
"画像列が削除されるため、未使用の列を削除しないことが重要です。画像列がないと、\n",
"`pixel_values` を作成できません。このため、`remove_unused_columns`を`False`に設定します。\n",
"ハブにプッシュしてモデルを共有したい場合は、`push_to_hub` を `True` に設定します (Hugging にサインインする必要があります)\n",
"顔に向かってモデルをアップロードします)。"
]
},
{
"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": [
"最後に、すべてをまとめて、[train()](https://huggingface.co/docs/transformers/main/ja/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",
" processing_class=image_processor,\n",
")\n",
"\n",
"trainer.train()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"`training_args`で`push_to_hub`を`True`に設定した場合、トレーニング チェックポイントは\n",
"ハグフェイスハブ。トレーニングが完了したら、[push_to_hub()](https://huggingface.co/docs/transformers/main/ja/main_classes/trainer#transformers.Trainer.push_to_hub) メソッドを呼び出して、最終モデルもハブにプッシュします。"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"trainer.push_to_hub()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Evaluate"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"物体検出モデルは通常、一連の <a href=\"https://cocodataset.org/#detection-eval\">COCO スタイルの指標</a>を使用して評価されます。\n",
"既存のメトリクス実装のいずれかを使用できますが、ここでは`torchvision`のメトリクス実装を使用して最終的なメトリクスを評価します。\n",
"ハブにプッシュしたモデル。\n",
"\n",
"`torchvision`エバリュエーターを使用するには、グラウンド トゥルース COCO データセットを準備する必要があります。 COCO データセットを構築するための API\n",
"データを特定の形式で保存する必要があるため、最初に画像と注釈をディスクに保存する必要があります。と同じように\n",
"トレーニング用にデータを準備するとき、`cppe5[\"test\"]` からの注釈をフォーマットする必要があります。ただし、画像\n",
"そのままでいるべきです。\n",
"\n",
"評価ステップには少し作業が必要ですが、大きく 3 つのステップに分けることができます。\n",
"まず、`cppe5[\"test\"]` セットを準備します。注釈をフォーマットし、データをディスクに保存します。"
]
},
{
"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": [
"次に、`cocoevaluator`で利用できる`CocoDetection`クラスのインスタンスを用意します。"
]
},
{
"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, image_processor, ann_file):\n",
" super().__init__(img_folder, ann_file)\n",
" self.image_processor = image_processor\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.image_processor(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(\"devonho/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": [
"最後に、メトリクスをロードして評価を実行します。"
]
},
{
"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.352\n",
" Average Precision (AP) @[ IoU=0.50 | area= all | maxDets=100 ] = 0.681\n",
" Average Precision (AP) @[ IoU=0.75 | area= all | maxDets=100 ] = 0.292\n",
" Average Precision (AP) @[ IoU=0.50:0.95 | area= small | maxDets=100 ] = 0.168\n",
" Average Precision (AP) @[ IoU=0.50:0.95 | area=medium | maxDets=100 ] = 0.208\n",
" Average Precision (AP) @[ IoU=0.50:0.95 | area= large | maxDets=100 ] = 0.429\n",
" Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets= 1 ] = 0.274\n",
" Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets= 10 ] = 0.484\n",
" Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets=100 ] = 0.501\n",
" Average Recall (AR) @[ IoU=0.50:0.95 | area= small | maxDets=100 ] = 0.191\n",
" Average Recall (AR) @[ IoU=0.50:0.95 | area=medium | maxDets=100 ] = 0.323\n",
" Average Recall (AR) @[ IoU=0.50:0.95 | area= large | maxDets=100 ] = 0.590"
]
},
"execution_count": null,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"import evaluate\n",
"from tqdm import tqdm\n",
"\n",
"model = AutoModelForObjectDetection.from_pretrained(\"devonho/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 Pascal VOC format (xmin, ymin, xmax, ymax)\n",
"\n",
" module.add(prediction=results, reference=labels)\n",
" del batch\n",
"\n",
"results = module.compute()\n",
"print(results)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"これらの結果は、[TrainingArguments](https://huggingface.co/docs/transformers/main/ja/main_classes/trainer#transformers.TrainingArguments) のハイパーパラメータを調整することでさらに改善できます。試してごらん!"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Inference"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"DETR モデルを微調整して評価し、Hugging Face Hub にアップロードしたので、それを推論に使用できます。\n",
"推論用に微調整されたモデルを試す最も簡単な方法は、それを [pipeline()](https://huggingface.co/docs/transformers/main/ja/main_classes/pipelines#transformers.pipeline) で使用することです。パイプラインをインスタンス化する\n",
"モデルを使用してオブジェクトを検出し、それに画像を渡します。"
]
},
{
"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=\"devonho/detr-resnet-50_finetuned_cppe5\")\n",
"obj_detector(image)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"必要に応じて、パイプラインの結果を手動で複製することもできます。"
]
},
{
"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"
}
],
"source": [
"image_processor = AutoImageProcessor.from_pretrained(\"devonho/detr-resnet-50_finetuned_cppe5\")\n",
"model = AutoModelForObjectDetection.from_pretrained(\"devonho/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": [
"結果をプロットしてみましょう:"
]
},
{
"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": [
"<div class=\"flex justify-center\">\n",
" <img src=\"https://i.imgur.com/4QZnf9A.png\" alt=\"Object detection result on a new image\"/>\n",
"</div>"
]
}
],
"metadata": {},
"nbformat": 4,
"nbformat_minor": 4
}