# UNet2DModel

[UNet](https://huggingface.co/papers/1505.04597)モデルは、Ronneberger らによって生体医用画像のセグメンテーションのために最初に提案されましたが、入力と同じサイズの画像を出力するため、🤗 Diffusers でも広く使用されています。実際の拡散プロセスを担うため、拡散システムにおいて最も重要なコンポーネントの一つです。🤗 Diffusers には、次元数や条件付きモデルかどうかによっていくつかの UNet モデルのバリアントが存在します。ここでは 2D UNet モデルについて説明します。

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

*深層ネットワークの成功した学習には、数千枚のラベル付き訓練サンプルが必要であるという点について、大きな合意がある。本論文では、データ拡張を強力に活用することで、利用可能なラベル付きサンプルをより効率的に使用できるネットワークと学習戦略を提案する。このアーキテクチャは、コンテキストを捉えるための縮小パスと、正確な位置特定を可能にする対称的な拡大パスで構成される。このようなネットワークは、非常に少ない画像からエンドツーエンドで学習でき、電子顕微鏡スタックにおける神経構造のセグメンテーションに関するISBIチャレンジにおいて、従来の最良手法（スライディングウィンドウ畳み込みネットワーク）を上回ることを示す。透過光顕微鏡画像（位相差およびDIC）で学習した同じネットワークを用いて、ISBIセルトラッキングチャレンジ2015では、これらのカテゴリで大幅な差をつけて優勝した。さらに、このネットワークは高速である。最新のGPUでは、512x512画像のセグメンテーションに1秒未満しかかからない。完全な実装（Caffeベース）と学習済みネットワークは、http://lmb.informatik.uni-freiburg.de/people/ronneber/u-net で入手できる。*

## UNet2DModel[[diffusers.UNet2DModel]]

#### diffusers.UNet2DModel[[diffusers.UNet2DModel]]

```python
diffusers.UNet2DModel(sample_size: int | tuple[int, int] | None = None, in_channels: int = 3, out_channels: int = 3, center_input_sample: bool = False, time_embedding_type: str = 'positional', time_embedding_dim: int | None = None, freq_shift: int = 0, flip_sin_to_cos: bool = True, down_block_types: tuple[str, ...] = ('DownBlock2D', 'AttnDownBlock2D', 'AttnDownBlock2D', 'AttnDownBlock2D'), mid_block_type: str | None = 'UNetMidBlock2D', up_block_types: tuple[str, ...] = ('AttnUpBlock2D', 'AttnUpBlock2D', 'AttnUpBlock2D', 'UpBlock2D'), block_out_channels: tuple[int, ...] = (224, 448, 672, 896), layers_per_block: int = 2, mid_block_scale_factor: float = 1, downsample_padding: int = 1, downsample_type: str = 'conv', upsample_type: str = 'conv', dropout: float = 0.0, act_fn: str = 'silu', attention_head_dim: int | None = 8, norm_num_groups: int = 32, attn_norm_num_groups: int | None = None, norm_eps: float = 1e-05, resnet_time_scale_shift: str = 'default', add_attention: bool = True, class_embed_type: str | None = None, num_class_embeds: int | None = None, num_train_timesteps: int | None = None)
```

[ソース](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/unets/unet_2d.py#L39)

**パラメータ:**

sample_size (`int` または `tuple[int, int]`、*省略可能*、デフォルトは `None`) : 入力/出力サンプルの高さと幅。次元は `2 ** (len(block_out_channels) - 1)` の倍数である必要があります。

in_channels (`int`、*任意*、デフォルトは 3) : 入力サンプルのチャネル数。

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

center_input_sample (`bool`、*任意*、デフォルトは`False`) : 入力サンプルを中央揃けにするかどうか。

time_embedding_type (`str`、*任意*、デフォルトは`"positional"`) : 使用する時間埋め込みのタイプ。

freq_shift (`int`、*任意*、デフォルトは 0) : フーリエ時間埋め込みの周波数シフト。

flip_sin_to_cos (`bool`、*任意*、デフォルトは `True`) : Fourier 時間埋め込みにおいて sin を cos に反転させるかどうか。

down_block_types (`tuple[str]`、*任意*、デフォルトは`("DownBlock2D", "AttnDownBlock2D", "AttnDownBlock2D", "AttnDownBlock2D")`) : ダウンサンプルブロックの種類のタプル。

mid_block_type (`str`、*任意*、デフォルトは`"UNetMidBlock2D"`) : UNetの中央部分のブロックタイプ。`UNetMidBlock2D`または`None`のいずれかです。

up_block_types (`tuple[str]`、*任意*、デフォルトは`("AttnUpBlock2D", "AttnUpBlock2D", "AttnUpBlock2D", "UpBlock2D")`) : アップサンプリングブロックの種類のタプル。

block_out_channels (`tuple[int]`、*optional*、デフォルトは`(224, 448, 672, 896)`) : ブロックの出力チャネルのタプル。

layers_per_block (`int`、*任意*、デフォルトは`2`) : ブロックあたりのレイヤー数。

mid_block_scale_factor (`float`、*任意*、デフォルトは`1`) : mid ブロックのスケール係数です。

downsample_padding (`int`、*任意*、デフォルトは`1`) : ダウンサンプル畳み込みのパディング。

downsample_type (`str`、*任意*、デフォルトは`conv`) : ダウンサンプリング層のダウンサンプルタイプ。"conv" と "resnet" から選択します

upsample_type (`str`、*任意*、デフォルトは`conv`) : アップサンプリング層のアップサンプリングタイプ。"conv" と "resnet" から選択します

dropout (`float`、*任意*、デフォルトは 0.0) : 使用する dropout の確率。

act_fn (`str`、*任意*、デフォルトは`"silu"`) : 使用する活性化関数。

attention_head_dim (`int`、*任意*、デフォルトは`8`) : アテンションヘッドの次元数。

norm_num_groups (`int`、*任意*、デフォルトは`32`) : 正規化のグループ数です。

attn_norm_num_groups (`int`, *任意*, デフォルトは `None`) : 整数が設定されている場合、mid block の `Attention` レイヤーに、指定されたグループ数を持つ group norm レイヤーが作成されます。 `None` のままの場合、 `resnet_time_scale_shift` が `default` に設定されている場合のみ group norm レイヤーが作成され、作成される場合は `norm_num_groups` 個のグループを持ちます。

norm_eps (`float`、*任意*、デフォルトは`1e-5`) : 正規化のためのepsilonです。

resnet_time_scale_shift (`str`、*任意*、デフォルトは `"default"`) : ResNet ブロック用の時間スケールシフト設定（`ResnetBlock2D` を参照）。`default` または `scale_shift` から選択します。

class_embed_type (`str`、*任意*、デフォルトは`None`) : 最終的に time embeddings と加算される class embedding の種類を指定します。`None`、`"timestep"`、または`"identity"`から選択します。

num_class_embeds (`int`, *任意*, デフォルトは `None`) : `class_embed_type` が `None` の場合にクラス条件付けを行う際、学習可能な埋め込み行列の `time_embed_dim` への射影対象となる入力次元。

ノイズ付きサンプルとタイムステップを受け取り、サンプル形状の出力を返す2次元UNetモデル。

このモデルは [ModelMixin](/docs/diffusers/main/ja/api/models/overview#diffusers.ModelMixin) を継承しています。すべてのモデルに実装されている汎用的なメソッド（ダウンロードや保存など）については、スーパークラスのドキュメントを参照してください。

#### forward[[diffusers.UNet2DModel.forward]]

```python
forward(sample: Tensor, timestep: typing.Union[torch.Tensor, float, int], class_labels: typing.Optional[torch.Tensor] = None, return_dict: bool = True)
```

[ソース](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/unets/unet_2d.py#L249)

**パラメータ:**

sample (`torch.Tensor`) : 以下の形状 `(batch, channel, height, width)` を持つノイズ付き入力テンソル。

timestep (`torch.Tensor` または `float` または `int`) : 入力からノイズを除去するためのタイムステップ数。

class_labels (`torch.Tensor`、*任意*、デフォルトは`None`) : 条件付け用の任意のクラスラベル。その埋め込みは、タイムステップの埋め込みと加算されます。

return_dict (`bool`、*任意*、デフォルトは`True`) : プレーンなタプルではなく[UNet2DOutput](/docs/diffusers/main/ja/api/models/unet2d#diffusers.models.unets.unet_2d.UNet2DOutput)を返すかどうか。

**戻り値:** [UNet2DOutput](/docs/diffusers/main/ja/api/models/unet2d#diffusers.models.unets.unet_2d.UNet2DOutput) または `tuple`

`return_dict` が True の場合、[UNet2DOutput](/docs/diffusers/main/ja/api/models/unet2d#diffusers.models.unets.unet_2d.UNet2DOutput) が返され、それ以外の場合は、最初の要素がサンプルテンソルである `tuple` が返されます。

[UNet2DModel](/docs/diffusers/main/ja/api/models/unet2d#diffusers.UNet2DModel)のforwardメソッドです。

## UNet2DOutput[[diffusers.models.unets.unet_2d.UNet2DOutput]]

#### diffusers.models.unets.unet_2d.UNet2DOutput[[diffusers.models.unets.unet_2d.UNet2DOutput]]

```python
diffusers.models.unets.unet_2d.UNet2DOutput(sample: Tensor)
```

[ソース](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/unets/unet_2d.py#L27)

**パラメータ:**

sample (`torch.Tensor`、形状 `(batch_size, num_channels, height, width)`) : モデルの最終層から出力される隠れ状態です。

[UNet2DModel](/docs/diffusers/main/ja/api/models/unet2d#diffusers.UNet2DModel)の出力です。

