# Deformable DETR

[Deformable DETR](https://huggingface.co/papers/2010.04159)は、deformable attentionモジュールを用いることで、元の[DETR](./detr)を改善しています。このメカニズムは、参照点の周囲にある少数の主要なサンプリング点に選択的に注意を向けます。これにより、学習速度と精度が向上します。

<img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/deformable_detr_architecture.png"
alt="drawing" width="600"/>

 Deformable DETRのアーキテクチャ。元の論文から引用。

利用可能な Deformable DETR のチェックポイントはすべて、[SenseTime](https://huggingface.co/SenseTime) 組織の下で確認できます。

> [!TIP]
> このモデルは [nielsr](https://huggingface.co/nielsr) によって提供されました。
>
> 右側のサイドバーにある Deformable DETR モデルをクリックすると、Deformable DETR をさまざまな物体検出やセグメンテーションタスクに適用する例をさらに確認できます。

以下の例では、[Pipeline](/docs/transformers/v5.24.0/ja/main_classes/pipelines#transformers.Pipeline)と[AutoModel](/docs/transformers/v5.24.0/ja/model_doc/auto#transformers.AutoModel)クラスを使用してオブジェクト検出を実行する方法を示しています。

```python

from transformers import pipeline

pipeline = pipeline(
    "object-detection",
    model="SenseTime/deformable-detr",
    device_map=0
)

pipeline("http://images.cocodataset.org/val2017/000000039769.jpg")
```

```python
import requests
import torch
from PIL import Image

from transformers import AutoImageProcessor, AutoModelForObjectDetection

url = "http://images.cocodataset.org/val2017/000000039769.jpg"
image = Image.open(requests.get(url, stream=True).raw)

image_processor = AutoImageProcessor.from_pretrained("SenseTime/deformable-detr")
model = AutoModelForObjectDetection.from_pretrained("SenseTime/deformable-detr", device_map="auto")

# prepare image for the model
inputs = image_processor(images=image, return_tensors="pt").to(model.device)

with torch.no_grad():
    outputs = model(**inputs)

results = image_processor.post_process_object_detection(outputs, target_sizes=torch.tensor([image.size[::-1]]), threshold=0.3)

for result in results:
    for score, label_id, box in zip(result["scores"], result["labels"], result["boxes"]):
        score, label = score.item(), label_id.item()
        box = [round(i, 2) for i in box.tolist()]
        print(f"{model.config.id2label[label]}: {score:.2f} {box}")
```

## リソース

- カスタムデータセット上で[DeformableDetrForObjectDetection](/docs/transformers/v5.24.0/ja/model_doc/deformable_detr#transformers.DeformableDetrForObjectDetection)の推論とファインチューニングを行うには、この[ノートブック](https://github.com/NielsRogge/Transformers-Tutorials/tree/master/Deformable-DETR)のセットを参照してください。

## DeformableDetrImageProcessor[[transformers.DeformableDetrImageProcessor]]

#### transformers.DeformableDetrImageProcessor[[transformers.DeformableDetrImageProcessor]]

```python
transformers.DeformableDetrImageProcessor(**kwargs: *<class 'transformers.models.deformable_detr.image_processing_deformable_detr.DeformableDetrImageProcessorKwargs'>)
```

[ソース](https://github.com/huggingface/transformers/blob/v5.24.0/src/transformers/models/deformable_detr/image_processing_deformable_detr.py#L271)

**パラメータ:**

do_convert_rgb (`bool`, *kwargs*, *optional*) : 画像を RGB に変換するかどうか。

do_resize (`bool`, *kwargs*, *任意*, デフォルトは `True`) : 画像をリサイズするかどうか。

size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*、デフォルトは `{'shortest_edge' : 800, 'longest_edge': 1333}`): モデルへの最大入力次元を記述します。

default_to_square (`bool`, *kwargs*, *optional*, デフォルトは `False`) : size が int の場合、リサイズ時に正方形の画像をデフォルトとするかどうか。

crop_size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*) : `center_crop` を適用した後の出力画像のサイズ。

resample (`Annotated[Union[int, PILImageResampling, NoneType], None]`, *kwargs*、デフォルト値は`2`) : 画像のリサイズ時に使用するリサンプリングフィルタです。これは列挙型`PILImageResampling`のいずれかになります。`do_resize`が`True`に設定されている場合のみ、効果が現れます。

do_rescale (`bool`, *kwargs*, *optional*, デフォルトは `True`) : 画像をリスケールするかどうか。

rescale_factor (`float`, *kwargs*, *optional*, デフォルトは `0.00392156862745098`) : `do_rescale` が `True` に設定されている場合、画像をリスケールするための係数。

do_normalize (`bool`, *kwargs*, *optional*, デフォルトは `True`) : 画像を正規化するかどうかを指定します。

image_mean (`Union[float, list[float], tuple[float, ...]]`, *kwargs*, *optional*, デフォルトは `[0.485, 0.456, 0.406]`) : 正規化に使用する画像の平均値です。`do_normalize` が `True` に設定されている場合のみ有効です。

image_std (`Union[float, list[float], tuple[float, ...]]`, *kwargs*, *optional*, デフォルトは `[0.229, 0.224, 0.225]`) : 正規化に使用する画像の標準偏差。`do_normalize` が `True` に設定されている場合のみ有効です。

do_pad (`bool`, *kwargs*, *optional*, デフォルトは `True`) : 画像にパディングを適用するかどうか。パディングは、バッチ内の最大サイズに合わせるか、画像ごとに固定の正方形サイズに合わせるかのいずれかで行われます。正確なパディング戦略はモデルによって異なります。

pad_size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*) : 画像をパディングするサイズを`{"height": int, "width" int}`で指定します。前処理に提供されたすべての画像サイズより大きい必要があります。`pad_size`が指定されない場合、バッチ内の最大の幅と高さにパディングされます。`do_pad=True.`の場合にのみ適用されます。

do_center_crop (`bool`, *kwargs*, *optional*) : 画像を中央クロップするかどうか。

data_format (`Union[str, ~image_utils.ChannelDimension]`、*kwargs*、*optional*) : 対応するのは `ChannelDimension.FIRST` のみです。slow processors との互換性のために追加されました。

input_data_format (`Union[str, ~image_utils.ChannelDimension]`, *kwargs*, *任意*) : 入力画像のチャネル次元の形式です。設定されていない場合、入力画像からチャネル次元の形式が推論されます。以下のいずれかになります: - `"channels_first"` または `ChannelDimension.FIRST`: (num_channels, height, width) 形式の画像。 - `"channels_last"` または `ChannelDimension.LAST`: (height, width, num_channels) 形式の画像。 - `"none"` または `ChannelDimension.NONE`: (height, width) 形式の画像。

device (`Annotated[Union[str, torch.device, NoneType], None]`, *kwargs*) : 動画を処理するデバイスです。未設定の場合、入力動画からデバイスが推論されます。

return_tensors (`Annotated[str | ~utils.generic.TensorType | None, None]`, *kwargs*) : `'pt'`に設定されている場合はスタックされたテンソルを返し、それ以外の場合はテンソルのリストを返します。

disable_grouping (`bool`, *kwargs*, *optional*) : 画像をサイズごとにグループ化してバッチ処理するのではなく、個別に処理するためにグループ化を無効にするかどうかを指定します。None の場合、画像が CPU にある場合は True、それ以外の場合は False に設定されます。この選択は、https://github.com/huggingface/transformers/pull/38157 に詳しく記載されている実証的な観察に基づいています。

image_seq_length (`int`, *kwargs*, *任意*) : 入力内の各画像に使用される画像トークンの数です。後方互換性のために追加されましたが、将来のモデルではプロセッサの属性として設定されるべきです。

format (`str`、*kwargs*、*任意*、デフォルトは`AnnotationFormat.COCO_DETECTION`) : アノテーションのデータ形式。"coco_detection"または"coco_panoptic"のいずれかです。

do_convert_annotations (`bool`, *kwargs*, *optional*, デフォルトは `True`) : アノテーションを DEFORMABLE_DETR モデルが期待する形式に変換するかどうかを制御します。バウンディングボックスを `(center_x, center_y, width, height)` の形式に変換し、値の範囲を `[0, 1]` にします。`preprocess` メソッドの `do_convert_annotations` パラメータによって上書きできます。

DeformableDetrImageProcessor の画像プロセッサを構築します。

#### preprocess[[transformers.DeformableDetrImageProcessor.preprocess]]

```python
preprocess(images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']], annotations: dict[str, int | str | list[dict]] | list[dict[str, int | str | list[dict]]] | None = None, return_segmentation_masks: bool | None = None, masks_path: str | pathlib.Path | None = None, **kwargs: *<class 'transformers.models.deformable_detr.image_processing_deformable_detr.DeformableDetrImageProcessorKwargs'>)
```

[ソース](https://github.com/huggingface/transformers/blob/v5.24.0/src/transformers/models/deformable_detr/image_processing_deformable_detr.py#L526)

**パラメータ:**

images (`Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]]`) : 前処理対象の画像。ピクセル値が 0 から 255 の範囲にある単一の画像またはバッチの画像を想定しています。ピクセル値が 0 から 1 の範囲にある画像を渡す場合は、`do_rescale=False` を設定してください。

annotations (`AnnotationType` または `list[AnnotationType]`、*任意*) : 画像に適用されるパディングに従って変換するアノテーション。

return_segmentation_masks (`bool`、*任意*、デフォルトは `self.return_segmentation_masks`) : セグメンテーションマスクを返すかどうか。

masks_path (`str` または `pathlib.Path`、*省略可能*) : セグメンテーションマスクを含むディレクトリへのパス。

do_convert_rgb (`bool`, *kwargs*, *optional*) : 画像を RGB に変換するかどうか。

do_resize (`bool`, *kwargs*, *optional*) : 画像をリサイズするかどうか。

size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*) : モデルへの最大入力次元を記述します。

default_to_square (`bool`, *kwargs*, *optional*) : size が int の場合、リサイズ時に正方形の画像をデフォルトとするかどうか。

crop_size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*) : `center_crop` を適用した後の出力画像のサイズ。

resample (`Annotated[Union[int, PILImageResampling, NoneType], None]`, *kwargs*) : 画像をリサイズする場合に使用するリサンプリングフィルタ。`PILImageResampling` の列挙型のいずれかです。`do_resize` が `True` に設定されている場合のみ有効です。

do_rescale (`bool`, *kwargs*, *任意*) : 画像をリスケールするかどうか。

rescale_factor (`float`, *kwargs*, *optional*) : `do_rescale` が `True` に設定されている場合、画像をリサイズするためのリスケール係数。

do_normalize (`bool`, *kwargs*, *optional*) : 画像を正規化するかどうかを指定します。

image_mean (`Union[float, list[float], tuple[float, ...]]`, *kwargs*, *optional*) : 正規化に使用する画像の平均値。`do_normalize` が `True` に設定されている場合のみ有効です。

image_std (`Union[float, list[float], tuple[float, ...]]`, *kwargs*, *optional*) : 正規化に使用する画像の標準偏差。`do_normalize` が `True` に設定されている場合のみ有効です。

do_pad (`bool`, *kwargs*, *任意*) : 画像にパディングを適用するかどうか。パディングは、バッチ内の最大サイズに合わせるか、画像ごとに固定の正方形サイズに合わせるかのいずれかで行われます。正確なパディング戦略はモデルによって異なります。

pad_size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*) : 画像をパディングするサイズを`{"height": int, "width" int}`で指定します。前処理に提供されたすべての画像サイズより大きい必要があります。`pad_size`が指定されない場合、バッチ内の最大の幅と高さにパディングされます。`do_pad=True.`の場合にのみ適用されます。

do_center_crop (`bool`, *kwargs*, *optional*) : 画像を中央クロップするかどうか。

data_format (`Union[str, ~image_utils.ChannelDimension]`、*kwargs*、*optional*) : 対応するのは `ChannelDimension.FIRST` のみです。slow processors との互換性のために追加されました。

input_data_format (`Union[str, ~image_utils.ChannelDimension]`, *kwargs*, *任意*) : 入力画像のチャネル次元の形式です。設定されていない場合、入力画像からチャネル次元の形式が推論されます。以下のいずれかになります: - `"channels_first"` または `ChannelDimension.FIRST`: (num_channels, height, width) 形式の画像。 - `"channels_last"` または `ChannelDimension.LAST`: (height, width, num_channels) 形式の画像。 - `"none"` または `ChannelDimension.NONE`: (height, width) 形式の画像。

device (`Annotated[Union[str, torch.device, NoneType], None]`, *kwargs*) : 動画を処理するデバイスです。未設定の場合、入力動画からデバイスが推論されます。

return_tensors (`Annotated[str | ~utils.generic.TensorType | None, None]`, *kwargs*) : `'pt'`に設定されている場合はスタックされたテンソルを返し、それ以外の場合はテンソルのリストを返します。

disable_grouping (`bool`, *kwargs*, *optional*) : 画像をサイズごとにグループ化してバッチ処理するのではなく、個別に処理するためにグループ化を無効にするかどうかを指定します。None の場合、画像が CPU にある場合は True、それ以外の場合は False に設定されます。この選択は、https://github.com/huggingface/transformers/pull/38157 に詳しく記載されている実証的な観察に基づいています。

image_seq_length (`int`, *kwargs*, *任意*) : 入力内の各画像に使用される画像トークンの数です。後方互換性のために追加されましたが、将来のモデルではプロセッサの属性として設定されるべきです。

format (`str`、*kwargs*、*任意*、デフォルトは`AnnotationFormat.COCO_DETECTION`) : アノテーションのデータ形式。"coco_detection"または"coco_panoptic"のいずれかです。

do_convert_annotations (`bool`, *kwargs*, *optional*, デフォルトは `True`) : アノテーションを DEFORMABLE_DETR モデルが期待する形式に変換するかどうかを制御します。バウンディングボックスを `(center_x, center_y, width, height)` の形式に変換し、値の範囲を `[0, 1]` にします。`preprocess` メソッドの `do_convert_annotations` パラメータによって上書きできます。

**戻り値:** `~image_processing_base.BatchFeature`

- **data** (`dict`) -- __call__ メソッドによって返されるリスト/配列/テンソルの辞書（'pixel_values' など）。
- **tensor_type** (`Union[None, str, TensorType]`、*省略可*) -- 初期化時に PyTorch/Numpy の Tensor 内の整数リストを変換するために、ここで tensor_type を指定できます。

#### post_process_object_detection[[transformers.DeformableDetrImageProcessor.post_process_object_detection]]

```python
post_process_object_detection(outputs, threshold: float = 0.5, target_sizes: transformers.utils.generic.TensorType | list[tuple] = None, top_k: int = 100)
```

[ソース](https://github.com/huggingface/transformers/blob/v5.24.0/src/transformers/models/deformable_detr/image_processing_deformable_detr.py#L667)

**パラメータ:**

outputs (`DetrObjectDetectionOutput`) : モデルの生出力。

threshold (`float`, *任意*) : オブジェクト検出の予測を保持するためのスコアしきい値。

target_sizes (`torch.Tensor` または `list[tuple[int, int]]`、*任意*) : バッチ内の各画像のターゲットサイズ（高さ、幅）を含む、形状 `(batch_size, 2)` の Tensor またはタプルのリスト（`tuple[int, int]`）。None の場合、予測結果はリサイズされません。

top_k (`int`、*optional*、デフォルトは 100) : 閾値によるフィルタリングの前に、上位 k 個のバウンディングボックスのみを保持します。

**戻り値:** `list[Dict]`

モデルが予測した、バッチ内の各画像のスコア、ラベル、ボックスをそれぞれ含む辞書のリスト。

[DeformableDetrForObjectDetection](/docs/transformers/v5.24.0/ja/model_doc/deformable_detr#transformers.DeformableDetrForObjectDetection)の生出力を、(top_left_x, top_left_y, bottom_right_x, bottom_right_y)形式の最終バウンディングボックスに変換します。PyTorchのみサポートしています。

## DeformableDetrImageProcessorPil[[transformers.DeformableDetrImageProcessorPil]]

#### transformers.DeformableDetrImageProcessorPil[[transformers.DeformableDetrImageProcessorPil]]

```python
transformers.DeformableDetrImageProcessorPil(**kwargs: *<class 'transformers.models.deformable_detr.image_processing_pil_deformable_detr.DeformableDetrImageProcessorKwargs'>)
```

[ソース](https://github.com/huggingface/transformers/blob/v5.24.0/src/transformers/models/deformable_detr/image_processing_pil_deformable_detr.py#L263)

**パラメータ:**

do_convert_rgb (`bool`, *kwargs*, *optional*) : 画像を RGB に変換するかどうか。

do_resize (`bool`, *kwargs*, *任意*, デフォルトは `True`) : 画像をリサイズするかどうか。

size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*、デフォルトは `{'shortest_edge' : 800, 'longest_edge': 1333}`): モデルへの最大入力次元を記述します。

default_to_square (`bool`, *kwargs*, *optional*, デフォルトは `False`) : size が int の場合、リサイズ時に正方形の画像をデフォルトとするかどうか。

crop_size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*) : `center_crop` を適用した後の出力画像のサイズ。

resample (`Annotated[Union[int, PILImageResampling, NoneType], None]`, *kwargs*、デフォルト値は`2`) : 画像のリサイズ時に使用するリサンプリングフィルタです。これは列挙型`PILImageResampling`のいずれかになります。`do_resize`が`True`に設定されている場合のみ、効果が現れます。

do_rescale (`bool`, *kwargs*, *optional*, デフォルトは `True`) : 画像をリスケールするかどうか。

rescale_factor (`float`, *kwargs*, *optional*, デフォルトは `0.00392156862745098`) : `do_rescale` が `True` に設定されている場合、画像をリスケールするための係数。

do_normalize (`bool`, *kwargs*, *optional*, デフォルトは `True`) : 画像を正規化するかどうかを指定します。

image_mean (`Union[float, list[float], tuple[float, ...]]`, *kwargs*, *optional*, デフォルトは `[0.485, 0.456, 0.406]`) : 正規化に使用する画像の平均値です。`do_normalize` が `True` に設定されている場合のみ有効です。

image_std (`Union[float, list[float], tuple[float, ...]]`, *kwargs*, *optional*, デフォルトは `[0.229, 0.224, 0.225]`) : 正規化に使用する画像の標準偏差。`do_normalize` が `True` に設定されている場合のみ有効です。

do_pad (`bool`, *kwargs*, *optional*, デフォルトは `True`) : 画像にパディングを適用するかどうか。パディングは、バッチ内の最大サイズに合わせるか、画像ごとに固定の正方形サイズに合わせるかのいずれかで行われます。正確なパディング戦略はモデルによって異なります。

pad_size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*) : 画像をパディングするサイズを`{"height": int, "width" int}`で指定します。前処理に提供されたすべての画像サイズより大きい必要があります。`pad_size`が指定されない場合、バッチ内の最大の幅と高さにパディングされます。`do_pad=True.`の場合にのみ適用されます。

do_center_crop (`bool`, *kwargs*, *optional*) : 画像を中央クロップするかどうか。

data_format (`Union[str, ~image_utils.ChannelDimension]`、*kwargs*、*optional*) : 対応するのは `ChannelDimension.FIRST` のみです。slow processors との互換性のために追加されました。

input_data_format (`Union[str, ~image_utils.ChannelDimension]`, *kwargs*, *任意*) : 入力画像のチャネル次元の形式です。設定されていない場合、入力画像からチャネル次元の形式が推論されます。以下のいずれかになります: - `"channels_first"` または `ChannelDimension.FIRST`: (num_channels, height, width) 形式の画像。 - `"channels_last"` または `ChannelDimension.LAST`: (height, width, num_channels) 形式の画像。 - `"none"` または `ChannelDimension.NONE`: (height, width) 形式の画像。

device (`Annotated[Union[str, torch.device, NoneType], None]`, *kwargs*) : 動画を処理するデバイスです。未設定の場合、入力動画からデバイスが推論されます。

return_tensors (`Annotated[str | ~utils.generic.TensorType | None, None]`, *kwargs*) : `'pt'`に設定されている場合はスタックされたテンソルを返し、それ以外の場合はテンソルのリストを返します。

disable_grouping (`bool`, *kwargs*, *optional*) : 画像をサイズごとにグループ化してバッチ処理するのではなく、個別に処理するためにグループ化を無効にするかどうかを指定します。None の場合、画像が CPU にある場合は True、それ以外の場合は False に設定されます。この選択は、https://github.com/huggingface/transformers/pull/38157 に詳しく記載されている実証的な観察に基づいています。

image_seq_length (`int`, *kwargs*, *任意*) : 入力内の各画像に使用される画像トークンの数です。後方互換性のために追加されましたが、将来のモデルではプロセッサの属性として設定されるべきです。

format (`str`、*kwargs*、*任意*、デフォルトは`AnnotationFormat.COCO_DETECTION`) : アノテーションのデータ形式。"coco_detection"または"coco_panoptic"のいずれかです。

do_convert_annotations (`bool`, *kwargs*, *optional*, デフォルトは `True`) : アノテーションを DEFORMABLE_DETR モデルが期待する形式に変換するかどうかを制御します。バウンディングボックスを `(center_x, center_y, width, height)` の形式に変換し、値の範囲を `[0, 1]` にします。`preprocess` メソッドの `do_convert_annotations` パラメータによって上書きできます。

DeformableDetrImageProcessor の画像プロセッサを構築します。

#### preprocess[[transformers.DeformableDetrImageProcessorPil.preprocess]]

```python
preprocess(images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']], annotations: dict[str, int | str | list[dict]] | list[dict[str, int | str | list[dict]]] | None = None, return_segmentation_masks: bool | None = None, masks_path: str | pathlib.Path | None = None, **kwargs: *<class 'transformers.models.deformable_detr.image_processing_pil_deformable_detr.DeformableDetrImageProcessorKwargs'>)
```

[ソース](https://github.com/huggingface/transformers/blob/v5.24.0/src/transformers/models/deformable_detr/image_processing_pil_deformable_detr.py#L531)

**パラメータ:**

images (`Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]]`) : 前処理対象の画像。ピクセル値が 0 から 255 の範囲にある単一の画像またはバッチの画像を想定しています。ピクセル値が 0 から 1 の範囲にある画像を渡す場合は、`do_rescale=False` を設定してください。

annotations (`AnnotationType` または `list[AnnotationType]`、*任意*) : 画像に適用されるパディングに従って変換するアノテーション。

return_segmentation_masks (`bool`、*任意*、デフォルトは `self.return_segmentation_masks`) : セグメンテーションマスクを返すかどうか。

masks_path (`str` または `pathlib.Path`、*省略可能*) : セグメンテーションマスクを含むディレクトリへのパス。

do_convert_rgb (`bool`, *kwargs*, *optional*) : 画像を RGB に変換するかどうか。

do_resize (`bool`, *kwargs*, *optional*) : 画像をリサイズするかどうか。

size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*) : モデルへの最大入力次元を記述します。

default_to_square (`bool`, *kwargs*, *optional*) : size が int の場合、リサイズ時に正方形の画像をデフォルトとするかどうか。

crop_size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*) : `center_crop` を適用した後の出力画像のサイズ。

resample (`Annotated[Union[int, PILImageResampling, NoneType], None]`, *kwargs*) : 画像をリサイズする場合に使用するリサンプリングフィルタ。`PILImageResampling` の列挙型のいずれかです。`do_resize` が `True` に設定されている場合のみ有効です。

do_rescale (`bool`, *kwargs*, *任意*) : 画像をリスケールするかどうか。

rescale_factor (`float`, *kwargs*, *optional*) : `do_rescale` が `True` に設定されている場合、画像をリサイズするためのリスケール係数。

do_normalize (`bool`, *kwargs*, *optional*) : 画像を正規化するかどうかを指定します。

image_mean (`Union[float, list[float], tuple[float, ...]]`, *kwargs*, *optional*) : 正規化に使用する画像の平均値。`do_normalize` が `True` に設定されている場合のみ有効です。

image_std (`Union[float, list[float], tuple[float, ...]]`, *kwargs*, *optional*) : 正規化に使用する画像の標準偏差。`do_normalize` が `True` に設定されている場合のみ有効です。

do_pad (`bool`, *kwargs*, *任意*) : 画像にパディングを適用するかどうか。パディングは、バッチ内の最大サイズに合わせるか、画像ごとに固定の正方形サイズに合わせるかのいずれかで行われます。正確なパディング戦略はモデルによって異なります。

pad_size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*) : 画像をパディングするサイズを`{"height": int, "width" int}`で指定します。前処理に提供されたすべての画像サイズより大きい必要があります。`pad_size`が指定されない場合、バッチ内の最大の幅と高さにパディングされます。`do_pad=True.`の場合にのみ適用されます。

do_center_crop (`bool`, *kwargs*, *optional*) : 画像を中央クロップするかどうか。

data_format (`Union[str, ~image_utils.ChannelDimension]`、*kwargs*、*optional*) : 対応するのは `ChannelDimension.FIRST` のみです。slow processors との互換性のために追加されました。

input_data_format (`Union[str, ~image_utils.ChannelDimension]`, *kwargs*, *任意*) : 入力画像のチャネル次元の形式です。設定されていない場合、入力画像からチャネル次元の形式が推論されます。以下のいずれかになります: - `"channels_first"` または `ChannelDimension.FIRST`: (num_channels, height, width) 形式の画像。 - `"channels_last"` または `ChannelDimension.LAST`: (height, width, num_channels) 形式の画像。 - `"none"` または `ChannelDimension.NONE`: (height, width) 形式の画像。

device (`Annotated[Union[str, torch.device, NoneType], None]`, *kwargs*) : 動画を処理するデバイスです。未設定の場合、入力動画からデバイスが推論されます。

return_tensors (`Annotated[str | ~utils.generic.TensorType | None, None]`, *kwargs*) : `'pt'`に設定されている場合はスタックされたテンソルを返し、それ以外の場合はテンソルのリストを返します。

disable_grouping (`bool`, *kwargs*, *optional*) : 画像をサイズごとにグループ化してバッチ処理するのではなく、個別に処理するためにグループ化を無効にするかどうかを指定します。None の場合、画像が CPU にある場合は True、それ以外の場合は False に設定されます。この選択は、https://github.com/huggingface/transformers/pull/38157 に詳しく記載されている実証的な観察に基づいています。

image_seq_length (`int`, *kwargs*, *任意*) : 入力内の各画像に使用される画像トークンの数です。後方互換性のために追加されましたが、将来のモデルではプロセッサの属性として設定されるべきです。

format (`str`、*kwargs*、*任意*、デフォルトは`AnnotationFormat.COCO_DETECTION`) : アノテーションのデータ形式。"coco_detection"または"coco_panoptic"のいずれかです。

do_convert_annotations (`bool`, *kwargs*, *optional*, デフォルトは `True`) : アノテーションを DEFORMABLE_DETR モデルが期待する形式に変換するかどうかを制御します。バウンディングボックスを `(center_x, center_y, width, height)` の形式に変換し、値の範囲を `[0, 1]` にします。`preprocess` メソッドの `do_convert_annotations` パラメータによって上書きできます。

**戻り値:** `~image_processing_base.BatchFeature`

- **data** (`dict`) -- __call__ メソッドによって返されるリスト/配列/テンソルの辞書（'pixel_values' など）。
- **tensor_type** (`Union[None, str, TensorType]`、*省略可*) -- 初期化時に PyTorch/Numpy の Tensor 内の整数リストを変換するために、ここで tensor_type を指定できます。

#### post_process_object_detection[[transformers.DeformableDetrImageProcessorPil.post_process_object_detection]]

```python
post_process_object_detection(outputs, threshold: float = 0.5, target_sizes: transformers.utils.generic.TensorType | list[tuple] = None, top_k: int = 100)
```

[ソース](https://github.com/huggingface/transformers/blob/v5.24.0/src/transformers/models/deformable_detr/image_processing_pil_deformable_detr.py#L676)

**パラメータ:**

outputs (`DetrObjectDetectionOutput`) : モデルの生出力。

threshold (`float`, *任意*) : オブジェクト検出の予測を保持するためのスコアしきい値。

target_sizes (`torch.Tensor` または `list[tuple[int, int]]`、*任意*) : バッチ内の各画像のターゲットサイズ（高さ、幅）を含む、形状 `(batch_size, 2)` の Tensor またはタプルのリスト（`tuple[int, int]`）。None の場合、予測結果はリサイズされません。

top_k (`int`、*optional*、デフォルトは 100) : 閾値によるフィルタリングの前に、上位 k 個のバウンディングボックスのみを保持します。

**戻り値:** `list[Dict]`

モデルが予測した、バッチ内の各画像のスコア、ラベル、ボックスをそれぞれ含む辞書のリスト。

[DeformableDetrForObjectDetection](/docs/transformers/v5.24.0/ja/model_doc/deformable_detr#transformers.DeformableDetrForObjectDetection)の生出力を、(top_left_x, top_left_y, bottom_right_x, bottom_right_y)形式の最終バウンディングボックスに変換します。PyTorchのみサポートしています。

## DeformableDetrConfig[[transformers.DeformableDetrConfig]]

#### transformers.DeformableDetrConfig[[transformers.DeformableDetrConfig]]

```python
transformers.DeformableDetrConfig(transformers_version: str | None = None, architectures: list[str] | None = None, output_hidden_states: bool | None = False, return_dict: bool | None = True, dtype: str | torch.dtype | None = None, chunk_size_feed_forward: int = 0, id2label: dict[int, str] | dict[str, str] | None = None, label2id: dict[str, int] | dict[str, str] | None = None, problem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = None, is_encoder_decoder: bool = True, backbone_config: dict | transformers.configuration_utils.PreTrainedConfig | None = None, num_channels: int = 3, num_queries: int = 300, max_position_embeddings: int = 1024, encoder_layers: int = 6, encoder_ffn_dim: int = 1024, encoder_attention_heads: int = 8, decoder_layers: int = 6, decoder_ffn_dim: int = 1024, decoder_attention_heads: int = 8, encoder_layerdrop: float | int = 0.0, activation_function: str = 'relu', d_model: int = 256, dropout: float | int = 0.1, attention_dropout: float | int = 0.0, activation_dropout: float | int = 0.0, init_std: float = 0.02, init_xavier_std: float = 1.0, return_intermediate: bool = True, auxiliary_loss: bool = False, position_embedding_type: str = 'sine', dilation: bool | None = False, num_feature_levels: int = 4, encoder_n_points: int = 4, decoder_n_points: int = 4, two_stage: bool = False, two_stage_num_proposals: int = 300, with_box_refine: bool = False, class_cost: int = 1, bbox_cost: int = 5, giou_cost: int = 2, mask_loss_coefficient: int = 1, dice_loss_coefficient: int = 1, bbox_loss_coefficient: int = 5, giou_loss_coefficient: int = 2, eos_coefficient: float = 0.1, focal_alpha: float = 0.25, disable_custom_kernels: bool = False, tie_word_embeddings: bool = True)
```

[ソース](https://github.com/huggingface/transformers/blob/v5.24.0/src/transformers/models/deformable_detr/configuration_deformable_detr.py#L25)

**パラメータ:**

is_encoder_decoder (`bool`、*任意*、デフォルトは`True`) : モデルがエンコーダー/デコーダーとして使用されるかどうかを示します。

backbone_config (`Union[dict, ~configuration_utils.PreTrainedConfig]`、*optional*) : バックボーンモデルの設定です。

num_channels (`int`、*任意*、デフォルトは`3`) : 入力チャネル数。

num_queries (`int`、*任意*、デフォルト値は 300) : オブジェクトクエリ数、すなわち検出スロットの数です。これは、[DeformableDetrModel](/docs/transformers/v5.24.0/ja/model_doc/deformable_detr#transformers.DeformableDetrModel) が 1 枚の画像内で検出できるオブジェクトの最大数を示します。`two_stage` が `True` に設定されている場合は、代わりに `two_stage_num_proposals` が使用されます。

max_position_embeddings (`int`、*任意*、デフォルトは`1024`) : このモデルが使用される可能性のある最大シーケンス長。

encoder_layers (`int`、*任意*、デフォルトは`6`) : Transformerエンコーダーの隠れ層の数。設定されていない場合は、`num_layers`と同じ値が使用されます。

encoder_ffn_dim (`int`、*任意*、デフォルトは`1024`) : エンコーダー内の「intermediate」（feed-forward とも呼ばれる）層の次元数。

encoder_attention_heads (`int`、*optional*、デフォルトは`8`) : Transformer エンコーダーの各アテンション層におけるアテンションヘッドの数。

decoder_layers (`int`、*任意*、デフォルトは`6`) : Transformer デコーダーの隠れ層の数。設定されていない場合は、`num_layers` と同じ値が使用されます。

decoder_ffn_dim (`int`、*任意*、デフォルトは `1024`) : デコーダー内の「intermediate」（feed-forward と呼ばれることが多い）層の次元数。

decoder_attention_heads (`int`、*任意*、デフォルトは `8`) : Transformer デコーダーの各アテンション層におけるアテンションヘッドの数。

encoder_layerdrop (`Union[float, int]`、*任意*、デフォルトは`0.0`) : エンコーダーのLayerDrop確率です。詳細については、[LayerDrop論文](see https://huggingface.co/papers/1909.11556)を参照してください。

activation_function (`str`、*任意*、デフォルトは `relu`) : デコーダーで使用する非線形活性化関数（関数または文字列）。例えば、`"gelu"`、`"relu"`、`"silu"` など。

d_model (`int`、*任意*、デフォルトは`256`) : エンコーダ層とプーラー層のサイズ。

dropout (`Union[float, int]`、*任意*、デフォルトは`0.1`) : すべての dropout 層の比率。

attention_dropout (`Union[float, int]`、*任意*、デフォルトは`0.0`) : 注意確率のドロップアウト率。

activation_dropout (`Union[float, int]`、*任意*、デフォルトは`0.0`) : 全結合層内の活性化に対する dropout 率。

init_std (`float`、*任意*、デフォルトは`0.02`) : すべての重み行列を初期化するためのtruncated_normal_initializerの標準偏差です。

init_xavier_std (`float`、*任意*、デフォルトは `1.0`) : クロスアテンションの重みの Xavier 初期化に使用されるスケーリング係数です。

return_intermediate (`bool`, *任意*, デフォルトは True) : 中間状態を返すかどうか

auxiliary_loss (`bool`、*任意*、デフォルトは`False`) : 補助的なデコーディング損失（各デコーダ層での損失）を使用するかどうかを指定します。

position_embedding_type (`str`、*任意*、デフォルトは`"sine"`) : 画像特徴の上に適用する位置埋め込みの種類。`"sine"`または`"learned"`のいずれかです。

dilation (`bool`、*任意*、デフォルトは `False`) : 最後の畳み込みブロック（DC5）で stride を dilation に置き換えるかどうか。`use_timm_backbone` = `True` の場合のみサポートされます。

num_feature_levels (`int`、*任意*、デフォルトは 4) : 入力特徴量のレベル数。

encoder_n_points (`int`、*optional*、デフォルトは 4) : エンコーダーの各アテンションヘッドにおける、各特徴レベルでサンプリングされるキーの数。

decoder_n_points (`int`、*optional*、デフォルトは 4) : デコーダーの各アテンションヘッドにおける、各特徴レベルでサンプリングされるキーの数。

two_stage (`bool`、*任意*、デフォルトは`False`) : 2段階のDeformable DETRを適用するかどうか。この場合、領域提案もDeformable DETRのバリアントによって生成され、それらがデコーダーに渡されてバウンディングボックスの反復的な精緻化が行われます。

two_stage_num_proposals (`int`、*任意*、デフォルトは 300) : `two_stage` が `True` に設定されている場合、生成される region proposals の数です。

with_box_refine (`bool`, *任意*, デフォルトは `False`) : 反復的なバウンディングボックスの精緻化を適用するかどうか。各デコーダー層が、前の層の予測に基づいてバウンディングボックスを精緻化します。

class_cost (`int`, *optional*, デフォルトは `1`) : ハンガリアンマッチングのコストにおける分類誤差の相対的な重み。

bbox_cost (`int`、*任意*、デフォルトは`5`) : ハンガリアンマッチングのコストにおける、L1バウンディングボックス誤差の相対的な重み。

giou_cost (`int`, *optional*, デフォルトは `2`) : ハンガリアンマッチングのコストにおける汎化 IoU ロスの相対的な重み。

mask_loss_coefficient (`int`, *optional*, デフォルトは `1`) : パノプティックセグメンテーション損失における focal loss の相対的な重み。

dice_loss_coefficient (`int`、*任意*、デフォルトは`1`) : パノプティックセグメンテーション損失におけるdice lossの相対的な重み。

bbox_loss_coefficient (`int`、*任意*、デフォルトは`5`) : パノプティックセグメンテーション損失におけるL1バウンディングボックス損失の相対的な重み。

giou_loss_coefficient (`int`, *任意*, デフォルトは `2`) : パノプティックセグメンテーション損失における汎化IoU損失の相対的な重み。

eos_coefficient (`float`、*任意*、デフォルトは`0.1`) : オブジェクト検出損失における「no-object」クラスの相対的な分類重み。

focal_alpha (`float`、*任意*、デフォルトは `0.25`) : focal loss の Alpha パラメータです。

disable_custom_kernels (`bool`、*任意*、デフォルトは`False`) : カスタム CUDA カーネルおよび CPU カーネルの使用を無効にします。PyTorch の ONNX エクスポートではカスタムカーネルがサポートされていないため、ONNX エクスポートを行うにはこのオプションが必要です。

tie_word_embeddings (`bool`、*任意*、デフォルトは`True`) : モデルの`tied_weights_keys`マッピングに従って重み埋め込みを共有するかどうか。

これはDeformableDetrModelの設定を保存するための設定クラスです。指定された引数に基づいてDeformable Detrモデルをインスタンス化し、モデルのアーキテクチャを定義するために使用されます。デフォルト値で設定をインスタンス化すると、[SenseTime/deformable-detr](https://huggingface.co/SenseTime/deformable-detr)の設定に類似した設定が得られます。

設定オブジェクトは [PreTrainedConfig](/docs/transformers/v5.24.0/ja/main_classes/configuration#transformers.PreTrainedConfig) を継承し、モデルの出力を制御するために使用できます。詳細については、[PreTrainedConfig](/docs/transformers/v5.24.0/ja/main_classes/configuration#transformers.PreTrainedConfig) のドキュメントを参照してください。

例:

```python
>>> from transformers import DeformableDetrConfig, DeformableDetrModel

>>> # Initializing a Deformable DETR SenseTime/deformable-detr style configuration
>>> configuration = DeformableDetrConfig()

>>> # Initializing a model (with random weights) from the SenseTime/deformable-detr style configuration
>>> model = DeformableDetrModel(configuration)

>>> # Accessing the model configuration
>>> configuration = model.config
```

## DeformableDetrModel[[transformers.DeformableDetrModel]]

#### transformers.DeformableDetrModel[[transformers.DeformableDetrModel]]

```python
transformers.DeformableDetrModel(config: DeformableDetrConfig)
```

[ソース](https://github.com/huggingface/transformers/blob/v5.24.0/src/transformers/models/deformable_detr/modeling_deformable_detr.py#L1144)

**パラメータ:**

config ([DeformableDetrConfig](/docs/transformers/v5.24.0/ja/model_doc/deformable_detr#transformers.DeformableDetrConfig)) : モデルのパラメータをすべて含むモデル設定クラスです。設定ファイルで初期化しても、モデルに関連する重みは読み込まれず、設定のみが読み込まれます。モデルの重みをロードするには、[from_pretrained()](/docs/transformers/v5.24.0/ja/main_classes/model#transformers.PreTrainedModel.from_pretrained) メソッドを確認してください。

Deformable DETRのベースモデル（バックボーンとエンコーダー・デコーダーのTransformerで構成）は、特定のヘッドを上に載せず、生のhidden-statesを出力します。

このモデルは [PreTrainedModel](/docs/transformers/v5.24.0/ja/main_classes/model#transformers.PreTrainedModel) を継承しています。ライブラリがすべてのモデルに対して実装している汎用的なメソッド（ダウンロードや保存、入力埋め込みのリサイズ、ヘッドのプルーニングなど）については、スーパークラスのドキュメントを参照してください。

このモデルは、PyTorchの[torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module)のサブクラスでもあります。通常のPyTorch Moduleとして使用し、一般的な使用方法や動作に関する詳細については、PyTorchのドキュメントを参照してください。

#### forward[[transformers.DeformableDetrModel.forward]]

```python
forward(pixel_values: Tensor, pixel_mask: typing.Optional[torch.LongTensor] = None, decoder_attention_mask: typing.Optional[torch.Tensor] = None, encoder_outputs: typing.Optional[torch.Tensor] = None, inputs_embeds: typing.Optional[torch.Tensor] = None, decoder_inputs_embeds: typing.Optional[torch.Tensor] = None, **kwargs: *<class 'transformers.utils.generic.TransformersKwargs'>)
```

[ソース](https://github.com/huggingface/transformers/blob/v5.24.0/src/transformers/models/deformable_detr/modeling_deformable_detr.py#L1318)

**パラメータ:**

pixel_values (`torch.Tensor`、shape `(batch_size, num_channels, image_size, image_size)`) : 入力画像に対応するテンソルです。ピクセル値は `image_processor_class` を使用して取得できます。詳細は `image_processor_class.__call__` を参照してください（`processor_class` は画像の処理に `image_processor_class` を使用します）。

pixel_mask (`torch.LongTensor`、形状 `(batch_size, height, width)`、*任意*) : パディングピクセル値に対するアテンションの実行を回避するためのマスク。`[0, 1]` から選択されるマスク値:  - 実在するピクセル（つまり **マスクされていない**）は 1、 - パディングのピクセル（つまり **マスクされている**）は 0。  [アテンションマスクとは何ですか？](../glossary#attention-mask)

decoder_attention_mask (`torch.Tensor`、形状 `(batch_size, num_queries)`、*任意*) : デフォルトでは使用されません。オブジェクトクエリをマスクするために使用できます。

encoder_outputs (`torch.Tensor`, *任意*) : (`last_hidden_state`, *任意*: `hidden_states`, *任意*: `attentions`) のタプル。`last_hidden_state` は形状 `(batch_size, sequence_length, hidden_size)` を持ち、エンコーダーの最終層の出力における隠れ状態のシーケンスです。*任意*デコーダーのクロスアテンションで使用されます。

inputs_embeds (`torch.Tensor`、shape `(batch_size, sequence_length, hidden_size)`、*optional*) : フラット化された特徴マップ（backboneとprojection layerの出力）を渡す代わりに、画像のフラット化された表現を直接渡すこともできます。

decoder_inputs_embeds (`torch.Tensor`、形状 `(batch_size, num_queries, hidden_size)`、*任意*) : クエリをゼロのテンソルで初期化する代わりに、埋め込み表現を直接渡すこともできます。

**戻り値:** `DeformableDetrModelOutput` または `tuple(torch.Tensor)`

`None`および入力に応じて、さまざまな要素で構成される`DeformableDetrModelOutput`または`torch.Tensor`のタプル（`return_dict=False`が渡された場合、または`config.return_dict=False`の場合）。

[DeformableDetrModel](/docs/transformers/v5.24.0/ja/model_doc/deformable_detr#transformers.DeformableDetrModel)のforwardメソッドは、`__call__`特殊メソッドをオーバーライドします。

この関数内でフォワードパスの手順を定義する必要がありますが、その後、この関数ではなく`Module`インスタンスを呼び出すべきです。前者は前処理と後処理の実行を適切に処理するのに対し、後者はそれらを無視してしまいます。

- **init_reference_points** (`torch.Tensor`、形状 `(batch_size, num_queries, 4)`) -- Transformerデコーダーに渡される初期の参照点。
- **last_hidden_state** (`torch.Tensor`、形状 `(batch_size, num_queries, hidden_size)`) -- モデルのデコーダーの最終層の出力における、隠れ状態のシーケンスです。
- **intermediate_hidden_states** (`torch.Tensor`、形状 `(batch_size, config.decoder_layers, num_queries, hidden_size)`) -- 中間隠れ状態のスタック（デコーダーの各層の出力）。
- **intermediate_reference_points** (`torch.Tensor`、形状 `(batch_size, config.decoder_layers, num_queries, 4)`) -- 中間参照点のスタック（デコーダーの各層の参照点）。
- **decoder_hidden_states** (`tuple[torch.Tensor]`、*optional*、`output_hidden_states=True` が渡された場合または `config.output_hidden_states=True` の場合に返されます) -- `torch.Tensor` のタプル（埋め込み層を持つモデルの場合、埋め込みの出力用 1 つ + 各層の出力用 1 つ）で、形状は `(batch_size, sequence_length, hidden_size)` です。

  各層の出力および初期埋め込み出力における、デコーダーの隠れ状態。
- **decoder_attentions** (`tuple[torch.Tensor]`、*optional*、`output_attentions=True` が渡された場合または `config.output_attentions=True` の場合に返されます) -- `torch.Tensor` のタプル（各レイヤーごとに1つ）、形状は `(batch_size, num_heads, sequence_length, sequence_length)`。

  自己アテンションヘッドにおける加重平均を計算するために使用される、アテンションのsoftmax後のデコーダーのアテンション重み。
- **cross_attentions** (`tuple[torch.Tensor]`、*optional*、`output_attentions=True` が渡された場合または `config.output_attentions=True` の場合に返されます) -- `torch.Tensor` のタプル（各レイヤーごとに1つ）、形状は `(batch_size, num_heads, sequence_length, sequence_length)`。

  クロスアテンション層のアテンション重みは、アテンションのsoftmax適用後に計算され、クロスアテンションヘッドにおける加重平均の計算に使用されます。
- **encoder_last_hidden_state** (`torch.Tensor`、形状 `(batch_size, sequence_length, hidden_size)`、*任意*) -- モデルのエンコーダーの最終層の出力における隠れ状態のシーケンス。
- **encoder_hidden_states** (`tuple[torch.Tensor]`、*optional*、`output_hidden_states=True` が渡された場合または `config.output_hidden_states=True` の場合に返されます) -- `torch.Tensor` のタプル（埋め込み層を持つモデルの場合、埋め込みの出力用 1 つ + 各層の出力用 1 つずつ）で、形状は `(batch_size, sequence_length, hidden_size)` です。

  各層の出力および初期埋め込み出力におけるエンコーダーの隠れ状態。
- **encoder_attentions** (`tuple[torch.Tensor]`、*optional*、`output_attentions=True` が渡された場合または `config.output_attentions=True` の場合に返されます) -- `torch.Tensor` のタプル（各レイヤーごとに1つ）、形状は `(batch_size, num_heads, sequence_length, sequence_length)`。

  アテンションのsoftmaxを適用した後のエンコーダーのアテンション重み。自己アテンションヘッドにおける加重平均の計算に使用されます。
- **enc_outputs_class** (`torch.Tensor`、形状 `(batch_size, sequence_length, config.num_labels)`、*任意*、`config.with_box_refine=True` かつ `config.two_stage=True` の場合に返されます) -- 第1段階でスコア上位の `config.two_stage_num_proposals` 個のバウンディングボックスがリージョンプロポーザルとして選択される、予測されたバウンディングボックスのスコアです。バウンディングボックスの二値分類（すなわちフォアグラウンドとバックグラウンド）の出力です。
- **enc_outputs_coord_logits** (`torch.Tensor`、形状 `(batch_size, sequence_length, 4)`、*任意*、`config.with_box_refine=True` かつ `config.two_stage=True` の場合に返されます) -- 第1段階で予測されるバウンディングボックス座標のロジット。

例:

```python
>>> from transformers import AutoImageProcessor, DeformableDetrModel
>>> from PIL import Image
>>> from huggingface_hub.utils import httpx
>>> from io import BytesIO

>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> with httpx.stream("GET", url) as response:
...     image = Image.open(BytesIO(response.read()))

>>> image_processor = AutoImageProcessor.from_pretrained("SenseTime/deformable-detr")
>>> model = DeformableDetrModel.from_pretrained("SenseTime/deformable-detr")

>>> inputs = image_processor(images=image, return_tensors="pt")

>>> outputs = model(**inputs)

>>> last_hidden_states = outputs.last_hidden_state
>>> list(last_hidden_states.shape)
[1, 300, 256]
```

## DeformableDetrForObjectDetection[[transformers.DeformableDetrForObjectDetection]]

#### transformers.DeformableDetrForObjectDetection[[transformers.DeformableDetrForObjectDetection]]

```python
transformers.DeformableDetrForObjectDetection(config: DeformableDetrConfig)
```

[ソース](https://github.com/huggingface/transformers/blob/v5.24.0/src/transformers/models/deformable_detr/modeling_deformable_detr.py#L1541)

**パラメータ:**

config ([DeformableDetrConfig](/docs/transformers/v5.24.0/ja/model_doc/deformable_detr#transformers.DeformableDetrConfig)) : モデルのパラメータをすべて含むモデル設定クラスです。設定ファイルで初期化しても、モデルに関連する重みは読み込まれず、設定のみが読み込まれます。モデルの重みをロードするには、[from_pretrained()](/docs/transformers/v5.24.0/ja/main_classes/model#transformers.PreTrainedModel.from_pretrained) メソッドを確認してください。

COCO検出などのタスク向けに、オブジェクト検出ヘッドを備えたDeformable DETRモデル（バックボーンとエンコーダー・デコーダーのTransformerで構成）。

このモデルは [PreTrainedModel](/docs/transformers/v5.24.0/ja/main_classes/model#transformers.PreTrainedModel) を継承しています。ライブラリがすべてのモデルに対して実装している汎用的なメソッド（ダウンロードや保存、入力埋め込みのリサイズ、ヘッドのプルーニングなど）については、スーパークラスのドキュメントを参照してください。

このモデルは、PyTorchの[torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module)のサブクラスでもあります。通常のPyTorch Moduleとして使用し、一般的な使用方法や動作に関する詳細については、PyTorchのドキュメントを参照してください。

#### forward[[transformers.DeformableDetrForObjectDetection.forward]]

```python
forward(pixel_values: Tensor, pixel_mask: typing.Optional[torch.LongTensor] = None, decoder_attention_mask: typing.Optional[torch.Tensor] = None, encoder_outputs: typing.Optional[torch.Tensor] = None, inputs_embeds: typing.Optional[torch.Tensor] = None, decoder_inputs_embeds: typing.Optional[torch.Tensor] = None, labels: list[dict] | None = None, **kwargs: *<class 'transformers.utils.generic.TransformersKwargs'>)
```

[ソース](https://github.com/huggingface/transformers/blob/v5.24.0/src/transformers/models/deformable_detr/modeling_deformable_detr.py#L1579)

**パラメータ:**

pixel_values (`torch.Tensor`、shape `(batch_size, num_channels, image_size, image_size)`) : 入力画像に対応するテンソルです。ピクセル値は `image_processor_class` を使用して取得できます。詳細は `image_processor_class.__call__` を参照してください（`processor_class` は画像の処理に `image_processor_class` を使用します）。

pixel_mask (`torch.LongTensor`、形状 `(batch_size, height, width)`、*任意*) : パディングピクセル値に対するアテンションの実行を回避するためのマスク。`[0, 1]` から選択されるマスク値:  - 実在するピクセル（つまり **マスクされていない**）は 1、 - パディングのピクセル（つまり **マスクされている**）は 0。  [アテンションマスクとは何ですか？](../glossary#attention-mask)

decoder_attention_mask (`torch.Tensor`、形状 `(batch_size, num_queries)`、*任意*) : デフォルトでは使用されません。オブジェクトクエリをマスクするために使用できます。

encoder_outputs (`torch.Tensor`, *任意*) : (`last_hidden_state`, *任意*: `hidden_states`, *任意*: `attentions`) のタプル。`last_hidden_state` は形状 `(batch_size, sequence_length, hidden_size)` を持ち、エンコーダーの最終層の出力における隠れ状態のシーケンスです。*任意*デコーダーのクロスアテンションで使用されます。

inputs_embeds (`torch.Tensor`、shape `(batch_size, sequence_length, hidden_size)`、*optional*) : フラット化された特徴マップ（backboneとprojection layerの出力）を渡す代わりに、画像のフラット化された表現を直接渡すこともできます。

decoder_inputs_embeds (`torch.Tensor`、形状 `(batch_size, num_queries, hidden_size)`、*任意*) : クエリをゼロのテンソルで初期化する代わりに、埋め込み表現を直接渡すこともできます。

labels (`list[Dict]`、長さ `(batch_size,)`、*任意*) : 二部マッチング損失を計算するためのラベル。辞書のリストで、各辞書には少なくとも以下の 2 つのキーが含まれます: 'class_labels' と 'boxes' (それぞれバッチ内の画像のクラスラベルとバウンディングボックス)。クラスラベル自体は長さ `(number of bounding boxes in the image,)` の `torch.LongTensor` であり、ボックスは形状 `(number of bounding boxes in the image, 4)` の `torch.Tensor` である必要があります。

**戻り値:** `DeformableDetrObjectDetectionOutput` または `tuple(torch.Tensor)`

`None` や入力に応じて、さまざまな要素で構成される`DeformableDetrObjectDetectionOutput`、または`torch.Tensor`のタプル（`return_dict=False`が渡された場合、または`config.return_dict=False`の場合）。

[DeformableDetrForObjectDetection](/docs/transformers/v5.24.0/ja/model_doc/deformable_detr#transformers.DeformableDetrForObjectDetection)のforwardメソッドは、`__call__`特殊メソッドをオーバーライドします。

この関数内でフォワードパスの手順を定義する必要がありますが、その後、この関数ではなく`Module`インスタンスを呼び出すべきです。前者は前処理と後処理の実行を適切に処理するのに対し、後者はそれらを無視してしまいます。

- **loss** (`torch.Tensor`、形状 `(1,)`、*任意*、`labels` が提供された場合に返されます) -- クラス予測の負の対数尤度（クロスエントロピー）とバウンディングボックス損失の線形結合としての総損失。後者は、L1損失と汎用スケール不変IoU損失の線形結合として定義されます。
- **loss_dict** (`Dict`, *任意*) -- 個別の損失を含む辞書です。ログ出力に便利です。
- **logits** (`torch.Tensor`、形状 `(batch_size, num_queries, num_classes + 1)`) -- すべてのクエリに対する分類 logits（no-object を含む）。
- **pred_boxes** (`torch.Tensor`、shape `(batch_size, num_queries, 4)`) -- すべてのクエリに対する正規化されたボックス座標。(center_x, center_y, width, height) で表されます。これらの値は、バッチ内の各画像のサイズに対して [0, 1] の範囲で正規化されています（パディングは考慮されません）。正規化されていないバウンディングボックスを取得するには、`~DeformableDetrProcessor.post_process_object_detection` を使用できます。
- **auxiliary_outputs** (`list[Dict]`, *optional*) -- 任意。補助損失が有効化されている場合（つまり `config.auxiliary_loss` が `True` に設定されている場合）かつラベルが提供されている場合にのみ返されます。各デコーダ層について、上記の 2 つのキー（`logits` と `pred_boxes`）を含む辞書のリストです。
- **last_hidden_state** (`torch.Tensor`、形状 `(batch_size, num_queries, hidden_size)`、*任意*) -- モデルのデコーダーの最終層の出力における隠れ状態のシーケンス。
- **decoder_hidden_states** (`tuple[torch.Tensor]`、*optional*、`output_hidden_states=True` が渡された場合または `config.output_hidden_states=True` の場合に返されます) -- `torch.Tensor` のタプル（埋め込み層を持つモデルの場合、埋め込みの出力用 1 つ + 各層の出力用 1 つ）で、形状は `(batch_size, sequence_length, hidden_size)` です。

  各層の出力および初期埋め込み出力における、デコーダーの隠れ状態。
- **decoder_attentions** (`tuple[torch.Tensor]`、*optional*、`output_attentions=True` が渡された場合または `config.output_attentions=True` の場合に返されます) -- `torch.Tensor` のタプル（各レイヤーごとに1つ）、形状は `(batch_size, num_heads, sequence_length, sequence_length)`。

  自己アテンションヘッドにおける加重平均を計算するために使用される、アテンションのsoftmax後のデコーダーのアテンション重み。
- **cross_attentions** (`tuple[torch.Tensor]`、*optional*、`output_attentions=True` が渡された場合または `config.output_attentions=True` の場合に返されます) -- `torch.Tensor` のタプル（各レイヤーごとに1つ）、形状は `(batch_size, num_heads, sequence_length, sequence_length)`。

  クロスアテンション層のアテンション重みは、アテンションのsoftmax適用後に計算され、クロスアテンションヘッドにおける加重平均の計算に使用されます。
- **encoder_last_hidden_state** (`torch.Tensor`、形状 `(batch_size, sequence_length, hidden_size)`、*任意*) -- モデルのエンコーダーの最終層の出力における隠れ状態のシーケンス。
- **encoder_hidden_states** (`tuple[torch.Tensor]`、*optional*、`output_hidden_states=True` が渡された場合または `config.output_hidden_states=True` の場合に返されます) -- `torch.Tensor` のタプル（埋め込み層を持つモデルの場合、埋め込みの出力用 1 つ + 各層の出力用 1 つずつ）で、形状は `(batch_size, sequence_length, hidden_size)` です。

  各層の出力および初期埋め込み出力におけるエンコーダーの隠れ状態。
- **encoder_attentions** (`tuple[torch.Tensor]`、*optional*、`output_attentions=True` が渡された場合または `config.output_attentions=True` の場合に返されます) -- `torch.Tensor` のタプル（各レイヤーごとに1つ）、形状は `(batch_size, num_heads, sequence_length, sequence_length)`。

  アテンションのsoftmaxを適用した後のエンコーダーのアテンション重み。自己アテンションヘッドにおける加重平均の計算に使用されます。
- **init_reference_points** (`torch.Tensor`、形状 `(batch_size, num_queries, 4)`) -- Transformerデコーダーに渡される初期の参照点。
- **intermediate_hidden_states** (`torch.Tensor`、形状 `(batch_size, config.decoder_layers, num_queries, hidden_size)`) -- 中間隠れ状態のスタック（デコーダーの各層の出力）。
- **intermediate_reference_points** (`torch.Tensor`、形状 `(batch_size, config.decoder_layers, num_queries, 4)`) -- 中間参照点のスタック（デコーダーの各層の参照点）。
- **enc_outputs_class** (`torch.Tensor`、形状 `(batch_size, sequence_length, config.num_labels)`、*任意*、`config.with_box_refine=True` かつ `config.two_stage=True` の場合に返されます) -- 第1段階でスコア上位の `config.two_stage_num_proposals` 個のバウンディングボックスがリージョンプロポーザルとして選択される、予測されたバウンディングボックスのスコアです。バウンディングボックスの二値分類（すなわちフォアグラウンドとバックグラウンド）の出力です。
- **enc_outputs_coord_logits** (`torch.Tensor`、形状 `(batch_size, sequence_length, 4)`、*任意*、`config.with_box_refine=True` かつ `config.two_stage=True` の場合に返されます) -- 第1段階で予測されるバウンディングボックス座標のロジット。

例:

```python
>>> from transformers import AutoImageProcessor, DeformableDetrForObjectDetection
>>> from PIL import Image
>>> from huggingface_hub.utils import httpx
>>> from io import BytesIO

>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> with httpx.stream("GET", url) as response:
...     image = Image.open(BytesIO(response.read()))

>>> image_processor = AutoImageProcessor.from_pretrained("SenseTime/deformable-detr")
>>> model = DeformableDetrForObjectDetection.from_pretrained("SenseTime/deformable-detr")

>>> inputs = image_processor(images=image, return_tensors="pt")
>>> outputs = model(**inputs)

>>> # convert outputs (bounding boxes and class logits) to Pascal VOC format (xmin, ymin, xmax, ymax)
>>> target_sizes = torch.tensor([image.size[::-1]])
>>> results = image_processor.post_process_object_detection(outputs, threshold=0.5, 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()]
...     print(
...         f"Detected {model.config.id2label[label.item()]} with confidence "
...         f"{round(score.item(), 3)} at location {box}"
...     )
Detected cat with confidence 0.8 at location [16.5, 52.84, 318.25, 470.78]
Detected cat with confidence 0.789 at location [342.19, 24.3, 640.02, 372.25]
Detected remote with confidence 0.633 at location [40.79, 72.78, 176.76, 117.25]
```

