# MobileNet V2

[MobileNet V2](https://huggingface.co/papers/1801.04381) 通过更高效的架构提升了在移动设备上的性能。它使用倒置残差块和线性瓶颈，先以较小的数据表示开始，然后扩展以进行处理，最后再次缩小以减少计算量。该模型还移除了非线性，以在简化设计的同时保持精度。与 [MobileNet V1](./mobilenet_v1) 一样，它使用深度可分离卷积来提高效率。

您可以在 [Google](https://huggingface.co/google?search_models=mobilenet) 组织下找到所有原始的 MobileNet 检查点。

> [!TIP]
> 点击右侧边栏中的 MobileNet V2 模型，以查看更多将 MobileNet 应用于不同视觉任务的示例。

以下示例演示了如何使用 [Pipeline](/docs/transformers/main/zh/main_classes/pipelines#transformers.Pipeline) 或 [AutoModel](/docs/transformers/main/zh/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}")
```

## 备注

- 分类检查点名称遵循 `mobilenet_v2_{depth_multiplier}_{resolution}` 的命名模式，例如 `mobilenet_v2_1.4_224`。其中 `1.4` 是深度乘数，`224` 是图像分辨率。分割检查点名称遵循 `deeplabv3_mobilenet_v2_{depth_multiplier}_{resolution}` 的命名模式。
- 尽管模型是在特定尺寸的图片上训练的，但其架构支持处理不同尺寸的图片（最小为 32x32）。[MobileNetV2ImageProcessor](/docs/transformers/main/zh/model_doc/mobilenet_v2#transformers.MobileNetV2ImageProcessor) 负责处理所需的预处理。
- MobileNet 在 [ImageNet-1k](https://huggingface.co/datasets/ILSVRC/imagenet-1k) 上进行了预训练，该数据集包含 1000 个类别。然而，模型实际上预测 1001 个类别。额外的类别是一个“背景”类别（索引 0）。
- 分割模型使用 [DeepLabV3+](https://huggingface.co/papers/1802.02611) 头，该头通常在 [PASCAL VOC](https://huggingface.co/datasets/merve/pascal-voc) 等数据集上进行预训练。
- 原始 TensorFlow 检查点在推理时确定填充量，因为它取决于输入图像的大小。若要使用 PyTorch 原生的填充行为，请在 [MobileNetV2Config](/docs/transformers/main/zh/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 的实现不支持以下功能。
  - 使用全局平均池化，而非可选的步长为 2 的 7x7 平均池化。对于较大的输入，这将产生大于 1x1 像素的池化输出。
  - `output_hidden_states=True` 会返回*所有*中间隐藏状态。无法提取特定层的输出用于其他下游用途。
  - 不包含原始检查点中的量化模型，因为它们包含用于反量化权重的“FakeQuantization”操作。
  - 对于分割模型，即使 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”或“宽度乘数”。

depth_divisible_by (`int`，*可选*，默认为 8)：每一层的通道数始终为该数值的倍数。

min_depth (`int`，*可选*，默认为 8)：所有层至少包含此数量的通道。

expand_ratio (`float`, *可选*，默认为 6.0)：每个块中第一层的输出通道数为输入通道数乘以扩展比例。

output_stride (`int`, *可选*，默认为 32)：输入与输出特征图空间分辨率之间的比率。默认情况下，模型会将输入维度缩小 32 倍。如果 `output_stride` 为 8 或 16，模型将在深度可分离层中使用空洞卷积而非常规卷积，从而确保特征图不会比输入图像缩小超过 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) 类似的配置

配置对象继承自 [PreTrainedConfig](/docs/transformers/main/zh/main_classes/configuration#transformers.PreTrainedConfig)，可用于控制模型输出。有关更多信息，请参阅 [PreTrainedConfig](/docs/transformers/main/zh/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 为整数时，是否在调整大小时默认使用正方形图像。

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` 中的一个值。仅当 `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*, *可选*) : 输入中每张图片所使用的图像 token 数量。为向后兼容而添加，但在未来的模型中，应将其设置为处理器的属性。

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` 中的一个值。仅当 `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*, *可选*) : 输入中每张图片所使用的图像 token 数量。为向后兼容而添加，但在未来的模型中，应将其设置为处理器的属性。

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]`，*可选*) -- 您可以在此处指定 tensor_type，以便在初始化时将 PyTorch/Numpy 张量中的整数列表进行转换。

#### 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/zh/model_doc/mobilenet_v2#transformers.MobileNetV2ForSemanticSegmentation))：模型的原始输出。

target_sizes (`list[tuple[int, int]]`, *可选*) : 与每个预测所需的最终尺寸（高度、宽度）对应的元组列表。

return_segmentation_scores (`bool`，*可选*，默认为 `False`)：是否同时返回分割分数和分割图。当为 `True` 时，返回列表中的每个元素都是一个 `SemanticSegmentationPostProcessorOutput`，包含字段 `segmentation`（类别 ID，形状为 `(height, width)`）和 `segmentation_scores`（形状为 `(num_classes, height, width)`）。

**返回：** `list[torch.Tensor]` 或 `list[SemanticSegmentationPostProcessorOutput]`

当 `return_segmentation_scores=False`（默认值）时，返回一个长度为 `batch_size` 的列表，其中每个元素都是形状为 `(height, width)` 且包含类别 ID 的分割图。当 `return_segmentation_scores=True` 时，返回一个 `SemanticSegmentationPostProcessorOutput` 列表，包含字段 `segmentation`（类别 ID，形状为 `(height, width)`）和 `segmentation_scores`（形状为 `(num_classes, height, width)`）。在这两种情况下，`(height, width)` 均对应目标尺寸（如果指定了 `target_sizes`）。

将 [MobileNetV2ForSemanticSegmentation](/docs/transformers/main/zh/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 为整数时，是否在调整大小时默认使用正方形图像。

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` 中的一个值。仅当 `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*, *可选*) : 输入中每张图片所使用的图像 token 数量。为向后兼容而添加，但在未来的模型中，应将其设置为处理器的属性。

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` 中的一个值。仅当 `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*, *可选*) : 输入中每张图片所使用的图像 token 数量。为向后兼容而添加，但在未来的模型中，应将其设置为处理器的属性。

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]`，*可选*) -- 您可以在此处指定 tensor_type，以便在初始化时将 PyTorch/Numpy 张量中的整数列表进行转换。

#### 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/zh/model_doc/mobilenet_v2#transformers.MobileNetV2ForSemanticSegmentation))：模型的原始输出。

target_sizes (`list[tuple[int, int]]`, *可选*) : 与每个预测所需的最终尺寸（高度、宽度）对应的元组列表。

return_segmentation_scores (`bool`，*可选*，默认为 `False`)：是否同时返回分割分数和分割图。当为 `True` 时，返回列表中的每个元素都是一个 `SemanticSegmentationPostProcessorOutput`，包含字段 `segmentation`（类别 ID，形状为 `(height, width)`）和 `segmentation_scores`（形状为 `(num_classes, height, width)`）。

**返回：** `list[torch.Tensor]` 或 `list[SemanticSegmentationPostProcessorOutput]`

当 `return_segmentation_scores=False`（默认值）时，返回一个长度为 `batch_size` 的列表，其中每个元素都是形状为 `(height, width)` 且包含类别 ID 的分割图。当 `return_segmentation_scores=True` 时，返回一个 `SemanticSegmentationPostProcessorOutput` 列表，包含字段 `segmentation`（类别 ID，形状为 `(height, width)`）和 `segmentation_scores`（形状为 `(num_classes, height, width)`）。在这两种情况下，`(height, width)` 均对应目标尺寸（如果指定了 `target_sizes`）。

将 [MobileNetV2ForSemanticSegmentation](/docs/transformers/main/zh/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/zh/model_doc/mobilenet_v2#transformers.MobileNetV2Config))：包含模型所有参数的模型配置类。通过配置文件进行初始化并不会加载与模型关联的权重，仅加载配置。请查看 [from_pretrained()](/docs/transformers/main/zh/main_classes/model#transformers.PreTrainedModel.from_pretrained) 方法以加载模型权重。

add_pooling_layer (`bool`，*可选*，默认为 `True`)：是否添加池化层

原始的 Mobilenet V2 模型，输出原始隐藏状态，顶部未添加任何特定分类头。

该模型继承自 [PreTrainedModel](/docs/transformers/main/zh/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`，形状为 `(batch_size, num_channels, image_size, image_size)`，*可选*)：与输入图像对应的张量。可以使用 [MobileNetV2ImageProcessor](/docs/transformers/main/zh/model_doc/mobilenet_v2#transformers.MobileNetV2ImageProcessor) 获取像素值。有关详细信息，请参阅 [MobileNetV2ImageProcessor.__call__()](/docs/transformers/main/zh/model_doc/molmo2#transformers.Molmo2ImageProcessor.__call__)（`processor_class` 使用 [MobileNetV2ImageProcessor](/docs/transformers/main/zh/model_doc/mobilenet_v2#transformers.MobileNetV2ImageProcessor) 处理图像）。

output_hidden_states (`bool`, *可选*) : 是否返回所有层的隐藏状态。有关更多详细信息，请参阅返回张量中的 `hidden_states`。

return_dict (`bool`, *可选*) : 是否返回 [ModelOutput](/docs/transformers/main/zh/main_classes/output#transformers.utils.ModelOutput) 而不是普通元组。

**返回：** `BaseModelOutputWithPoolingAndNoAttention` 或 `tuple(torch.Tensor)`

`BaseModelOutputWithPoolingAndNoAttention` 或 `torch.Tensor` 元组（如果传入 `return_dict=False` 或 `config.return_dict=False`），其包含的元素取决于配置（[MobileNetV2Config](/docs/transformers/main/zh/model_doc/mobilenet_v2#transformers.MobileNetV2Config)）和输入。

[MobileNetV2Model](/docs/transformers/main/zh/model_doc/mobilenet_v2#transformers.MobileNetV2Model) 的 forward 方法重写了 `__call__` 特殊方法。

尽管前向传播的实现需要在此函数中定义，但之后应调用 `Module` 实例，而不是直接调用此函数，因为前者会负责执行预处理和后处理步骤，而后者会静默地忽略这些步骤。

- **last_hidden_state**（形状为 `(batch_size, num_channels, height, width)` 的 `torch.Tensor`）-- 模型最后一层输出的隐藏状态序列。
- **pooler_output**（形状为 `(batch_size, hidden_size)` 的 `torch.Tensor`）-- 在空间维度上执行池化操作后的最后一层隐藏状态。
- **hidden_states** (`tuple(torch.Tensor)`，*可选*，在传入 `output_hidden_states=True` 或 `config.output_hidden_states=True` 时返回) -- 一个 `torch.Tensor` 元组（如果模型具有嵌入层，则包含嵌入层输出的一个张量，以及每个层输出的一个张量），形状为 `(batch_size, num_channels, height, width)`。

  模型在每一层输出处的隐藏状态，以及可选的初始嵌入输出。

示例：

```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/zh/model_doc/mobilenet_v2#transformers.MobileNetV2Config))：包含模型所有参数的模型配置类。通过配置文件进行初始化并不会加载与模型关联的权重，仅加载配置。请查看 [from_pretrained()](/docs/transformers/main/zh/main_classes/model#transformers.PreTrainedModel.from_pretrained) 方法以加载模型权重。

在顶部带有图像分类头的 MobileNetV2 模型（在池化特征之上添加一个线性层），例如用于 ImageNet。

该模型继承自 [PreTrainedModel](/docs/transformers/main/zh/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`，形状为 `(batch_size, num_channels, image_size, image_size)`，*可选*)：与输入图像对应的张量。可以使用 [MobileNetV2ImageProcessor](/docs/transformers/main/zh/model_doc/mobilenet_v2#transformers.MobileNetV2ImageProcessor) 获取像素值。有关详细信息，请参阅 [MobileNetV2ImageProcessor.__call__()](/docs/transformers/main/zh/model_doc/molmo2#transformers.Molmo2ImageProcessor.__call__)（`processor_class` 使用 [MobileNetV2ImageProcessor](/docs/transformers/main/zh/model_doc/mobilenet_v2#transformers.MobileNetV2ImageProcessor) 处理图像）。

output_hidden_states (`bool`, *可选*) : 是否返回所有层的隐藏状态。有关更多详细信息，请参阅返回张量中的 `hidden_states`。

labels (`torch.LongTensor`，形状为 `(batch_size,)`，*可选*) : 用于计算图像分类/回归损失的标签。索引应在 `[0, ..., config.num_labels - 1]` 范围内。如果 `config.num_labels == 1`，则计算回归损失（均方损失）。如果 `config.num_labels > 1`，则计算分类损失（交叉熵）。

return_dict (`bool`, *可选*) : 是否返回 [ModelOutput](/docs/transformers/main/zh/main_classes/output#transformers.utils.ModelOutput) 而不是普通元组。

**返回：** [ImageClassifierOutputWithNoAttention](/docs/transformers/main/zh/main_classes/output#transformers.modeling_outputs.ImageClassifierOutputWithNoAttention) 或 `tuple(torch.Tensor)`

一个 [ImageClassifierOutputWithNoAttention](/docs/transformers/main/zh/main_classes/output#transformers.modeling_outputs.ImageClassifierOutputWithNoAttention) 或 `torch.Tensor` 元组（如果传入了 `return_dict=False` 或 `config.return_dict=False`），其包含的元素取决于配置（[MobileNetV2Config](/docs/transformers/main/zh/model_doc/mobilenet_v2#transformers.MobileNetV2Config)）和输入。

[MobileNetV2ForImageClassification](/docs/transformers/main/zh/model_doc/mobilenet_v2#transformers.MobileNetV2ForImageClassification) 的 forward 方法重写了 `__call__` 特殊方法。

尽管前向传播的实现需要在此函数中定义，但之后应调用 `Module` 实例，而不是直接调用此函数，因为前者会负责执行预处理和后处理步骤，而后者会静默地忽略这些步骤。

- **loss** (`torch.Tensor`，形状为 `(1,)`，*可选*，当提供 `labels` 时返回) -- 分类损失（如果 config.num_labels==1，则为回归损失）。
- **logits**（形状为 `(batch_size, config.num_labels)` 的 `torch.Tensor`）-- 分类（或当 config.num_labels==1 时为回归）得分（SoftMax 之前）。
- **hidden_states** (`tuple(torch.Tensor)`，*可选*，在传入 `output_hidden_states=True` 或 `config.output_hidden_states=True` 时返回) -- 一个 `torch.Tensor` 元组（如果模型具有嵌入层，则包含嵌入层输出的一个张量，以及每个阶段输出的一个张量），形状为 `(batch_size, num_channels, height, width)`。模型在每个阶段输出处的隐藏状态（也称为特征图）。

示例：

```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/zh/model_doc/mobilenet_v2#transformers.MobileNetV2Config))：包含模型所有参数的模型配置类。通过配置文件进行初始化并不会加载与模型关联的权重，仅加载配置。请查看 [from_pretrained()](/docs/transformers/main/zh/main_classes/model#transformers.PreTrainedModel.from_pretrained) 方法以加载模型权重。

在顶部添加了语义分割头的 MobileNetV2 模型，例如用于 Pascal VOC。

该模型继承自 [PreTrainedModel](/docs/transformers/main/zh/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`，形状为 `(batch_size, num_channels, image_size, image_size)`，*可选*)：与输入图像对应的张量。可以使用 [MobileNetV2ImageProcessor](/docs/transformers/main/zh/model_doc/mobilenet_v2#transformers.MobileNetV2ImageProcessor) 获取像素值。有关详细信息，请参阅 [MobileNetV2ImageProcessor.__call__()](/docs/transformers/main/zh/model_doc/molmo2#transformers.Molmo2ImageProcessor.__call__)（`processor_class` 使用 [MobileNetV2ImageProcessor](/docs/transformers/main/zh/model_doc/mobilenet_v2#transformers.MobileNetV2ImageProcessor) 处理图像）。

labels (`torch.LongTensor`，形状为 `(batch_size, height, width)`，*可选*) : 用于计算损失的真实语义分割图。索引应在 `[0, ..., config.num_labels - 1]` 范围内。如果 `config.num_labels > 1`，则计算分类损失（交叉熵）。

output_hidden_states (`bool`, *可选*) : 是否返回所有层的隐藏状态。有关更多详细信息，请参阅返回张量中的 `hidden_states`。

return_dict (`bool`, *可选*) : 是否返回 [ModelOutput](/docs/transformers/main/zh/main_classes/output#transformers.utils.ModelOutput) 而不是普通元组。

**返回：** [SemanticSegmenterOutput](/docs/transformers/main/zh/main_classes/output#transformers.modeling_outputs.SemanticSegmenterOutput) 或 `tuple(torch.Tensor)`

一个 [SemanticSegmenterOutput](/docs/transformers/main/zh/main_classes/output#transformers.modeling_outputs.SemanticSegmenterOutput) 或 `torch.Tensor` 元组（如果传入了 `return_dict=False` 或 `config.return_dict=False`），其包含的元素取决于配置（[MobileNetV2Config](/docs/transformers/main/zh/model_doc/mobilenet_v2#transformers.MobileNetV2Config)）和输入。

[MobileNetV2ForSemanticSegmentation](/docs/transformers/main/zh/model_doc/mobilenet_v2#transformers.MobileNetV2ForSemanticSegmentation) 的 forward 方法重写了 `__call__` 特殊方法。

尽管前向传播的实现需要在此函数中定义，但之后应调用 `Module` 实例，而不是直接调用此函数，因为前者会负责执行预处理和后处理步骤，而后者会静默地忽略这些步骤。

- **loss** (`torch.Tensor`，形状为 `(1,)`，*可选*，当提供 `labels` 时返回) -- 分类损失（如果 config.num_labels==1，则为回归损失）。
- **logits**（形状为 `(batch_size, config.num_labels, logits_height, logits_width)` 的 `torch.Tensor`）-- 每个像素的分类分数。

  

  返回的 logits 大小不一定与作为输入传入的 `pixel_values` 相同。这样设计是为了避免进行两次插值，从而在用户需要将 logits 调整为原始图像尺寸作为后处理时损失部分质量。您应始终检查 logits 的形状，并根据需要进行调整。

  
- **hidden_states** (`tuple(torch.Tensor)`，*可选*，在传入 `output_hidden_states=True` 或 `config.output_hidden_states=True` 时返回) -- 一个 `torch.Tensor` 元组（如果模型具有嵌入层，则包含嵌入层输出的一个张量，以及每个层输出的一个张量），形状为 `(batch_size, patch_size, hidden_size)`。

  模型在每一层输出处的隐藏状态，以及可选的初始嵌入输出。
- **attentions** (`tuple(torch.Tensor)`，*可选*，当传入 `output_attentions=True` 或 `config.output_attentions=True` 时返回) -- 一个 `torch.Tensor` 元组（每层一个），形状为 `(batch_size, num_heads, patch_size, sequence_length)`。

  经过注意力 softmax 后的注意力权重，用于在自注意力头中计算加权平均值。

示例：

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

