# MobileViT

[MobileViT](https://huggingface.co/papers/2110.02178)は、モバイルデバイス向けの軽量なビジョン・トランスフォーマーです。CNNの効率性と誘導バイアスと、トランスフォーマーのグローバルなコンテキストモデリングを融合しています。トランスフォーマーを畳み込みとして扱うことで、標準的なViTのような重い計算コストなしにグローバルな情報処理を可能にしています。

   

すべての MobileViT の元のチェックポイントは、[Apple](https://huggingface.co/apple/models?search=mobilevit) 組織の下で見つけることができます。

> [!TIP]
>
> - このモデルは [matthijs](https://huggingface.co/Matthijs) によって提供されました。
>
> MobileViTを異なるビジョンタスクに適用する方法のより多くの例については、右側のサイドバーにあるMobileViTモデルをクリックしてください。

以下の例では、[Pipeline](/docs/transformers/main/ja/main_classes/pipelines#transformers.Pipeline)と[AutoModel](/docs/transformers/main/ja/model_doc/auto#transformers.AutoModel)クラスを用いた[Image Classification]の実行方法を示しています。

```python
from transformers import pipeline

classifier = pipeline(
   task="image-classification",
   model="apple/mobilevit-small",
   device=0,
)

preds = classifier("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg")
print(f"Prediction: {preds}\n")
```

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

from transformers import AutoImageProcessor, MobileViTForImageClassification

image_processor = AutoImageProcessor.from_pretrained(
   "apple/mobilevit-small",
   use_fast=True,
)
model = MobileViTForImageClassification.from_pretrained("apple/mobilevit-small", device_map="auto")

url = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg"
image = Image.open(requests.get(url, stream=True).raw)
inputs = image_processor(image, return_tensors="pt").to(model.device)

with torch.no_grad():
    logits = model(**inputs).logits
predicted_class_id = logits.argmax(dim=-1).item()

class_labels = model.config.id2label
predicted_class_label = class_labels[predicted_class_id]
print(f"The predicted class label is:{predicted_class_label}")
```

## 注記

- **非**シーケンシャルデータには作用せず、画像タスクにのみ純粋に設計されています。
- フィーチャマップがトークン埋め込みの代わりに直接使用されます。
- [MobileViTImageProcessor](/docs/transformers/main/ja/model_doc/mobilevit#transformers.MobileViTImageProcessor) を使用して画像を前処理します。
- カスタム前処理を使用する場合は、事前学習済み重みが想定する形式である **BGR** 形式（RGB 形式ではない）で画像が提供されていることを確認してください。
- 分類モデルは[ImageNet-1k](https://huggingface.co/datasets/ILSVRC/imagenet-1k)で事前学習されています。
- セグメンテーションモデルは[DeepLabV3](https://huggingface.co/papers/1706.05587)ヘッドを使用し、[PASCAL VOC](http://host.robots.ox.ac.uk/pascal/VOC/)で事前学習されています。

## MobileViTConfig[[transformers.MobileViTConfig]]

#### transformers.MobileViTConfig[[transformers.MobileViTConfig]]

```python
transformers.MobileViTConfig(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, num_channels: int = 3, image_size: int | list[int] | tuple[int, int] = 256, patch_size: int | list[int] | tuple[int, int] = 2, hidden_sizes: list[int] | tuple[int, ...] = (144, 192, 240), neck_hidden_sizes: list[int] | tuple[int, ...] = (16, 32, 64, 96, 128, 160, 640), num_attention_heads: int = 4, mlp_ratio: float = 2.0, expand_ratio: float = 4.0, hidden_act: str = 'silu', conv_kernel_size: int = 3, output_stride: int = 32, hidden_dropout_prob: float | int = 0.1, attention_probs_dropout_prob: float | int = 0.0, classifier_dropout_prob: float | int = 0.1, initializer_range: float = 0.02, layer_norm_eps: float = 1e-05, qkv_bias: bool = True, aspp_out_channels: int = 256, atrous_rates: list[int] | tuple[int, ...] = (6, 12, 18), aspp_dropout_prob: float | int = 0.1, semantic_loss_ignore_index: int = 255)
```

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

**パラメータ:**

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

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

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

hidden_sizes (`Union[list[int], tuple[int, ...]]`、*任意*、デフォルトは`(144, 192, 240)`) : モデルの各ステージにおける次元数（隠れサイズ）。

neck_hidden_sizes (`list[int]`、*optional*、デフォルトは`[16, 32, 64, 96, 128, 160, 640]`) : バックボーンのフィーチャマップのチャネル数です。

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

mlp_ratio (`float`、*任意*、デフォルトは`2.0`) : MLPの隠れ層の次元と埋め込みの次元の比率。

expand_ratio (`float`、*任意*、デフォルトは`4.0`) : 拡張比率。拡張の出力次元を設定します

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

conv_kernel_size (`int`、*任意*、デフォルトは`3`) : 畳み込みカーネルのサイズ。

output_stride (`int`、*任意*、デフォルトは`32`) : 入力と出力のフィーチャマップの空間解像度の比率です。

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

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

classifier_dropout_prob (`Union[float, int]`、*任意*、デフォルトは`0.1`) : クラシファイヤのドロップアウト率。

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

layer_norm_eps (`float`、*任意*、デフォルトは`1e-05`) : Layer Normalization 層で使用する epsilon。

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

aspp_out_channels (`int`, *optional*, デフォルトは 256) : 意味分割用の ASPP レイヤーで使用する出力チャネル数。

atrous_rates (`list[int]`、*optional*、デフォルトは`[6, 12, 18]`) : 意味分割用のASPP層で使用するDilation (atrous) 係数。

aspp_dropout_prob (`float`、*optional*、デフォルトは 0.1) : 意味分割用の ASPP 層の dropout 率です。

semantic_loss_ignore_index (`int`、*任意*、デフォルトは`255`) : セマンティックセグメンテーションモデルの損失関数によって無視されるインデックス。

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

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

例:

```python
>>> from transformers import MobileViTConfig, MobileViTModel

>>> # Initializing a mobilevit-small style configuration
>>> configuration = MobileViTConfig()

>>> # Initializing a model from the mobilevit-small style configuration
>>> model = MobileViTModel(configuration)

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

## MobileViTImageProcessor[[transformers.MobileViTImageProcessor]]

#### transformers.MobileViTImageProcessor[[transformers.MobileViTImageProcessor]]

```python
transformers.MobileViTImageProcessor(**kwargs: *<class 'transformers.models.mobilevit.image_processing_mobilevit.MobileVitImageProcessorKwargs'>)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/mobilevit/image_processing_mobilevit.py#L59)

**パラメータ:**

do_convert_rgb (`bool`, *kwargs*, *任意*, デフォルトは `None`) : 画像を RGB に変換するかどうかを指定します。

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

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

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

crop_size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*、デフォルト値は`{'height' : 256, 'width': 256}`): `center_crop`を適用した後の出力画像のサイズ。

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

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

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

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

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

image_std (`Union[float, list[float], tuple[float, ...]]`, *kwargs*, *optional*, デフォルトは `[0.5, 0.5, 0.5]`) : 正規化に使用する画像の標準偏差。`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*, デフォルトは `True`) : 画像を中央クロップするかどうか。

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

do_flip_channel_order (`bool`, *kwargs*, *optional*, デフォルトは `self.do_flip_channel_order`) : 色チャネルを RGB から BGR へ、またはその逆に変換するかどうかを指定します。

do_reduce_labels (`bool`, *kwargs*, *任意*、デフォルトは `self.do_reduce_labels`) : セグメンテーションマップのすべてのラベル値を 1 減らすかどうか。0 が背景に使用され、かつ背景自体がデータセットのすべてのクラスに含まれていないデータセット（ADE20k など）で通常使用されます。背景ラベルは 255 に置き換えられます。

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

#### preprocess[[transformers.MobileViTImageProcessor.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']], segmentation_maps: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor'], NoneType] = None, **kwargs: *<class 'transformers.models.mobilevit.image_processing_mobilevit.MobileVitImageProcessorKwargs'>)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/mobilevit/image_processing_mobilevit.py#L81)

**パラメータ:**

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` を設定してください。

segmentation_maps (`ImageInput`, *任意*) : 前処理対象のセグメンテーションマップ。

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

do_flip_channel_order (`bool`, *kwargs*, *optional*, デフォルトは `self.do_flip_channel_order`) : 色チャネルを RGB から BGR へ、またはその逆に変換するかどうかを指定します。

do_reduce_labels (`bool`, *kwargs*, *任意*、デフォルトは `self.do_reduce_labels`) : セグメンテーションマップのすべてのラベル値を 1 減らすかどうか。0 が背景に使用され、かつ背景自体がデータセットのすべてのクラスに含まれていないデータセット（ADE20k など）で通常使用されます。背景ラベルは 255 に置き換えられます。

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

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

#### post_process_semantic_segmentation[[transformers.MobileViTImageProcessor.post_process_semantic_segmentation]]

```python
post_process_semantic_segmentation(outputs, target_sizes: list[tuple[int, int]] | None = None, return_segmentation_scores: bool = False)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/mobilevit/image_processing_mobilevit.py#L207)

**パラメータ:**

outputs ([MobileViTForSemanticSegmentation](/docs/transformers/main/ja/model_doc/mobilevit#transformers.MobileViTForSemanticSegmentation)) : モデルの生出力。

target_sizes (`list[tuple[int, int]]`, *任意*) : 各予測の要求される最終サイズ（高さ、幅）に対応するタプルのリスト。

return_segmentation_scores (`bool`、*任意*、デフォルトは`False`) : セグメンテーションマップとともにセグメンテーションスコアを返すかどうか。`True`の場合、返されるリストの各要素は、`segmentation`（クラス ID、形状`(height, width)`）と`segmentation_scores`（形状`(num_classes, height, width)`）というフィールドを持つ`SemanticSegmentationPostProcessorOutput`です。

**戻り値:** `list[torch.Tensor]` または `list[SemanticSegmentationPostProcessorOutput]`

`return_segmentation_scores=False` (デフォルト)の場合、長さが`batch_size`のリストが返され、各要素はクラス ID を持つ形状`(height, width)`のセグメンテーションマップです。`return_segmentation_scores=True`の場合、`SemanticSegmentationPostProcessorOutput`のリストが返され、フィールド`segmentation` (クラス ID、形状`(height, width)`)と`segmentation_scores` (形状`(num_classes, height, width)`)を持ちます。どちらの場合も、`(height, width)`はターゲットサイズに対応します(`target_sizes`が指定されている場合)。

[MobileViTForSemanticSegmentation](/docs/transformers/main/ja/model_doc/mobilevit#transformers.MobileViTForSemanticSegmentation)の出力をセマンティックセグメンテーションマップに変換します。

## MobileViTImageProcessorPil[[transformers.MobileViTImageProcessorPil]]

#### transformers.MobileViTImageProcessorPil[[transformers.MobileViTImageProcessorPil]]

```python
transformers.MobileViTImageProcessorPil(**kwargs: *<class 'transformers.models.mobilevit.image_processing_pil_mobilevit.MobileVitImageProcessorKwargs'>)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/mobilevit/image_processing_pil_mobilevit.py#L64)

**パラメータ:**

do_convert_rgb (`bool`, *kwargs*, *任意*, デフォルトは `None`) : 画像を RGB に変換するかどうかを指定します。

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

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

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

crop_size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*、デフォルト値は`{'height' : 256, 'width': 256}`): `center_crop`を適用した後の出力画像のサイズ。

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

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

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

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

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

image_std (`Union[float, list[float], tuple[float, ...]]`, *kwargs*, *optional*, デフォルトは `[0.5, 0.5, 0.5]`) : 正規化に使用する画像の標準偏差。`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*, デフォルトは `True`) : 画像を中央クロップするかどうか。

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

do_flip_channel_order (`bool`, *kwargs*, *optional*, デフォルトは `self.do_flip_channel_order`) : 色チャネルを RGB から BGR へ、またはその逆に変換するかどうかを指定します。

do_reduce_labels (`bool`, *kwargs*, *任意*、デフォルトは `self.do_reduce_labels`) : セグメンテーションマップのすべてのラベル値を 1 減らすかどうか。0 が背景に使用され、かつ背景自体がデータセットのすべてのクラスに含まれていないデータセット（ADE20k など）で通常使用されます。背景ラベルは 255 に置き換えられます。

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

#### preprocess[[transformers.MobileViTImageProcessorPil.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']], segmentation_maps: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor'], NoneType] = None, **kwargs: *<class 'transformers.models.mobilevit.image_processing_pil_mobilevit.MobileVitImageProcessorKwargs'>)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/mobilevit/image_processing_pil_mobilevit.py#L86)

**パラメータ:**

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` を設定してください。

segmentation_maps (`ImageInput`, *任意*) : 前処理対象のセグメンテーションマップ。

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

do_flip_channel_order (`bool`, *kwargs*, *optional*, デフォルトは `self.do_flip_channel_order`) : 色チャネルを RGB から BGR へ、またはその逆に変換するかどうかを指定します。

do_reduce_labels (`bool`, *kwargs*, *任意*、デフォルトは `self.do_reduce_labels`) : セグメンテーションマップのすべてのラベル値を 1 減らすかどうか。0 が背景に使用され、かつ背景自体がデータセットのすべてのクラスに含まれていないデータセット（ADE20k など）で通常使用されます。背景ラベルは 255 に置き換えられます。

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

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

#### post_process_semantic_segmentation[[transformers.MobileViTImageProcessorPil.post_process_semantic_segmentation]]

```python
post_process_semantic_segmentation(outputs, target_sizes: list[tuple[int, int]] | None = None, return_segmentation_scores: bool = False)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/mobilevit/image_processing_pil_mobilevit.py#L191)

**パラメータ:**

outputs ([MobileViTForSemanticSegmentation](/docs/transformers/main/ja/model_doc/mobilevit#transformers.MobileViTForSemanticSegmentation)) : モデルの生出力。

target_sizes (`list[tuple[int, int]]`, *任意*) : 各予測の要求される最終サイズ（高さ、幅）に対応するタプルのリスト。

return_segmentation_scores (`bool`、*任意*、デフォルトは`False`) : セグメンテーションマップとともにセグメンテーションスコアを返すかどうか。`True`の場合、返されるリストの各要素は、`segmentation`（クラス ID、形状`(height, width)`）と`segmentation_scores`（形状`(num_classes, height, width)`）というフィールドを持つ`SemanticSegmentationPostProcessorOutput`です。

**戻り値:** `list[torch.Tensor]` または `list[SemanticSegmentationPostProcessorOutput]`

`return_segmentation_scores=False` (デフォルト)の場合、長さが`batch_size`のリストが返され、各要素はクラス ID を持つ形状`(height, width)`のセグメンテーションマップです。`return_segmentation_scores=True`の場合、`SemanticSegmentationPostProcessorOutput`のリストが返され、フィールド`segmentation` (クラス ID、形状`(height, width)`)と`segmentation_scores` (形状`(num_classes, height, width)`)を持ちます。どちらの場合も、`(height, width)`はターゲットサイズに対応します(`target_sizes`が指定されている場合)。

[MobileViTForSemanticSegmentation](/docs/transformers/main/ja/model_doc/mobilevit#transformers.MobileViTForSemanticSegmentation)の出力をセマンティックセグメンテーションマップに変換します。

## MobileViTModel[[transformers.MobileViTModel]]

#### transformers.MobileViTModel[[transformers.MobileViTModel]]

```python
transformers.MobileViTModel(config: MobileViTConfig, expand_output: bool = True)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/mobilevit/modeling_mobilevit.py#L613)

**パラメータ:**

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

expand_output (`bool`、*任意*、デフォルトは`True`) : モデルの出力を1x1畳み込みによって拡張するかどうか。`True`の場合、モデルは追加の1x1畳み込みを適用し、出力チャネルを`config.neck_hidden_sizes[5]`から`config.neck_hidden_sizes[6]`に拡張します。

特定のヘッドを付加せず、生の隠れ状態を出力する素のMobilevitモデル。

このモデルは [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.MobileViTModel.forward]]

```python
forward(pixel_values: typing.Optional[torch.Tensor] = None, output_hidden_states: bool | None = None, return_dict: bool | None = None, **kwargs)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/mobilevit/modeling_mobilevit.py#L645)

**パラメータ:**

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

output_hidden_states (`bool`, *任意*) : 全レイヤーの hidden states を返すかどうかを指定します。詳細は、返されるテンソルの `hidden_states` を参照してください。

return_dict (`bool`, *任意*) : プレーンなタプルではなく [ModelOutput](/docs/transformers/main/ja/main_classes/output#transformers.utils.ModelOutput) を返すかどうか。

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

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

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

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

- **last_hidden_state** (`torch.Tensor`、形状 `(batch_size, num_channels, height, width)`) -- モデルの最終層の出力における隠れ状態のシーケンス。
- **pooler_output** (`torch.Tensor`、形状 `(batch_size, hidden_size)`) -- 空間次元に対するプーリング操作を行った後の最終層の隠れ状態。
- **hidden_states** (`tuple(torch.Tensor)`、*optional*、`output_hidden_states=True` が渡された場合または `config.output_hidden_states=True` の場合に返されます) -- `torch.Tensor` のタプル（埋め込み層を持つモデルの場合、埋め込みの出力用 1 つ + 各層の出力用 1 つ）で、形状は `(batch_size, num_channels, height, width)` です。

  各層の出力におけるモデルのHidden-states、および任意の初期埋め込み出力。

例:

```python
```

## MobileViTForImageClassification[[transformers.MobileViTForImageClassification]]

#### transformers.MobileViTForImageClassification[[transformers.MobileViTForImageClassification]]

```python
transformers.MobileViTForImageClassification(config: MobileViTConfig)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/mobilevit/modeling_mobilevit.py#L695)

**パラメータ:**

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

MobileViTモデルの上部に画像分類ヘッド（プーリングされた特徴量の上に配置された線形層）を備えたもの。例えば、ImageNet向けに使用されます。

このモデルは [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.MobileViTForImageClassification.forward]]

```python
forward(pixel_values: typing.Optional[torch.Tensor] = None, output_hidden_states: bool | None = None, labels: typing.Optional[torch.Tensor] = None, return_dict: bool | None = None, **kwargs)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/mobilevit/modeling_mobilevit.py#L711)

**パラメータ:**

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

output_hidden_states (`bool`, *任意*) : 全レイヤーの hidden states を返すかどうかを指定します。詳細は、返されるテンソルの `hidden_states` を参照してください。

labels (`torch.LongTensor`、shape `(batch_size,)`、*任意*) : 画像分類/回帰の損失を計算するためのラベル。インデックスは `[0, ..., config.num_labels - 1]` の範囲である必要があります。`config.num_labels == 1` の場合は回帰損失（Mean-Square loss）が計算され、`config.num_labels > 1` の場合は分類損失（Cross-Entropy）が計算されます。

return_dict (`bool`, *任意*) : プレーンなタプルではなく [ModelOutput](/docs/transformers/main/ja/main_classes/output#transformers.utils.ModelOutput) を返すかどうか。

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

A [ImageClassifierOutputWithNoAttention](/docs/transformers/main/ja/main_classes/output#transformers.modeling_outputs.ImageClassifierOutputWithNoAttention) or a tuple of `torch.Tensor` (if `return_dict=False` is passed or when `config.return_dict=False`) comprising various elements depending on the configuration ([MobileViTConfig](/docs/transformers/main/ja/model_doc/mobilevit#transformers.MobileViTConfig)) and inputs.

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

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

- **loss** (`torch.Tensor`、shape `(1,)`、*optional*、`labels` が指定された場合に返されます) -- 分類損失（config.num_labels==1 の場合は回帰損失）。
- **logits** (`torch.Tensor`、形状 `(batch_size, config.num_labels)`) -- SoftMax 適用前の分類（または config.num_labels==1 の場合は回帰）スコア。
- **hidden_states** (`tuple(torch.Tensor)`、*optional*、`output_hidden_states=True` が渡された場合、または `config.output_hidden_states=True` の場合に返されます) -- `torch.Tensor` のタプル（モデルに埋め込み層がある場合はその出力用 1 つ、各ステージの出力用 1 つずつ）で、形状は `(batch_size, num_channels, height, width)` です。各ステージの出力におけるモデルの隠れ状態（特徴マップとも呼ばれます）。

例:

```python
>>> from transformers import AutoImageProcessor, MobileViTForImageClassification
>>> import torch
>>> from datasets import load_dataset

>>> dataset = load_dataset("huggingface/cats-image")
>>> image = dataset["test"]["image"][0]

>>> image_processor = AutoImageProcessor.from_pretrained("google/mobilenet_v2_1.0_224")
>>> model = MobileViTForImageClassification.from_pretrained("google/mobilenet_v2_1.0_224")

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

>>> with torch.no_grad():
...     logits = model(**inputs).logits

>>> # model predicts one of the 1000 ImageNet classes
>>> predicted_label = logits.argmax(-1).item()
>>> print(model.config.id2label[predicted_label])
...
```

## MobileViTForSemanticSegmentation[[transformers.MobileViTForSemanticSegmentation]]

#### transformers.MobileViTForSemanticSegmentation[[transformers.MobileViTForSemanticSegmentation]]

```python
transformers.MobileViTForSemanticSegmentation(config: MobileViTConfig)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/mobilevit/modeling_mobilevit.py#L859)

**パラメータ:**

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

Pascal VOC などの用途で、上部にセマンティックセグメンテーションヘッドを備えた MobileViT モデル。

このモデルは [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.MobileViTForSemanticSegmentation.forward]]

```python
forward(pixel_values: typing.Optional[torch.Tensor] = None, labels: typing.Optional[torch.Tensor] = None, output_hidden_states: bool | None = None, return_dict: bool | None = None, **kwargs)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/mobilevit/modeling_mobilevit.py#L870)

**パラメータ:**

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

labels (`torch.LongTensor`、shape `(batch_size, height, width)`、*任意*) : ロスの計算に使用する正解のセマンティックセグメンテーションマップ。インデックスは `[0, ..., config.num_labels - 1]` の範囲である必要があります。`config.num_labels > 1` の場合、分類ロス（Cross-Entropy）が計算されます。

output_hidden_states (`bool`, *任意*) : 全レイヤーの hidden states を返すかどうかを指定します。詳細は、返されるテンソルの `hidden_states` を参照してください。

return_dict (`bool`, *任意*) : プレーンなタプルではなく [ModelOutput](/docs/transformers/main/ja/main_classes/output#transformers.utils.ModelOutput) を返すかどうか。

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

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

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

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

- **loss** (`torch.Tensor`、shape `(1,)`、*optional*、`labels` が指定された場合に返されます) -- 分類損失（config.num_labels==1 の場合は回帰損失）。
- **logits** (`torch.Tensor`、形状 `(batch_size, config.num_labels, logits_height, logits_width)`) -- 各ピクセルの分類スコア。

  

  返される logits は、入力として渡された `pixel_values` と同じサイズであるとは限りません。これは、ユーザーが後処理として logits を元の画像サイズにリサイズする際に、2回の補間処理による品質の低下を避けるためです。常に logits の形状を確認し、必要に応じてリサイズしてください。

  
- **hidden_states** (`tuple(torch.Tensor)`、*optional*、`output_hidden_states=True` が渡された場合または `config.output_hidden_states=True` の場合に返されます) -- `torch.Tensor` のタプル（埋め込み層を持つモデルの場合、埋め込みの出力用 1 つ + 各層の出力用 1 つ）で、形状は `(batch_size, patch_size, hidden_size)` です。

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

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

例:

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

>>> 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("apple/deeplabv3-mobilevit-small")
>>> model = MobileViTForSemanticSegmentation.from_pretrained("apple/deeplabv3-mobilevit-small")

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

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

>>> # logits are of shape (batch_size, num_labels, height, width)
>>> logits = outputs.logits
```

