# MobileNet V2

[MobileNet V2](https://huggingface.co/papers/1801.04381)는 더 효율적인 아키텍처를 통해 모바일 기기에서의 성능을 향상시킵니다. 이 모델은 인버티드 레지듀얼 블록과 리니어 보틀넥을 사용하여 데이터의 표현을 먼저 작게 시작하고, 처리를 위해 확장한 뒤 다시 축소하여 계산량을 줄입니다. 또한 단순화된 설계에도 불구하고 정확도를 유지하기 위해 비선형성을 제거합니다. [MobileNet V1](./mobilenet_v1)과 마찬가지로 효율성을 위해 depthwise separable convolution을 사용합니다.

모든 원본 MobileNet 체크포인트는 [Google](https://huggingface.co/google?search_models=mobilenet) 조직에서 찾을 수 있습니다.

> [!TIP]
> 오른쪽 사이드바의 MobileNet V2 모델에 클릭하여 MobileNet을 다양한 비전 작업에 적용하는 방법에 대한 추가 예제를 확인하세요.

아래 예제는 [Pipeline](/docs/transformers/main/ko/main_classes/pipelines#transformers.Pipeline) 또는 [AutoModel](/docs/transformers/main/ko/model_doc/auto#transformers.AutoModel) 클래스를 사용하여 이미지를 분류하는 방법을 보여줍니다.

```python
from transformers import pipeline

pipeline = pipeline(
    task="image-classification",
    model="google/mobilenet_v2_1.4_224",
    device=0
)
pipeline("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg")
```

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

from transformers import AutoImageProcessor, AutoModelForImageClassification

image_processor = AutoImageProcessor.from_pretrained(
    "google/mobilenet_v2_1.4_224",
)
model = AutoModelForImageClassification.from_pretrained(
    "google/mobilenet_v2_1.4_224",
    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}")
```

## The input is a single word "Notes".

참고

- Classification 체크포인트 이름은 `mobilenet_v2_{depth_multiplier}_{resolution}` 패턴을 따르며, 예를 들어 `mobilenet_v2_1.4_224`와 같습니다. `1.4`는 depth multiplier이고, `224`는 이미지 해상도입니다. Segmentation 체크포인트 이름은 `deeplabv3_mobilenet_v2_{depth_multiplier}_{resolution}` 패턴을 따릅니다.
- 특정 크기의 이미지로 학습되었지만, 모델 아키텍처는 다른 크기의 이미지(최소 32x32)도 처리할 수 있습니다. [MobileNetV2ImageProcessor](/docs/transformers/main/ko/model_doc/mobilenet_v2#transformers.MobileNetV2ImageProcessor)가 필요한 전처리를 수행합니다.
- MobileNet은 1000개의 클래스를 가진 [ImageNet-1k](https://huggingface.co/datasets/ILSVRC/imagenet-1k) 데이터셋으로 사전 학습됩니다. 그러나 모델은 실제로 1001개의 클래스를 예측합니다. 추가된 클래스는 인덱스 0에 있는 "background" 클래스입니다.
- 분할 모델은 [DeepLabV3+](https://huggingface.co/papers/1802.02611) 헤드를 사용하며, 이 헤드는 [PASCAL VOC](https://huggingface.co/datasets/merve/pascal-voc)와 같은 데이터셋으로 사전 학습된 경우가 많습니다.
- 원본 TensorFlow 체크포인트는 입력 이미지 크기에 따라 패딩 양이 결정되므로 추론 시 패딩 양을 결정합니다. PyTorch의 기본 패딩 동작을 사용하려면 [MobileNetV2Config](/docs/transformers/main/ko/model_doc/mobilenet_v2#transformers.MobileNetV2Config)에서 `tf_padding=False`를 설정하세요.

    ```python
    from transformers import MobileNetV2Config

    config = MobileNetV2Config.from_pretrained("google/mobilenet_v2_1.4_224", tf_padding=True)
    ```

- Transformers 구현은 다음 기능을 지원하지 않습니다.
  - 7x7 평균 풀링(stride 2) 옵션 대신 전역 평균 풀링을 사용합니다. 입력이 더 큰 경우, 1x1 픽셀보다 큰 풀링 출력을 생성합니다.
  - `output_hidden_states=True`를 사용하면 *모든* 중간 hidden state가 반환됩니다. 이를 통해 특정 레이어의 출력을 추출하여 다른 하위 작업에 사용하는 것은 불가능합니다.
  - …
  - 분할 모델의 경우, DeepLabV3+ 헤드에서 사용하지 않음에도 불구하고 백본의 최종 컨볼루션 레이어가 계산됩니다.

## MobileNetV2Config[[transformers.MobileNetV2Config]]

#### transformers.MobileNetV2Config[[transformers.MobileNetV2Config]]

```python
transformers.MobileNetV2Config(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] = 224, depth_multiplier: float | int = 1.0, depth_divisible_by: int = 8, min_depth: int = 8, expand_ratio: float | int = 6.0, output_stride: int = 32, first_layer_is_expansion: bool = True, finegrained_output: bool = True, hidden_act: str = 'relu6', tf_padding: bool = True, classifier_dropout_prob: float | int = 0.8, initializer_range: float = 0.02, layer_norm_eps: float = 0.001, semantic_loss_ignore_index: int = 255)
```

[소스](https://github.com/huggingface/transformers/blob/main/src/transformers/models/mobilenet_v2/configuration_mobilenet_v2.py#L24)

**매개변수:**

num_channels (`int`, *선택 사항*, 기본값 `3`) : 입력 채널의 수입니다.

image_size (`Union[int, list[int], tuple[int, int]]`, *선택*, 기본값 `224`) : 각 이미지의 크기(해상도).

depth_multiplier (`Union[float, int]`, *선택 사항*, 기본값 `1.0`) : 각 레이어의 채널 수를 축소하거나 확장합니다. 이 값은 "alpha" 또는 "width multiplier"라고도 불립니다.

depth_divisible_by (`int`, *선택 사항*, 기본값 8) : 각 레이어의 채널 수는 항상 이 숫자의 배수가 됩니다.

min_depth (`int`, *선택 사항*, 기본값 8) : 모든 레이어는 최소한 이 수만큼의 채널을 가집니다.

expand_ratio (`float`, *선택 사항*, 기본값 6.0) : 각 블록의 첫 번째 레이어의 출력 채널 수는 입력 채널 수에 확장 비율을 곱한 값입니다.

output_stride (`int`, *선택 사항*, 기본값 32) : 입력 및 출력 특징 맵의 공간 해상도 비율입니다. 기본적으로 모델은 입력 차원을 32배로 축소합니다. `output_stride`가 8 또는 16인 경우, 모델은 depthwise 레이어에서 일반 합성곱 대신 dilated convolutions를 사용하여 특징 맵이 입력 이미지보다 8배 또는 16배 이상 작아지지 않도록 합니다.

first_layer_is_expansion (`bool`, *선택 사항*, 기본값 `True`) : 첫 번째 컨볼루션 레이어가 첫 번째 확장 블록의 확장 레이어이기도 한 경우 True입니다.

finegrained_output (`bool`, *선택 사항*, 기본값 `True`) : true인 경우, `depth_multiplier`가 1보다 작더라도 최종 컨볼루션 레이어의 출력 채널 수가 크게(1280) 유지됩니다.

hidden_act (`str`, *선택 사항*, 기본값 `relu6`) : 디코더의 비선형 활성화 함수(함수 또는 문자열). 예를 들어, `"gelu"`, `"relu"`, `"silu"` 등.

tf_padding (`bool`, *선택 사항*, 기본값 `True`) : 컨볼루션 레이어에 TensorFlow 패딩 규칙을 사용할지 여부.

classifier_dropout_prob (`Union[float, int]`, *선택 사항*, 기본값 `0.8`) : 분류기의 dropout 비율입니다.

initializer_range (`float`, *선택 사항*, 기본값 `0.02`) : 모든 가중치 행렬을 초기화하는 truncated_normal_initializer의 표준 편차입니다.

layer_norm_eps (`float`, *선택 사항*, 기본값 `0.001`) : 레이어 정규화 레이어에서 사용되는 epsilon 값입니다.

semantic_loss_ignore_index (`int`, *선택 사항*, 기본값 `255`) : 시맨틱 세그멘테이션 모델의 손실 함수가 무시하는 인덱스입니다.

이것은 MobileNetV2Model의 구성을 저장하기 위한 구성 클래스입니다. 지정된 인자에 따라 Mobilenet V2 모델을 인스턴스화하여 모델 아키텍처를 정의하는 데 사용됩니다. 기본값으로 구성을 인스턴스화하면 [google/mobilenet_v2_1.0_224](https://huggingface.co/google/mobilenet_v2_1.0_224)와 유사한 구성이 생성됩니다.

Configuration 객체는 [PreTrainedConfig](/docs/transformers/main/ko/main_classes/configuration#transformers.PreTrainedConfig)를 상속하며, 모델 출력을 제어하는 데 사용할 수 있습니다. 자세한 내용은 [PreTrainedConfig](/docs/transformers/main/ko/main_classes/configuration#transformers.PreTrainedConfig)의 문서를 참고하세요.

예:

```python
>>> from transformers import MobileNetV2Config, MobileNetV2Model

>>> # Initializing a "mobilenet_v2_1.0_224" style configuration
>>> configuration = MobileNetV2Config()

>>> # Initializing a model from the "mobilenet_v2_1.0_224" style configuration
>>> model = MobileNetV2Model(configuration)

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

## MobileNetV2ImageProcessor[[transformers.MobileNetV2ImageProcessor]]

#### transformers.MobileNetV2ImageProcessor[[transformers.MobileNetV2ImageProcessor]]

```python
transformers.MobileNetV2ImageProcessor(**kwargs: *<class 'transformers.models.mobilenet_v2.image_processing_mobilenet_v2.MobileNetV2ImageProcessorKwargs'>)
```

[소스](https://github.com/huggingface/transformers/blob/main/src/transformers/models/mobilenet_v2/image_processing_mobilenet_v2.py#L49)

**매개변수:**

do_convert_rgb (`bool`, *kwargs*, *선택*) : 이미지를 RGB로 변환할지 여부.

do_resize (`bool`, *kwargs*, *선택 사항*, 기본값 `True`) : 이미지를 리사이즈할지 여부.

size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*, 기본값 `{'shortest_edge' : 256}`): 모델에 입력되는 최대 차원을 설명합니다.

default_to_square (`bool`, *kwargs*, *선택 사항*, 기본값 `False`) : size가 int인 경우 리사이즈 시 정사각형 이미지로 설정할지 여부.

crop_size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*, 기본값 `{'height' : 224, 'width': 224}`): `center_crop`를 적용한 후 출력 이미지의 크기.

resample (`Annotated[Union[int, PILImageResampling, NoneType], None]`, *kwargs*, 기본값 `2`) : 이미지를 리사이즈할 때 사용할 리샘플링 필터입니다. 이는 `PILImageResampling` enum 중 하나일 수 있습니다. `do_resize`가 `True`로 설정된 경우에만 효과가 있습니다.

do_rescale (`bool`, *kwargs*, *선택 사항*, 기본값 `True`) : 이미지를 다시 스케일링할지 여부.

rescale_factor (`float`, *kwargs*, *선택 사항*, 기본값 `0.00392156862745098`) : `do_rescale`이 `True`로 설정된 경우 이미지를 재조정하는 데 사용되는 재조정 계수입니다.

do_normalize (`bool`, *kwargs*, *선택 사항*, 기본값 `True`) : 이미지를 정규화할지 여부.

image_mean (`Union[float, list[float], tuple[float, ...]]`, *kwargs*, *선택*, 기본값은 `[0.5, 0.5, 0.5]`) : 정규화에 사용할 이미지 평균입니다. `do_normalize`가 `True`로 설정된 경우에만 효과가 있습니다.

image_std (`Union[float, list[float], tuple[float, ...]]`, *kwargs*, *선택*, 기본값 `[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*, *선택 사항*, 기본값 `True`) : 이미지를 중앙 크롭할지 여부.

data_format (`Union[str, ~image_utils.ChannelDimension]`, *kwargs*, *선택*) : `ChannelDimension.FIRST`만 지원됩니다. 느린 프로세서와의 호환성을 위해 추가되었습니다.

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*, *선택*) : 이미지의 크기에 따른 그룹화를 비활성화하여 이미지를 배치 대신 개별적으로 처리할지 여부입니다. None인 경우, 이미지가 CPU에 있으면 True, 그렇지 않으면 False로 설정됩니다. 이 선택은 https://github.com/huggingface/transformers/pull/38157에 자세히 설명된 경험적 관찰에 기반합니다.

image_seq_length (`int`, *kwargs*, *선택*) : 입력의 각 이미지에 사용할 이미지 토큰의 수입니다. 하위 호환성을 위해 추가되었지만, 향후 모델에서는 프로세서 속성으로 설정해야 합니다.

do_reduce_labels (`bool`, *kwargs*, *선택 사항*, 기본값은 `self.do_reduce_labels`) : 세그멘테이션 맵의 모든 라벨 값을 1만큼 줄일지 여부입니다. 일반적으로 0을 배경으로 사용하고 배경 자체가 데이터셋의 모든 클래스에 포함되지 않는 데이터셋(예: ADE20k)에서 사용됩니다. 배경 라벨은 255로 대체됩니다.

MobileNetV2ImageProcessor 이미지 프로세서를 생성합니다.

#### preprocess[[transformers.MobileNetV2ImageProcessor.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.mobilenet_v2.image_processing_mobilenet_v2.MobileNetV2ImageProcessorKwargs'>)
```

[소스](https://github.com/huggingface/transformers/blob/main/src/transformers/models/mobilenet_v2/image_processing_mobilenet_v2.py#L69)

**매개변수:**

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*, *선택*) : 이미지를 RGB로 변환할지 여부.

do_resize (`bool`, *kwargs*, *선택*) : 이미지를 리사이즈할지 여부.

size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*) : 모델의 최대 입력 차원을 설명합니다.

default_to_square (`bool`, *kwargs*, *선택*) : 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` enum 중 하나를 사용할 수 있습니다. `do_resize`가 `True`로 설정된 경우에만 효과가 있습니다.

do_rescale (`bool`, *kwargs*, *선택*) : 이미지를 다시 스케일링할지 여부.

rescale_factor (`float`, *kwargs*, *선택*) : `do_rescale`가 `True`로 설정된 경우 이미지를 재조정하는 데 사용되는 재조정 계수입니다.

do_normalize (`bool`, *kwargs*, *선택*) : 이미지를 정규화할지 여부.

image_mean (`Union[float, list[float], tuple[float, ...]]`, *kwargs*, *선택*) : 정규화에 사용할 이미지 평균값. `do_normalize`이 `True`로 설정된 경우에만 효과가 있습니다.

image_std (`Union[float, list[float], tuple[float, ...]]`, *kwargs*, *선택*) : 정규화에 사용할 이미지 표준 편차. `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*, *선택*) : 이미지를 중앙 크롭할지 여부.

data_format (`Union[str, ~image_utils.ChannelDimension]`, *kwargs*, *선택*) : `ChannelDimension.FIRST`만 지원됩니다. 느린 프로세서와의 호환성을 위해 추가되었습니다.

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*, *선택*) : 이미지의 크기에 따른 그룹화를 비활성화하여 이미지를 배치 대신 개별적으로 처리할지 여부입니다. None인 경우, 이미지가 CPU에 있으면 True, 그렇지 않으면 False로 설정됩니다. 이 선택은 https://github.com/huggingface/transformers/pull/38157에 자세히 설명된 경험적 관찰에 기반합니다.

image_seq_length (`int`, *kwargs*, *선택*) : 입력의 각 이미지에 사용할 이미지 토큰의 수입니다. 하위 호환성을 위해 추가되었지만, 향후 모델에서는 프로세서 속성으로 설정해야 합니다.

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_type을 지정할 수 있습니다.

#### post_process_semantic_segmentation[[transformers.MobileNetV2ImageProcessor.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/mobilenet_v2/image_processing_mobilenet_v2.py#L184)

**매개변수:**

outputs ([MobileNetV2ForSemanticSegmentation](/docs/transformers/main/ko/model_doc/mobilenet_v2#transformers.MobileNetV2ForSemanticSegmentation)) : 모델의 원시 출력.

target_sizes (`list[tuple[int, int]]`, *선택 사항*) : 각 예측의 요청된 최종 크기(높이, 너비)에 해당하는 튜플 목록.

return_segmentation_scores (`bool`, *선택 사항*, 기본값 `False`) : 분할 맵과 함께 분할 점수를 반환할지 여부입니다. `True`인 경우, 반환된 리스트의 각 요소는 `segmentation` 필드(클래스 ID, shape `(height, width)`)와 `segmentation_scores` 필드(shape `(num_classes, height, width)`)를 가진 `SemanticSegmentationPostProcessorOutput`입니다.

**반환값:** `list[torch.Tensor]` 또는 `list[SemanticSegmentationPostProcessorOutput]`

`return_segmentation_scores=False`(기본값)인 경우, 각 항목이 클래스 ID를 가진 `(height, width)` 모양의 세그멘테이션 맵인 `batch_size` 길이의 리스트를 반환합니다. `return_segmentation_scores=True`인 경우, `segmentation`(클래스 ID, `(height, width)` 모양)와 `segmentation_scores`(`(num_classes, height, width)` 모양) 필드를 가진 `SemanticSegmentationPostProcessorOutput` 리스트를 반환합니다. 두 경우 모두 `(height, width)`는 대상 크기(`target_sizes`가 지정된 경우)에 해당합니다.

[MobileNetV2ForSemanticSegmentation](/docs/transformers/main/ko/model_doc/mobilenet_v2#transformers.MobileNetV2ForSemanticSegmentation)의 출력을 의미 분할 맵으로 변환합니다.

## MobileNetV2ImageProcessorPil[[transformers.MobileNetV2ImageProcessorPil]]

#### transformers.MobileNetV2ImageProcessorPil[[transformers.MobileNetV2ImageProcessorPil]]

```python
transformers.MobileNetV2ImageProcessorPil(**kwargs: *<class 'transformers.models.mobilenet_v2.image_processing_pil_mobilenet_v2.MobileNetV2ImageProcessorKwargs'>)
```

[소스](https://github.com/huggingface/transformers/blob/main/src/transformers/models/mobilenet_v2/image_processing_pil_mobilenet_v2.py#L57)

**매개변수:**

do_convert_rgb (`bool`, *kwargs*, *선택*) : 이미지를 RGB로 변환할지 여부.

do_resize (`bool`, *kwargs*, *선택 사항*, 기본값 `True`) : 이미지를 리사이즈할지 여부.

size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*, 기본값 `{'shortest_edge' : 256}`): 모델에 입력되는 최대 차원을 설명합니다.

default_to_square (`bool`, *kwargs*, *선택 사항*, 기본값 `False`) : size가 int인 경우 리사이즈 시 정사각형 이미지로 설정할지 여부.

crop_size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*, 기본값 `{'height' : 224, 'width': 224}`): `center_crop`를 적용한 후 출력 이미지의 크기.

resample (`Annotated[Union[int, PILImageResampling, NoneType], None]`, *kwargs*, 기본값 `2`) : 이미지를 리사이즈할 때 사용할 리샘플링 필터입니다. 이는 `PILImageResampling` enum 중 하나일 수 있습니다. `do_resize`가 `True`로 설정된 경우에만 효과가 있습니다.

do_rescale (`bool`, *kwargs*, *선택 사항*, 기본값 `True`) : 이미지를 다시 스케일링할지 여부.

rescale_factor (`float`, *kwargs*, *선택 사항*, 기본값 `0.00392156862745098`) : `do_rescale`이 `True`로 설정된 경우 이미지를 재조정하는 데 사용되는 재조정 계수입니다.

do_normalize (`bool`, *kwargs*, *선택 사항*, 기본값 `True`) : 이미지를 정규화할지 여부.

image_mean (`Union[float, list[float], tuple[float, ...]]`, *kwargs*, *선택*, 기본값은 `[0.5, 0.5, 0.5]`) : 정규화에 사용할 이미지 평균입니다. `do_normalize`가 `True`로 설정된 경우에만 효과가 있습니다.

image_std (`Union[float, list[float], tuple[float, ...]]`, *kwargs*, *선택*, 기본값 `[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*, *선택 사항*, 기본값 `True`) : 이미지를 중앙 크롭할지 여부.

data_format (`Union[str, ~image_utils.ChannelDimension]`, *kwargs*, *선택*) : `ChannelDimension.FIRST`만 지원됩니다. 느린 프로세서와의 호환성을 위해 추가되었습니다.

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*, *선택*) : 이미지의 크기에 따른 그룹화를 비활성화하여 이미지를 배치 대신 개별적으로 처리할지 여부입니다. None인 경우, 이미지가 CPU에 있으면 True, 그렇지 않으면 False로 설정됩니다. 이 선택은 https://github.com/huggingface/transformers/pull/38157에 자세히 설명된 경험적 관찰에 기반합니다.

image_seq_length (`int`, *kwargs*, *선택*) : 입력의 각 이미지에 사용할 이미지 토큰의 수입니다. 하위 호환성을 위해 추가되었지만, 향후 모델에서는 프로세서 속성으로 설정해야 합니다.

do_reduce_labels (`bool`, *kwargs*, *선택 사항*, 기본값은 `self.do_reduce_labels`) : 세그멘테이션 맵의 모든 라벨 값을 1만큼 줄일지 여부입니다. 일반적으로 0을 배경으로 사용하고 배경 자체가 데이터셋의 모든 클래스에 포함되지 않는 데이터셋(예: ADE20k)에서 사용됩니다. 배경 라벨은 255로 대체됩니다.

MobileNetV2ImageProcessor 이미지 프로세서를 생성합니다.

#### preprocess[[transformers.MobileNetV2ImageProcessorPil.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.mobilenet_v2.image_processing_pil_mobilenet_v2.MobileNetV2ImageProcessorKwargs'>)
```

[소스](https://github.com/huggingface/transformers/blob/main/src/transformers/models/mobilenet_v2/image_processing_pil_mobilenet_v2.py#L77)

**매개변수:**

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*, *선택*) : 이미지를 RGB로 변환할지 여부.

do_resize (`bool`, *kwargs*, *선택*) : 이미지를 리사이즈할지 여부.

size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*) : 모델의 최대 입력 차원을 설명합니다.

default_to_square (`bool`, *kwargs*, *선택*) : 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` enum 중 하나를 사용할 수 있습니다. `do_resize`가 `True`로 설정된 경우에만 효과가 있습니다.

do_rescale (`bool`, *kwargs*, *선택*) : 이미지를 다시 스케일링할지 여부.

rescale_factor (`float`, *kwargs*, *선택*) : `do_rescale`가 `True`로 설정된 경우 이미지를 재조정하는 데 사용되는 재조정 계수입니다.

do_normalize (`bool`, *kwargs*, *선택*) : 이미지를 정규화할지 여부.

image_mean (`Union[float, list[float], tuple[float, ...]]`, *kwargs*, *선택*) : 정규화에 사용할 이미지 평균값. `do_normalize`이 `True`로 설정된 경우에만 효과가 있습니다.

image_std (`Union[float, list[float], tuple[float, ...]]`, *kwargs*, *선택*) : 정규화에 사용할 이미지 표준 편차. `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*, *선택*) : 이미지를 중앙 크롭할지 여부.

data_format (`Union[str, ~image_utils.ChannelDimension]`, *kwargs*, *선택*) : `ChannelDimension.FIRST`만 지원됩니다. 느린 프로세서와의 호환성을 위해 추가되었습니다.

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*, *선택*) : 이미지의 크기에 따른 그룹화를 비활성화하여 이미지를 배치 대신 개별적으로 처리할지 여부입니다. None인 경우, 이미지가 CPU에 있으면 True, 그렇지 않으면 False로 설정됩니다. 이 선택은 https://github.com/huggingface/transformers/pull/38157에 자세히 설명된 경험적 관찰에 기반합니다.

image_seq_length (`int`, *kwargs*, *선택*) : 입력의 각 이미지에 사용할 이미지 토큰의 수입니다. 하위 호환성을 위해 추가되었지만, 향후 모델에서는 프로세서 속성으로 설정해야 합니다.

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_type을 지정할 수 있습니다.

#### post_process_semantic_segmentation[[transformers.MobileNetV2ImageProcessorPil.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/mobilenet_v2/image_processing_pil_mobilenet_v2.py#L180)

**매개변수:**

outputs ([MobileNetV2ForSemanticSegmentation](/docs/transformers/main/ko/model_doc/mobilenet_v2#transformers.MobileNetV2ForSemanticSegmentation)) : 모델의 원시 출력.

target_sizes (`list[tuple[int, int]]`, *선택 사항*) : 각 예측의 요청된 최종 크기(높이, 너비)에 해당하는 튜플 목록.

return_segmentation_scores (`bool`, *선택 사항*, 기본값 `False`) : 분할 맵과 함께 분할 점수를 반환할지 여부입니다. `True`인 경우, 반환된 리스트의 각 요소는 `segmentation` 필드(클래스 ID, shape `(height, width)`)와 `segmentation_scores` 필드(shape `(num_classes, height, width)`)를 가진 `SemanticSegmentationPostProcessorOutput`입니다.

**반환값:** `list[torch.Tensor]` 또는 `list[SemanticSegmentationPostProcessorOutput]`

`return_segmentation_scores=False`(기본값)인 경우, 각 항목이 클래스 ID를 가진 `(height, width)` 모양의 세그멘테이션 맵인 `batch_size` 길이의 리스트를 반환합니다. `return_segmentation_scores=True`인 경우, `segmentation`(클래스 ID, `(height, width)` 모양)와 `segmentation_scores`(`(num_classes, height, width)` 모양) 필드를 가진 `SemanticSegmentationPostProcessorOutput` 리스트를 반환합니다. 두 경우 모두 `(height, width)`는 대상 크기(`target_sizes`가 지정된 경우)에 해당합니다.

[MobileNetV2ForSemanticSegmentation](/docs/transformers/main/ko/model_doc/mobilenet_v2#transformers.MobileNetV2ForSemanticSegmentation)의 출력을 의미 분할 맵으로 변환합니다.

## MobileNetV2Model[[transformers.MobileNetV2Model]]

#### transformers.MobileNetV2Model[[transformers.MobileNetV2Model]]

```python
transformers.MobileNetV2Model(config: MobileNetV2Config, add_pooling_layer: bool = True)
```

[소스](https://github.com/huggingface/transformers/blob/main/src/transformers/models/mobilenet_v2/modeling_mobilenet_v2.py#L260)

**매개변수:**

config ([MobileNetV2Config](/docs/transformers/main/ko/model_doc/mobilenet_v2#transformers.MobileNetV2Config)) : 모델의 모든 매개변수를 포함하는 모델 구성 클래스입니다. 구성 파일로 초기화하는 것은 모델과 관련된 가중치를 로드하지 않으며, 구성 정보만 로드합니다. 모델 가중치를 로드하려면 [from_pretrained()](/docs/transformers/main/ko/main_classes/model#transformers.PreTrainedModel.from_pretrained) 메서드를 확인하세요.

add_pooling_layer (`bool`, *선택 사항*, 기본값 `True`) : 풀링 레이어를 추가할지 여부

특정 헤드가 위에 없는 상태의 Mobilenet V2 모델로, 원시 hidden-states를 출력합니다.

이 모델은 [PreTrainedModel](/docs/transformers/main/ko/main_classes/model#transformers.PreTrainedModel)에서 상속됩니다. 라이브러리가 모든 모델에 대해 구현하는 일반적 메서드(다운로드 또는 저장, 입력 임베딩 크기 조정, 헤드 프루닝 등)에 대해서는 상위 클래스 문서를 확인하세요.

이 모델은 또한 PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module)의 하위 클래스입니다. 일반적인 PyTorch Module처럼 사용하며, 일반적인 사용법과 동작에 관한 모든 사항은 PyTorch 문서를 참조하세요.

#### forward[[transformers.MobileNetV2Model.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/mobilenet_v2/modeling_mobilenet_v2.py#L325)

**매개변수:**

pixel_values (`torch.Tensor`, shape `(batch_size, num_channels, image_size, image_size)`, *선택 사항*) : 입력 이미지에 해당하는 텐서입니다. 픽셀 값은 [MobileNetV2ImageProcessor](/docs/transformers/main/ko/model_doc/mobilenet_v2#transformers.MobileNetV2ImageProcessor)를 사용하여 얻을 수 있습니다. 자세한 내용은 [MobileNetV2ImageProcessor.__call__()](/docs/transformers/main/ko/model_doc/molmo2#transformers.Molmo2ImageProcessor.__call__)를 참조하세요 (`processor_class`는 이미지 처리에 [MobileNetV2ImageProcessor](/docs/transformers/main/ko/model_doc/mobilenet_v2#transformers.MobileNetV2ImageProcessor)를 사용합니다).

output_hidden_states (`bool`, *선택 사항*) : 모든 레이어의 hidden states를 반환할지 여부. 자세한 내용은 반환되는 텐서 중 `hidden_states` 항목을 참조하세요.

return_dict (`bool`, *선택 사항*) : 일반 튜플 대신 [ModelOutput](/docs/transformers/main/ko/main_classes/output#transformers.utils.ModelOutput)를 반환할지 여부.

**반환값:** `BaseModelOutputWithPoolingAndNoAttention` 또는 `tuple(torch.Tensor)`

`BaseModelOutputWithPoolingAndNoAttention` 또는 `torch.Tensor`의 튜플(`return_dict=False`가 전달되거나 `config.return_dict=False`인 경우)로, 구성([MobileNetV2Config](/docs/transformers/main/ko/model_doc/mobilenet_v2#transformers.MobileNetV2Config)) 및 입력에 따라 다양한 요소를 포함합니다.

[MobileNetV2Model](/docs/transformers/main/ko/model_doc/mobilenet_v2#transformers.MobileNetV2Model)의 forward 메서드는 `__call__` 특수 메서드를 오버라이드합니다.

`Module` 인스턴스는 전처리 및 후처리 단계를 실행하는 것을 처리하지만, 이 함수는 해당 단계를 조용히 무시하므로, 순전파(forward pass) 레시피를 이 함수 내에서 정의해야 하더라도 이후에는 이 함수 대신 `Module` 인스턴스를 호출해야 합니다.

- **last_hidden_state** (`torch.Tensor`, shape `(batch_size, num_channels, height, width)`) -- 모델의 마지막 레이어 출력에서 생성된 hidden-state 시퀀스입니다.
- **pooler_output** (`torch.Tensor`, shape `(batch_size, hidden_size)`) -- 공간 차원에 대해 풀링 연산을 수행한 후의 마지막 레이어 hidden-state입니다.
- **hidden_states** (`tuple(torch.Tensor)`, *선택 사항*, `output_hidden_states=True`가 전달되었거나 `config.output_hidden_states=True`인 경우 반환됨) -- `torch.Tensor`의 튜플(모델에 임베딩 레이어가 있는 경우 임베딩 출력 1개 + 각 레이어의 출력 1개)로, 모양은 `(batch_size, num_channels, height, width)`입니다.

  각 레이어의 출력에서 모델의 Hidden-states와 선택적 초기 임베딩 출력을 포함합니다.

예:

```python
```

## MobileNetV2ForImageClassification[[transformers.MobileNetV2ForImageClassification]]

#### transformers.MobileNetV2ForImageClassification[[transformers.MobileNetV2ForImageClassification]]

```python
transformers.MobileNetV2ForImageClassification(config: MobileNetV2Config)
```

[소스](https://github.com/huggingface/transformers/blob/main/src/transformers/models/mobilenet_v2/modeling_mobilenet_v2.py#L374)

**매개변수:**

config ([MobileNetV2Config](/docs/transformers/main/ko/model_doc/mobilenet_v2#transformers.MobileNetV2Config)) : 모델의 모든 매개변수를 포함하는 모델 구성 클래스입니다. 구성 파일로 초기화하는 것은 모델과 관련된 가중치를 로드하지 않으며, 구성 정보만 로드합니다. 모델 가중치를 로드하려면 [from_pretrained()](/docs/transformers/main/ko/main_classes/model#transformers.PreTrainedModel.from_pretrained) 메서드를 확인하세요.

MobileNetV2 모델 위에 이미지 분류 헤더(풀링된 특징 위에 선형 레이어)를 추가한 형태입니다. 예를 들어 ImageNet에 사용됩니다.

이 모델은 [PreTrainedModel](/docs/transformers/main/ko/main_classes/model#transformers.PreTrainedModel)에서 상속됩니다. 라이브러리가 모든 모델에 대해 구현하는 일반적 메서드(다운로드 또는 저장, 입력 임베딩 크기 조정, 헤드 프루닝 등)에 대해서는 상위 클래스 문서를 확인하세요.

이 모델은 또한 PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module)의 하위 클래스입니다. 일반적인 PyTorch Module처럼 사용하며, 일반적인 사용법과 동작에 관한 모든 사항은 PyTorch 문서를 참조하세요.

#### forward[[transformers.MobileNetV2ForImageClassification.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/mobilenet_v2/modeling_mobilenet_v2.py#L390)

**매개변수:**

pixel_values (`torch.Tensor`, shape `(batch_size, num_channels, image_size, image_size)`, *선택 사항*) : 입력 이미지에 해당하는 텐서입니다. 픽셀 값은 [MobileNetV2ImageProcessor](/docs/transformers/main/ko/model_doc/mobilenet_v2#transformers.MobileNetV2ImageProcessor)를 사용하여 얻을 수 있습니다. 자세한 내용은 [MobileNetV2ImageProcessor.__call__()](/docs/transformers/main/ko/model_doc/molmo2#transformers.Molmo2ImageProcessor.__call__)를 참조하세요 (`processor_class`는 이미지 처리에 [MobileNetV2ImageProcessor](/docs/transformers/main/ko/model_doc/mobilenet_v2#transformers.MobileNetV2ImageProcessor)를 사용합니다).

output_hidden_states (`bool`, *선택 사항*) : 모든 레이어의 hidden states를 반환할지 여부. 자세한 내용은 반환되는 텐서 중 `hidden_states` 항목을 참조하세요.

labels (`torch.LongTensor`, shape `(batch_size,)`, *선택 사항*) : 이미지 분류/회귀 손실을 계산하는 데 사용되는 라벨. 인덱스는 `[0, ..., config.num_labels - 1]` 범위에 있어야 합니다. `config.num_labels == 1`인 경우 회귀 손실(평균 제곱 손실)이 계산됩니다. `config.num_labels > 1`인 경우 분류 손실(크로스 엔트로피)이 계산됩니다.

return_dict (`bool`, *선택 사항*) : 일반 튜플 대신 [ModelOutput](/docs/transformers/main/ko/main_classes/output#transformers.utils.ModelOutput)를 반환할지 여부.

**반환값:** [ImageClassifierOutputWithNoAttention](/docs/transformers/main/ko/main_classes/output#transformers.modeling_outputs.ImageClassifierOutputWithNoAttention) 또는 `tuple(torch.Tensor)`

구성([MobileNetV2Config](/docs/transformers/main/ko/model_doc/mobilenet_v2#transformers.MobileNetV2Config))과 입력에 따라 다양한 요소를 포함하는 [ImageClassifierOutputWithNoAttention](/docs/transformers/main/ko/main_classes/output#transformers.modeling_outputs.ImageClassifierOutputWithNoAttention) 또는 `torch.Tensor`의 튜플(`return_dict=False`가 전달되거나 `config.return_dict=False`인 경우).

[MobileNetV2ForImageClassification](/docs/transformers/main/ko/model_doc/mobilenet_v2#transformers.MobileNetV2ForImageClassification)의 forward 메서드는 `__call__` 특수 메서드를 오버라이드합니다.

`Module` 인스턴스는 전처리 및 후처리 단계를 실행하는 것을 처리하지만, 이 함수는 해당 단계를 조용히 무시하므로, 순전파(forward pass) 레시피를 이 함수 내에서 정의해야 하더라도 이후에는 이 함수 대신 `Module` 인스턴스를 호출해야 합니다.

- **loss** (`torch.Tensor`, shape `(1,)`, *선택*, `labels`이 제공될 때 반환됨) -- 분류(또는 config.num_labels==1인 경우 회귀) 손실.
- **logits** (`torch.Tensor`, shape `(batch_size, config.num_labels)`) -- SoftMax 적용 전 분류(또는 config.num_labels==1인 경우 회귀) 점수.
- **hidden_states** (`tuple(torch.Tensor)`, *선택*, `output_hidden_states=True`가 전달되거나 `config.output_hidden_states=True`인 경우 반환) -- `torch.Tensor`의 튜플(모델에 임베딩 레이어가 있는 경우 임베딩 출력용 1개 + 각 단계 출력용 1개)로, shape은 `(batch_size, num_channels, height, width)`입니다. 각 단계 출력 시점의 모델 hidden-states(또는 feature maps)입니다.

예:

```python
>>> from transformers import AutoImageProcessor, MobileNetV2ForImageClassification
>>> 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 = MobileNetV2ForImageClassification.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])
...
```

## MobileNetV2ForSemanticSegmentation[[transformers.MobileNetV2ForSemanticSegmentation]]

#### transformers.MobileNetV2ForSemanticSegmentation[[transformers.MobileNetV2ForSemanticSegmentation]]

```python
transformers.MobileNetV2ForSemanticSegmentation(config: MobileNetV2Config)
```

[소스](https://github.com/huggingface/transformers/blob/main/src/transformers/models/mobilenet_v2/modeling_mobilenet_v2.py#L508)

**매개변수:**

config ([MobileNetV2Config](/docs/transformers/main/ko/model_doc/mobilenet_v2#transformers.MobileNetV2Config)) : 모델의 모든 매개변수를 포함하는 모델 구성 클래스입니다. 구성 파일로 초기화하는 것은 모델과 관련된 가중치를 로드하지 않으며, 구성 정보만 로드합니다. 모델 가중치를 로드하려면 [from_pretrained()](/docs/transformers/main/ko/main_classes/model#transformers.PreTrainedModel.from_pretrained) 메서드를 확인하세요.

Pascal VOC과 같은 작업에 사용할 수 있도록 상단에 semantic segmentation head가 있는 MobileNetV2 모델.

이 모델은 [PreTrainedModel](/docs/transformers/main/ko/main_classes/model#transformers.PreTrainedModel)에서 상속됩니다. 라이브러리가 모든 모델에 대해 구현하는 일반적 메서드(다운로드 또는 저장, 입력 임베딩 크기 조정, 헤드 프루닝 등)에 대해서는 상위 클래스 문서를 확인하세요.

이 모델은 또한 PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module)의 하위 클래스입니다. 일반적인 PyTorch Module처럼 사용하며, 일반적인 사용법과 동작에 관한 모든 사항은 PyTorch 문서를 참조하세요.

#### forward[[transformers.MobileNetV2ForSemanticSegmentation.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/mobilenet_v2/modeling_mobilenet_v2.py#L519)

**매개변수:**

pixel_values (`torch.Tensor`, shape `(batch_size, num_channels, image_size, image_size)`, *선택 사항*) : 입력 이미지에 해당하는 텐서입니다. 픽셀 값은 [MobileNetV2ImageProcessor](/docs/transformers/main/ko/model_doc/mobilenet_v2#transformers.MobileNetV2ImageProcessor)를 사용하여 얻을 수 있습니다. 자세한 내용은 [MobileNetV2ImageProcessor.__call__()](/docs/transformers/main/ko/model_doc/molmo2#transformers.Molmo2ImageProcessor.__call__)를 참조하세요 (`processor_class`는 이미지 처리에 [MobileNetV2ImageProcessor](/docs/transformers/main/ko/model_doc/mobilenet_v2#transformers.MobileNetV2ImageProcessor)를 사용합니다).

labels (`torch.LongTensor`, shape `(batch_size, height, width)`, *선택 사항*) : 손실을 계산하기 위한 ground truth semantic segmentation 맵입니다. 인덱스는 `[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/ko/main_classes/output#transformers.utils.ModelOutput)를 반환할지 여부.

**반환값:** [SemanticSegmenterOutput](/docs/transformers/main/ko/main_classes/output#transformers.modeling_outputs.SemanticSegmenterOutput) 또는 `tuple(torch.Tensor)`

구성([MobileNetV2Config](/docs/transformers/main/ko/model_doc/mobilenet_v2#transformers.MobileNetV2Config))과 입력에 따라 다양한 요소를 포함하는 [SemanticSegmenterOutput](/docs/transformers/main/ko/main_classes/output#transformers.modeling_outputs.SemanticSegmenterOutput) 또는 `torch.Tensor`의 튜플(`return_dict=False`가 전달되거나 `config.return_dict=False`인 경우).

[MobileNetV2ForSemanticSegmentation](/docs/transformers/main/ko/model_doc/mobilenet_v2#transformers.MobileNetV2ForSemanticSegmentation)의 forward 메서드는 `__call__` 특수 메서드를 오버라이드합니다.

`Module` 인스턴스는 전처리 및 후처리 단계를 실행하는 것을 처리하지만, 이 함수는 해당 단계를 조용히 무시하므로, 순전파(forward pass) 레시피를 이 함수 내에서 정의해야 하더라도 이후에는 이 함수 대신 `Module` 인스턴스를 호출해야 합니다.

- **loss** (`torch.Tensor`, shape `(1,)`, *선택*, `labels`이 제공될 때 반환됨) -- 분류(또는 config.num_labels==1인 경우 회귀) 손실.
- **logits** (shape `(batch_size, config.num_labels, logits_height, logits_width)`의 `torch.Tensor`) -- 각 픽셀에 대한 분류 점수입니다.

  

  반환되는 logits는 입력으로 전달된 `pixel_values`와 반드시 동일한 크기를 갖지 않습니다. 이는 사용자가 후처리 단계에서 logits를 원본 이미지 크기로 리사이즈할 때 두 번의 보간을 수행하여 품질이 저하되는 것을 방지하기 위한 것입니다. 항상 logits의 shape을 확인하고 필요에 따라 리사이즈해야 합니다.

  
- **hidden_states** (`tuple(torch.Tensor)`, *선택*, `output_hidden_states=True`가 전달되거나 `config.output_hidden_states=True`일 때 반환) -- shape가 `(batch_size, patch_size, hidden_size)`인 `torch.Tensor`의 튜플 (모델에 임베딩 레이어가 있는 경우 임베딩 출력 1개 + 각 레이어의 출력 1개).

  각 레이어의 출력에서 모델의 Hidden-states와 선택적 초기 임베딩 출력을 포함합니다.
- **attentions** (`tuple(torch.Tensor)`, *선택 사항*, `output_attentions=True`가 전달되었거나 `config.output_attentions=True`인 경우 반환) -- 각 레이어당 하나씩, shape가 `(batch_size, num_heads, patch_size, sequence_length)`인 `torch.Tensor`의 튜플.

  self-attention 헤드에서 가중 평균을 계산하는 데 사용되는 attention softmax 이후의 attention 가중치입니다.

예:

```python
>>> from transformers import AutoImageProcessor, MobileNetV2ForSemanticSegmentation
>>> 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("google/deeplabv3_mobilenet_v2_1.0_513")
>>> model = MobileNetV2ForSemanticSegmentation.from_pretrained("google/deeplabv3_mobilenet_v2_1.0_513")

>>> 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
```

