# YOLOS

[YOLOS](https://huggingface.co/papers/2106.00666)は、[Vision Transformer (ViT)](./vit)を最小限の変更とリージョン・プライオリティを用いて物体検出に適用します。2D空間構造に関する知識を持つことで、専用の物体検出モデルやフレームワークと同等の性能を達成できます。

YOLOSのすべてのオリジナルチェックポイントは、[HUST Vision Lab](https://huggingface.co/hustvl/models?search=yolos)組織の下で確認できます。

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

> [!TIP]
> このモデルは[nielsr](https://huggingface.co/nielsr)によって提供されました。YOLOSをさまざまなオブジェクト検出タスクに適用する方法の例については、右側のサイドバーにあるYOLOSモデルをクリックしてください。

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

```python
from transformers import pipeline

detector = pipeline(
    task="object-detection",
    model="hustvl/yolos-base",
    device=0
)
detector("https://huggingface.co/datasets/Narsil/image_dummy/raw/main/parrots.png")
```

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

from transformers import AutoImageProcessor, AutoModelForObjectDetection

processor = AutoImageProcessor.from_pretrained("hustvl/yolos-base")
model = AutoModelForObjectDetection.from_pretrained("hustvl/yolos-base", attn_implementation="sdpa", device_map="auto")

url = "https://huggingface.co/datasets/Narsil/image_dummy/raw/main/parrots.png"
image = Image.open(requests.get(url, stream=True).raw).convert("RGB")
inputs = processor(images=image, return_tensors="pt").to(model.device)

with torch.no_grad():
    outputs = model(**inputs)
logits = outputs.logits.softmax(-1)
scores, labels = logits[..., :-1].max(-1)
boxes = outputs.pred_boxes

threshold = 0.3
keep = scores[0] > threshold

filtered_scores = scores[0][keep]
filtered_labels = labels[0][keep]
filtered_boxes  = boxes[0][keep]

width, height = image.size
pixel_boxes = filtered_boxes * torch.tensor([width, height, width, height], device=boxes.device)

for score, label, box in zip(filtered_scores, filtered_labels, pixel_boxes):
    x0, y0, x1, y1 = box.tolist()
    print(f"Label {model.config.id2label[label.item()]}: {score:.2f} at [{x0:.0f}, {y0:.0f}, {x1:.0f}, {y1:.0f}]")
```

## 注記

- モデル用の画像（および任意のターゲット）の準備には、[YolosImageProcessor](/docs/transformers/main/ja/model_doc/yolos#transformers.YolosImageProcessor)を使用します。[DETR](./detr)とは異なり、YOLOSでは`pixel_mask`は必要ありません。

## リソース

- カスタムデータセットでの[YolosForObjectDetection](/docs/transformers/main/ja/model_doc/yolos#transformers.YolosForObjectDetection)による推論とファインチューニングについては、これらの[ノートブック](https://github.com/NielsRogge/Transformers-Tutorials/tree/master/YOLOS)を参照してください。

## YolosConfig[[transformers.YolosConfig]]

#### transformers.YolosConfig[[transformers.YolosConfig]]

```python
transformers.YolosConfig(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, is_encoder_decoder: bool = False, 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, hidden_size: int = 768, num_hidden_layers: int = 12, num_attention_heads: int = 12, intermediate_size: int = 3072, hidden_act: str = 'gelu', hidden_dropout_prob: float | int = 0.0, attention_probs_dropout_prob: float | int = 0.0, initializer_range: float = 0.02, layer_norm_eps: float = 1e-12, image_size: list[int] | tuple[int, ...] = (512, 864), patch_size: int | list[int] | tuple[int, int] = 16, num_channels: int = 3, qkv_bias: bool = True, num_detection_tokens: int = 100, use_mid_position_embeddings: bool = True, auxiliary_loss: bool = False, class_cost: int = 1, bbox_cost: int = 5, giou_cost: int = 2, bbox_loss_coefficient: int = 5, giou_loss_coefficient: int = 2, eos_coefficient: float = 0.1)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/yolos/configuration_yolos.py#L24)

**パラメータ:**

hidden_size (`int`、*任意*、デフォルトは`768`) : 隠れ表現の次元数。

num_hidden_layers (`int`, *任意*, デフォルトは `12`) : Transformer デコーダーの隠れ層の数。

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

intermediate_size (`int`、*任意*、デフォルトは `3072`) : MLP 表現の次元数。

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

hidden_dropout_prob (`Union[float, int]`、*任意*、デフォルトは`0.0`) : embeddings、encoder、pooler 内のすべての全結合層における dropout 確率。

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

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

layer_norm_eps (`float`、*任意*、デフォルトは `1e-12`) : layer normalization レイヤーで使用する epsilon。

image_size (`Union[list[int], tuple[int, ...]]`、*任意*、デフォルトは`(512, 864)`) : 各画像のサイズ（解像度）。

patch_size (`Union[int, list[int], tuple[int, int]]`、*任意*、デフォルトは`16`) : 各パッチのサイズ（解像度）。

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

qkv_bias (`bool`, *任意*, デフォルトは `True`) : クエリ、キー、バリューにバイアスを追加するかどうか。

num_detection_tokens (`int`、*optional*、デフォルトは 100) : 検出トークンの数。

use_mid_position_embeddings (`bool`, *任意*, デフォルトは `True`) : 中間層の位置エンコーディングを使用するかどうか。

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

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

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

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

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

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

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

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

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

例:

```python
>>> from transformers import YolosConfig, YolosModel

>>> # Initializing a YOLOS hustvl/yolos-base style configuration
>>> configuration = YolosConfig()

>>> # Initializing a model (with random weights) from the hustvl/yolos-base style configuration
>>> model = YolosModel(configuration)

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

## YolosImageProcessor[[transformers.YolosImageProcessor]]

#### transformers.YolosImageProcessor[[transformers.YolosImageProcessor]]

```python
transformers.YolosImageProcessor(**kwargs: *<class 'transformers.models.yolos.image_processing_yolos.YolosImageProcessorKwargs'>)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/yolos/image_processing_yolos.py#L298)

**パラメータ:**

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`) : アノテーションをYOLOSモデルが期待する形式に変換するかどうかを制御します。バウンディングボックスを`(center_x, center_y, width, height)`の形式に変換し、範囲を`[0, 1]`にします。`preprocess`メソッドの`do_convert_annotations`パラメータによって上書きできます。

YolosImageProcessor イメージプロセッサを構築します。

#### preprocess[[transformers.YolosImageProcessor.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.yolos.image_processing_yolos.YolosImageProcessorKwargs'>)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/yolos/image_processing_yolos.py#L553)

**パラメータ:**

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`) : アノテーションをYOLOSモデルが期待する形式に変換するかどうかを制御します。バウンディングボックスを`(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 を指定できます。

## YolosImageProcessorPil[[transformers.YolosImageProcessorPil]]

#### transformers.YolosImageProcessorPil[[transformers.YolosImageProcessorPil]]

```python
transformers.YolosImageProcessorPil(**kwargs: *<class 'transformers.models.yolos.image_processing_pil_yolos.YolosImageProcessorKwargs'>)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/yolos/image_processing_pil_yolos.py#L291)

**パラメータ:**

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`) : アノテーションをYOLOSモデルが期待する形式に変換するかどうかを制御します。バウンディングボックスを`(center_x, center_y, width, height)`の形式に変換し、範囲を`[0, 1]`にします。`preprocess`メソッドの`do_convert_annotations`パラメータによって上書きできます。

YolosImageProcessor イメージプロセッサを構築します。

#### preprocess[[transformers.YolosImageProcessorPil.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.yolos.image_processing_pil_yolos.YolosImageProcessorKwargs'>)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/yolos/image_processing_pil_yolos.py#L559)

**パラメータ:**

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`) : アノテーションをYOLOSモデルが期待する形式に変換するかどうかを制御します。バウンディングボックスを`(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 を指定できます。

#### pad[[transformers.YolosImageProcessorPil.pad]]

```python
pad(image: ndarray, padded_size: tuple, annotation: dict[str, typing.Any] | None = None, update_bboxes: bool = True, fill: int = 0)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/yolos/image_processing_pil_yolos.py#L521)

#### post_process_object_detection[[transformers.YolosImageProcessorPil.post_process_object_detection]]

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

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/yolos/image_processing_pil_yolos.py#L704)

**パラメータ:**

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

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

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

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

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

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

## YolosModel[[transformers.YolosModel]]

#### transformers.YolosModel[[transformers.YolosModel]]

```python
transformers.YolosModel(config: YolosConfig, add_pooling_layer: bool = True)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/yolos/modeling_yolos.py#L451)

**パラメータ:**

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

add_pooling_layer (`bool`、*任意*、デフォルトは`True`) : プーリング層を追加するかどうか

Yolosのベースモデル。特定のヘッドを付加せず、生のhidden-statesを出力します。

このモデルは [PreTrainedModel](/docs/transformers/main/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.YolosModel.forward]]

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

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/yolos/modeling_yolos.py#L472)

**パラメータ:**

pixel_values (`torch.Tensor`、形状 `(batch_size, num_channels, image_size, image_size)`、*任意*) : 入力画像に対応するテンソルです。ピクセル値は [YolosImageProcessor](/docs/transformers/main/ja/model_doc/yolos#transformers.YolosImageProcessor) を使用して取得できます。詳細については [YolosImageProcessor.__call__()](/docs/transformers/main/ja/model_doc/molmo2#transformers.Molmo2ImageProcessor.__call__) を参照してください（`processor_class` は画像の処理に [YolosImageProcessor](/docs/transformers/main/ja/model_doc/yolos#transformers.YolosImageProcessor) を使用します）。

**戻り値:** [BaseModelOutputWithPooling](/docs/transformers/main/ja/main_classes/output#transformers.modeling_outputs.BaseModelOutputWithPooling) または `tuple(torch.Tensor)`

`torch.Tensor` のタプル（`return_dict=False` が渡された場合、または `config.return_dict=False` の場合）または [BaseModelOutputWithPooling](/docs/transformers/main/ja/main_classes/output#transformers.modeling_outputs.BaseModelOutputWithPooling)。設定（[YolosConfig](/docs/transformers/main/ja/model_doc/yolos#transformers.YolosConfig)）と入力に応じて、さまざまな要素で構成されます。

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

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

- **last_hidden_state** (`torch.Tensor`、形状 `(batch_size, sequence_length, hidden_size)`) -- モデルの最終層の出力における隠れ状態のシーケンス。
- **pooler_output** (`torch.Tensor`、形状 `(batch_size, hidden_size)`) -- 補助的な事前学習タスクに使用される層をさらに通して処理された後、シーケンスの最初のトークン（分類トークン）の最終層の隠れ状態です。例えば、BERT系のモデルでは、線形層とtanh活性化関数を経て処理された後の分類トークンを返します。この線形層の重みは、事前学習中の次の文予測（分類）目的から学習されます。
- **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)` です。

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

  アテンションのsoftmax後のアテンション重み。自己アテンションヘッド内で加重平均を計算するために使用されます。

例:

```python
```

## YolosForObjectDetection[[transformers.YolosForObjectDetection]]

#### transformers.YolosForObjectDetection[[transformers.YolosForObjectDetection]]

```python
transformers.YolosForObjectDetection(config: YolosConfig)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/yolos/modeling_yolos.py#L534)

**パラメータ:**

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

YOLOSモデル（ViTエンコーダーで構成）の上部にオブジェクト検出ヘッドを備え、COCO検出などのタスクに対応します。

このモデルは [PreTrainedModel](/docs/transformers/main/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.YolosForObjectDetection.forward]]

```python
forward(pixel_values: Tensor, labels: list[dict] | None = None, **kwargs: *<class 'transformers.utils.generic.TransformersKwargs'>)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/yolos/modeling_yolos.py#L557)

**パラメータ:**

pixel_values (`torch.Tensor`、形状 `(batch_size, num_channels, image_size, image_size)`) : 入力画像に対応するテンソルです。ピクセル値は [YolosImageProcessor](/docs/transformers/main/ja/model_doc/yolos#transformers.YolosImageProcessor) を使用して取得できます。詳細は [YolosImageProcessor.__call__()](/docs/transformers/main/ja/model_doc/molmo2#transformers.Molmo2ImageProcessor.__call__) を参照してください（`processor_class` は画像の処理に [YolosImageProcessor](/docs/transformers/main/ja/model_doc/yolos#transformers.YolosImageProcessor) を使用します）。

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` である必要があります。

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

`YolosObjectDetectionOutput`、または`torch.Tensor`のタプル（`return_dict=False`が渡された場合、または`config.return_dict=False`の場合）。設定（[YolosConfig](/docs/transformers/main/ja/model_doc/yolos#transformers.YolosConfig)）や入力に応じて、さまざまな要素で構成されます。

[YolosForObjectDetection](/docs/transformers/main/ja/model_doc/yolos#transformers.YolosForObjectDetection)の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] の範囲で正規化されています（パディングは考慮されません）。正規化されていないバウンディングボックスを取得するには、`~YolosImageProcessor.post_process` を使用できます。
- **auxiliary_outputs** (`list[Dict]`, *optional*) -- 任意。補助損失が有効化されている場合（つまり `config.auxiliary_loss` が `True` に設定されている場合）かつラベルが提供されている場合にのみ返されます。各デコーダ層について、上記の 2 つのキー（`logits` と `pred_boxes`）を含む辞書のリストです。
- **last_hidden_state** (`torch.Tensor`、形状 `(batch_size, sequence_length, hidden_size)`、*任意*) -- モデルのデコーダーの最終層の出力における、隠れ状態のシーケンス。
- **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)` です。

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

  アテンションのsoftmax後のアテンション重み。自己アテンションヘッド内で加重平均を計算するために使用されます。

例:

```python
>>> from transformers import AutoImageProcessor, AutoModelForObjectDetection
>>> import torch
>>> 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("hustvl/yolos-tiny")
>>> model = AutoModelForObjectDetection.from_pretrained("hustvl/yolos-tiny")

>>> 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.9, 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 remote with confidence 0.991 at location [46.48, 72.78, 178.98, 119.3]
Detected remote with confidence 0.908 at location [336.48, 79.27, 368.23, 192.36]
Detected cat with confidence 0.934 at location [337.18, 18.06, 638.14, 373.09]
Detected cat with confidence 0.979 at location [10.93, 53.74, 313.41, 470.67]
Detected remote with confidence 0.974 at location [41.63, 72.23, 178.09, 119.99]
```

