# DPT

## 概要

DPTモデルは、René Ranftl、Alexey Bochkovskiy、Vladlen Koltun によって [Vision Transformers for Dense Prediction](https://huggingface.co/papers/2103.13413) で提案されました。DPTは、セマンティックセグメンテーションや深度推定などの高密度予測タスクにおいて、[Vision Transformer (ViT)](vit) をバックボーンとして活用するモデルです。

論文の抄録は以下の通りです。

*我々は、dense vision transformers（高密度ビジョン・トランスフォーマー）を導入します。これは、dense prediction（高密度予測）タスクのバックボーンとして、畳み込みネットワークの代わりにビジョン・トランスフォーマーを活用するアーキテクチャです。ビジョン・トランスフォーマーの各段階からトークンを組み立て、さまざまな解像度で画像のような表現を生成し、畳み込みデコーダーを用いて段階的に結合することで、フル解像度の予測を行います。トランスフォーマーのバックボーンは、一定かつ比較的高い解像度で表現を処理し、すべての段階でグローバルな受容野を有します。これらの特性により、dense vision transformer は、完全な畳み込みネットワークと比較して、より細粒度かつグローバルに整合性のある予測を提供できます。実験により、このアーキテクチャが dense prediction タスクにおいて大幅な性能向上をもたらすことが示されました。特に、大量の学習データが利用可能な場合に顕著です。単眼深度推定では、最先端の完全な畳み込みネットワークと比較して、相対的な性能が最大 28% 向上することが観察されました。セマンティックセグメンテーションに適用した場合、dense vision transformers は ADE20K で 49.02% mIoU という新たな最先端性能を達成しました。さらに、このアーキテクチャは NYUv2、KITTI、Pascal Context などのより小さなデータセットでファインチューニングでき、それらでも新たな最先端性能を達成することが示されています。*

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

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

このモデルは [nielsr](https://huggingface.co/nielsr) によって提供されました。元のコードは [こちら](https://github.com/isl-org/DPT) で確認できます。

## 使用のコツ

DPTは[AutoBackbone](/docs/transformers/v5.23.0/ja/main_classes/backbones#transformers.AutoBackbone)クラスと互換性があります。これにより、`VitDetBackbone`や`Dinov2Backbone`など、ライブラリで利用可能なさまざまなコンピュータビジョンのバックボーンと組み合わせてDPTフレームワークを使用できます。以下のように作成できます。

```python
from transformers import Dinov2Config, DPTConfig, DPTForDepthEstimation

# initialize with a Transformer-based backbone such as DINOv2
# in that case, we also specify `reshape_hidden_states=False` to get feature maps of shape (batch_size, num_channels, height, width)
backbone_config = Dinov2Config.from_pretrained("facebook/dinov2-base", out_features=["stage1", "stage2", "stage3", "stage4"], reshape_hidden_states=False)

config = DPTConfig(backbone_config=backbone_config)
model = DPTForDepthEstimation(config=config)
```

## リソース

DPTの入門を支援するための、Hugging Face公式およびコミュニティ（🌎で示されます）のリソースのリストです。

- [DPTForDepthEstimation](/docs/transformers/v5.23.0/ja/model_doc/dpt#transformers.DPTForDepthEstimation)のデモノートブックは[こちら](https://github.com/NielsRogge/Transformers-Tutorials/tree/master/DPT)で確認できます。

- [セマンティックセグメンテーションタスクガイド](../tasks/semantic_segmentation)
- [単眼深度推定タスクガイド](../tasks/monocular_depth_estimation)

ここにリソースを掲載していただくことを希望される場合は、Pull Request を開いてください。レビューいたします。リソースは、既存のリソースと重複するのではなく、新しいものを示すことが望ましいです。

## DPTConfig[[transformers.DPTConfig]]

#### transformers.DPTConfig[[transformers.DPTConfig]]

```python
transformers.DPTConfig(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: None | int = 12, num_attention_heads: int | None = 12, intermediate_size: int | None = 3072, hidden_act: str = 'gelu', hidden_dropout_prob: float | int | None = 0.0, attention_probs_dropout_prob: float | int | None = 0.0, initializer_range: float = 0.02, layer_norm_eps: float | None = 1e-12, image_size: int | list[int] | tuple[int, int] | None = 384, patch_size: int | list[int] | tuple[int, int] | None = 16, num_channels: int | None = 3, is_hybrid: bool = False, qkv_bias: bool | None = True, backbone_out_indices: list[int] | tuple[int, ...] | None = (2, 5, 8, 11), readout_type: typing.Literal['ignore', 'add', 'project'] = 'project', reassemble_factors: list[int | float] | tuple[int | float, ...] = (4, 2, 1, 0.5), neck_hidden_sizes: list[int] | tuple[int, ...] = (96, 192, 384, 768), fusion_hidden_size: int = 256, head_in_index: int = -1, use_batch_norm_in_fusion_residual: bool | None = False, use_bias_in_fusion_residual: bool | None = None, add_projection: bool = False, use_auxiliary_head: bool | None = True, auxiliary_loss_weight: float = 0.4, semantic_loss_ignore_index: int = 255, semantic_classifier_dropout: float | int = 0.1, backbone_featmap_shape: list[int] | tuple[int, ...] | None = (1, 1024, 24, 24), neck_ignore_stages: list[int] | tuple[int, ...] = (0, 1), backbone_config: dict | transformers.configuration_utils.PreTrainedConfig | None = None, pooler_output_size: int | None = None, pooler_act: str = 'tanh')
```

[ソース](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/dpt/configuration_dpt.py#L27)

**パラメータ:**

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[int, list[int], tuple[int, int]]`、*任意*、デフォルトは`384`) : 各画像のサイズ（解像度）。

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

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

is_hybrid (`bool`、*任意*、デフォルトは `False`) : ハイブリッドバックボーンを使用するかどうか。DPT-Hybrid モデルの読み込み時に有用です。

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

backbone_out_indices (`list[int]`、*optional*、デフォルトは`[2, 5, 8, 11]`) : backboneから使用する中間hidden stateのインデックスです。

readout_type (`str`、*optional*、デフォルトは`"project"`) : ViTバックボーンの中間隠れ状態のリードアウトトークン（CLSトークン）を処理する際に使用するリードアウトタイプ。`"ignore"`、`"add"`、`"project"`のいずれかになります。 - "ignore"はCLSトークンを単に無視します。 - "add"は表現を足し合わせることで、CLSトークンの情報を他のすべてのトークンに伝達します。 - "project"は、他のすべてのトークンにリードアウトを連結してから、線形層とGELU非線形性を適用して元のフィーチャ次元Dに射影することで、他のトークンに情報を伝達します。

reassemble_factors (`list[int]`、*optional*、デフォルトは`[4, 2, 1, 0.5]`) : reassemble レイヤーのアップ/ダウンサンプリング係数です。

neck_hidden_sizes (`list[str]`、*optional*、デフォルトは `[96, 192, 384, 768]`) : バックボーンのフィーチャマップを投影する隠れ層サイズ。

fusion_hidden_size (`int`、*optional*、デフォルトは 256) : フュージョン前のチャネル数。

head_in_index (`int`、*任意*、デフォルトは -1) : ヘッドで使用する特徴のインデックス。

use_batch_norm_in_fusion_residual (`bool`, *任意*, デフォルトは `False`) : フュージョンブロックのプレアクティベーション残差ユニットでバッチ正規化を使用するかどうか。

use_bias_in_fusion_residual (`bool`、*任意*、デフォルトは`True`) : フュージョンブロックのpre-activate residualユニットでバイアスを使用するかどうか。

add_projection (`bool`, *任意*, デフォルトは `False`) : 深度推定ヘッドの前に投影層を追加するかどうか。

use_auxiliary_head (`bool`、*任意*、デフォルトは `True`) : 学習時に補助ヘッドを使用するかどうか。

auxiliary_loss_weight (`float`、*任意*、デフォルトは 0.4) : 補助ヘッドのクロスエントロピー損失の重み。

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

semantic_classifier_dropout (`float`、*任意*、デフォルトは 0.1) : 意味分類ヘッドの dropout 率です。

backbone_featmap_shape (`list[int]`、*optional*、デフォルトは`[1, 1024, 24, 24]`) : `hybrid`埋め込みタイプでのみ使用されます。バックボーンのフィーチャマップの形状です。

neck_ignore_stages (`list[int]`、*optional*、デフォルトは`[0, 1]`) : `hybrid`埋め込みタイプでのみ使用されます。無視する読み出し層のステージです。

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

pooler_output_size (`int`, *optional*) : プーラー層の次元数。None の場合、デフォルトで `hidden_size` になります。

pooler_act (`str`、*任意*、デフォルトは`"tanh"`) : pooler で使用される活性化関数。

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

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

例:

```python
>>> from transformers import DPTModel, DPTConfig

>>> # Initializing a DPT dpt-large style configuration
>>> configuration = DPTConfig()

>>> # Initializing a model from the dpt-large style configuration
>>> model = DPTModel(configuration)

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

## DPTImageProcessor[[transformers.DPTImageProcessor]]

#### transformers.DPTImageProcessor[[transformers.DPTImageProcessor]]

```python
transformers.DPTImageProcessor(**kwargs: *<class 'transformers.models.dpt.image_processing_dpt.DPTImageProcessorKwargs'>)
```

[ソース](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/dpt/image_processing_dpt.py#L110)

**パラメータ:**

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*、デフォルト値は`{'height' : 384, 'width': 384}`): モデルへの最大入力サイズを指定します。

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

crop_size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*、デフォルトは `None`) : `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*, *optional*, デフォルトは `True`) : 画像を正規化するかどうかを指定します。

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*, *任意*、デフォルトは `False`) : 画像にパディングを適用するかどうか。パディングは、バッチ内の最大サイズに合わせるか、画像ごとに固定の正方形サイズに合わせるかのいずれかで行われます。正確なパディング戦略はモデルによって異なります。

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*, デフォルトは `None`) : 画像を中央クロップするかどうか。

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

ensure_multiple_of (`int`, *kwargs*, *optional*, デフォルトは 1) : `do_resize` が `True` の場合、画像はこの値の倍数となるサイズにリサイズされます。`preprocess` の `ensure_multiple_of` で上書きできます。

size_divisor (`int`, *kwargs*) : 高さと幅の両方が割り切れることを保証するためのサイズ。

keep_aspect_ratio (`bool`, *kwargs*, *optional*, デフォルトは `False`) : `True` の場合、アスペクト比を維持したまま、画像を可能な限り最大のサイズにリサイズします。`preprocess` の `keep_aspect_ratio` によって上書きできます。

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

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

#### preprocess[[transformers.DPTImageProcessor.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.dpt.image_processing_dpt.DPTImageProcessorKwargs'>)
```

[ソース](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/dpt/image_processing_dpt.py#L135)

**パラメータ:**

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

ensure_multiple_of (`int`, *kwargs*, *optional*, デフォルトは 1) : `do_resize` が `True` の場合、画像はこの値の倍数となるサイズにリサイズされます。`preprocess` の `ensure_multiple_of` で上書きできます。

size_divisor (`int`, *kwargs*) : 高さと幅の両方が割り切れることを保証するためのサイズ。

keep_aspect_ratio (`bool`, *kwargs*, *optional*, デフォルトは `False`) : `True` の場合、アスペクト比を維持したまま、画像を可能な限り最大のサイズにリサイズします。`preprocess` の `keep_aspect_ratio` によって上書きできます。

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 を指定できます。

## DPTImageProcessorPil[[transformers.DPTImageProcessorPil]]

#### transformers.DPTImageProcessorPil[[transformers.DPTImageProcessorPil]]

```python
transformers.DPTImageProcessorPil(**kwargs: *<class 'transformers.models.dpt.image_processing_pil_dpt.DPTImageProcessorKwargs'>)
```

[ソース](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/dpt/image_processing_pil_dpt.py#L110)

**パラメータ:**

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*、デフォルト値は`{'height' : 384, 'width': 384}`): モデルへの最大入力サイズを指定します。

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

crop_size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*) : `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*, *optional*, デフォルトは `True`) : 画像を正規化するかどうかを指定します。

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*, *任意*、デフォルトは `False`) : 画像にパディングを適用するかどうか。パディングは、バッチ内の最大サイズに合わせるか、画像ごとに固定の正方形サイズに合わせるかのいずれかで行われます。正確なパディング戦略はモデルによって異なります。

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

ensure_multiple_of (`int`, *kwargs*, *optional*, デフォルトは 1) : `do_resize` が `True` の場合、画像はこの値の倍数となるサイズにリサイズされます。`preprocess` の `ensure_multiple_of` で上書きできます。

size_divisor (`int`, *kwargs*) : 高さと幅の両方が割り切れることを保証するためのサイズ。

keep_aspect_ratio (`bool`, *kwargs*, *optional*, デフォルトは `False`) : `True` の場合、アスペクト比を維持したまま、画像を可能な限り最大のサイズにリサイズします。`preprocess` の `keep_aspect_ratio` によって上書きできます。

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

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

#### preprocess[[transformers.DPTImageProcessorPil.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.dpt.image_processing_pil_dpt.DPTImageProcessorKwargs'>)
```

[ソース](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/dpt/image_processing_pil_dpt.py#L131)

**パラメータ:**

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

ensure_multiple_of (`int`, *kwargs*, *optional*, デフォルトは 1) : `do_resize` が `True` の場合、画像はこの値の倍数となるサイズにリサイズされます。`preprocess` の `ensure_multiple_of` で上書きできます。

size_divisor (`int`, *kwargs*) : 高さと幅の両方が割り切れることを保証するためのサイズ。

keep_aspect_ratio (`bool`, *kwargs*, *optional*, デフォルトは `False`) : `True` の場合、アスペクト比を維持したまま、画像を可能な限り最大のサイズにリサイズします。`preprocess` の `keep_aspect_ratio` によって上書きできます。

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.DPTImageProcessorPil.post_process_semantic_segmentation]]

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

[ソース](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/dpt/image_processing_pil_dpt.py#L268)

**パラメータ:**

outputs ([DPTForSemanticSegmentation](/docs/transformers/v5.23.0/ja/model_doc/dpt#transformers.DPTForSemanticSegmentation)) : モデルの生出力。

target_sizes (`list[tuple]`、*任意*) : バッチ内の各画像のターゲットサイズ（高さ、幅）を含むタプルのリスト（`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`が指定されている場合)。

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

#### post_process_depth_estimation[[transformers.DPTImageProcessorPil.post_process_depth_estimation]]

```python
post_process_depth_estimation(outputs: DepthEstimatorOutput, target_sizes: transformers.utils.generic.TensorType | list[tuple[int, int]] | None = None)
```

[ソース](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/dpt/image_processing_pil_dpt.py#L331)

`DepthEstimatorOutput`の生出力を、最終的な深度予測に変換します。

## DPTModel[[transformers.DPTModel]]

#### transformers.DPTModel[[transformers.DPTModel]]

```python
transformers.DPTModel(config: DPTConfig, add_pooling_layer: bool = True)
```

[ソース](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/dpt/modeling_dpt.py#L752)

**パラメータ:**

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

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

特定のヘッドを付加せず、生のhidden-statesを出力する素のDpt Model。

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

```python
forward(pixel_values: Tensor, **kwargs: *<class 'transformers.utils.generic.TransformersKwargs'>)
```

[ソース](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/dpt/modeling_dpt.py#L780)

**パラメータ:**

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

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

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

[DPTModel](/docs/transformers/v5.23.0/ja/model_doc/dpt#transformers.DPTModel)の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後のアテンション重み。自己アテンションヘッド内で加重平均を計算するために使用されます。
- **intermediate_activations** (`tuple(torch.Tensor)`, *オプション*) -- モデルの各層の隠れ状態を計算するために使用できる中間活性化値。

例:

```python
```

## DPTForDepthEstimation[[transformers.DPTForDepthEstimation]]

#### transformers.DPTForDepthEstimation[[transformers.DPTForDepthEstimation]]

```python
transformers.DPTForDepthEstimation(config: DPTConfig)
```

[ソース](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/dpt/modeling_dpt.py#L923)

**パラメータ:**

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

depth estimationヘッド（3つの畳み込み層で構成）を上部に備えたDPTモデル。KITTIやNYUv2などの用途に使用できます。

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

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

[ソース](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/dpt/modeling_dpt.py#L942)

**パラメータ:**

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` を使用します）。

labels (`torch.LongTensor`、形状 `(batch_size, height, width)`、*任意*) : ロスの計算に使用する正解の深度推定マップ。

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

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

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

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

- **loss** (`torch.Tensor`、shape `(1,)`、*optional*、`labels` が指定された場合に返されます) -- 分類損失（config.num_labels==1 の場合は回帰損失）。
- **predicted_depth** (`torch.Tensor`、形状 `(batch_size, height, width)`) -- 各ピクセルの予測深度。
- **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、および任意の初期埋め込み出力。
- **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 transformers import AutoImageProcessor, DPTForDepthEstimation
>>> import torch
>>> import numpy as np
>>> 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("Intel/dpt-large")
>>> model = DPTForDepthEstimation.from_pretrained("Intel/dpt-large")

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

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

>>> # interpolate to original size
>>> post_processed_output = image_processor.post_process_depth_estimation(
...     outputs,
...     target_sizes=[(image.height, image.width)],
... )

>>> # visualize the prediction
>>> predicted_depth = post_processed_output[0]["predicted_depth"]
>>> depth = predicted_depth * 255 / predicted_depth.max()
>>> depth = depth.detach().cpu().numpy()
>>> depth = Image.fromarray(depth.astype("uint8"))
```

## DPTForSemanticSegmentation[[transformers.DPTForSemanticSegmentation]]

#### transformers.DPTForSemanticSegmentation[[transformers.DPTForSemanticSegmentation]]

```python
transformers.DPTForSemanticSegmentation(config: DPTConfig)
```

[ソース](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/dpt/modeling_dpt.py#L1070)

**パラメータ:**

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

ADE20KやCityScapesなど、セマンティックセグメンテーションヘッドを上部に備えたDpt Model。

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

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

[ソース](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/dpt/modeling_dpt.py#L1086)

**パラメータ:**

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

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

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

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

[DPTForSemanticSegmentation](/docs/transformers/v5.23.0/ja/model_doc/dpt#transformers.DPTForSemanticSegmentation)の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 transformers import AutoImageProcessor, DPTForSemanticSegmentation
>>> 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("Intel/dpt-large-ade")
>>> model = DPTForSemanticSegmentation.from_pretrained("Intel/dpt-large-ade")

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

>>> outputs = model(**inputs)
>>> logits = outputs.logits
```

