# EfficientNet

## 概述

EfficientNet 模型由 Mingxing Tan 和 Quoc V. Le 在 [EfficientNet: Rethinking Model Scaling for Convolutional Neural Networks](https://huggingface.co/papers/1905.11946) 中提出。EfficientNet 是一系列图像分类模型，在实现最先进精度的同时，其规模比之前的模型小一个数量级，速度也更快。

该论文的摘要如下：

*卷积神经网络（ConvNets）通常在固定的资源预算下开发，然后在资源充足时进行扩展以提升精度。在本文中，我们系统地研究了模型扩展，并发现精心平衡网络深度、宽度和分辨率可以带来更好的性能。基于这一观察，我们提出了一种新的扩展方法，使用简单但高效的复合系数来统一扩展深度/宽度/分辨率的所有维度。我们通过在 MobileNets 和 ResNet 上扩展模型来证明该方法的有效性。为了更进一步，我们使用神经架构搜索设计了一个新的基线网络，并将其扩展以获得一系列模型，称为 EfficientNets，这些模型在精度和效率上均远优于以往的 ConvNets。特别是，我们的 EfficientNet-B7 在 ImageNet 上达到了 84.3% 的 top-1 精度，同时比现有最佳 ConvNet 小 8.4 倍，推理速度快 6.1 倍。我们的 EfficientNets 还具有良好的迁移能力，在 CIFAR-100（91.7%）、Flowers（98.8%）以及其他 3 个迁移学习数据集上达到了最先进的精度，且参数量少了一个数量级。*

该模型由 [adirik](https://huggingface.co/adirik) 贡献。原始代码可在[此处](https://github.com/tensorflow/tpu/tree/master/models/official/efficientnet)找到。

## EfficientNetConfig[[transformers.EfficientNetConfig]]

#### transformers.EfficientNetConfig[[transformers.EfficientNetConfig]]

```python
transformers.EfficientNetConfig(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] = 600, width_coefficient: float = 2.0, depth_coefficient: float = 3.1, depth_divisor: int = 8, kernel_sizes: list[int] | tuple[int, ...] = (3, 3, 5, 3, 5, 5, 3), in_channels: list[int] | tuple[int, ...] = (32, 16, 24, 40, 80, 112, 192), out_channels: list[int] | tuple[int, ...] = (16, 24, 40, 80, 112, 192, 320), depthwise_padding: list[int] | tuple[int, ...] = (), strides: list[int] | tuple[int, ...] = (1, 2, 2, 2, 1, 2, 1), num_block_repeats: list[int] | tuple[int, ...] = (1, 2, 2, 3, 3, 4, 1), expand_ratios: list[int] | tuple[int, ...] = (1, 6, 6, 6, 6, 6, 6), squeeze_expansion_ratio: float = 0.25, hidden_act: str = 'swish', hidden_dim: int = 2560, pooling_type: str = 'mean', initializer_range: float = 0.02, batch_norm_eps: float = 0.001, batch_norm_momentum: float = 0.99, dropout_rate: float | int = 0.5, drop_connect_rate: float | int = 0.2)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/efficientnet/configuration_efficientnet.py#L24)

**参数：**

num_channels (`int`，*可选*，默认为 `3`)：输入通道数。

image_size (`Union[int, list[int], tuple[int, int]]`，*可选*，默认为 `600`)：每张图片的尺寸（分辨率）。

width_coefficient (`float`，*可选*，默认值为 2.0)：每个阶段网络宽度的缩放系数。

depth_coefficient (`float`, *可选*，默认为 3.1)：每个阶段的网络深度缩放系数。

depth_divisor (`int`，*可选*，默认为 8)：网络宽度的单位。

kernel_sizes (`list[int]`，*可选*，默认为 `[3, 3, 5, 3, 5, 5, 3]`)：用于每个块的核大小列表。

in_channels (`Union[list[int], tuple[int, ...]]`，*可选*，默认为 `(32, 16, 24, 40, 80, 112, 192)`)：输入通道数。

out_channels (`list[int]`，*可选*，默认为 `[16, 24, 40, 80, 112, 192, 320]`)：用于每个块中卷积层的输出通道大小列表。

depthwise_padding (`list[int]`, *可选*, 默认为 `[]`) : 使用方形填充的块索引列表。

strides (`Union[list[int], tuple[int, ...]]`，*可选*，默认为 `(1, 2, 2, 2, 1, 2, 1)`)：模型每个阶段的步幅。

num_block_repeats (`list[int]`，*可选*，默认为 `[1, 2, 2, 3, 3, 4, 1]`)：每个块重复次数的列表。

expand_ratios (`list[int]`，*可选*，默认为 `[1, 6, 6, 6, 6, 6, 6]`)：每个块的缩放系数列表。

squeeze_expansion_ratio (`float`，*可选*，默认值为 0.25)：Squeeze 扩展比率。

hidden_act (`str`，*可选*，默认为 `swish`)：解码器中使用的非线性激活函数（函数或字符串）。例如 `"gelu"`、`"relu"`、`"silu"` 等。

hidden_dim (`int`，*可选*，默认值为 `2560`)：隐藏表示的维度。

pooling_type (`str` 或 `function`，*可选*，默认为 `"mean"`)：在稠密分类头之前应用的最终池化类型。可用选项为 [`"mean"`, `"max"`]

initializer_range (`float`，*可选*，默认值为 `0.02`)：用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。

batch_norm_eps (`float`，*可选*，默认值为 `0.001`)：批归一化层所使用的 epsilon。

batch_norm_momentum (`float`，*可选*，默认值为 0.99)：批归一化层所使用的动量。

dropout_rate (`Union[float, int]`，*可选*，默认为 `0.5`)：所有 dropout 层的比率。

drop_connect_rate (`float`，*可选*，默认为 0.2)：跳跃连接的丢弃率。

这是用于存储 EfficientNetModel 配置的类。它根据指定的参数实例化 Efficientnet 模型，并定义模型架构。使用默认值实例化配置将生成与 [google/efficientnet-b7](https://huggingface.co/google/efficientnet-b7) 类似的配置。

配置对象继承自 [PreTrainedConfig](/docs/transformers/main/zh/main_classes/configuration#transformers.PreTrainedConfig)，可用于控制模型输出。有关更多信息，请参阅 [PreTrainedConfig](/docs/transformers/main/zh/main_classes/configuration#transformers.PreTrainedConfig) 的文档。

示例：
```python
>>> from transformers import EfficientNetConfig, EfficientNetModel

>>> # Initializing a EfficientNet efficientnet-b7 style configuration
>>> configuration = EfficientNetConfig()

>>> # Initializing a model (with random weights) from the efficientnet-b7 style configuration
>>> model = EfficientNetModel(configuration)

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

## EfficientNetImageProcessor[[transformers.EfficientNetImageProcessor]]

#### transformers.EfficientNetImageProcessor[[transformers.EfficientNetImageProcessor]]

```python
transformers.EfficientNetImageProcessor(**kwargs: *<class 'transformers.models.efficientnet.image_processing_efficientnet.EfficientNetImageProcessorKwargs'>)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/efficientnet/image_processing_efficientnet.py#L48)

**参数：**

do_convert_rgb (`bool`, *kwargs*, *可选*) : 是否将图像转换为 RGB。

do_resize (`bool`, *kwargs*, *可选*, 默认为 `True`) : 是否调整图像大小。

size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*，默认为 `{'height' : 346, 'width': 346}`)：描述输入到模型的最大尺寸。

default_to_square (`bool`，*kwargs*，*可选*，默认为 `True`)：当 size 为整数时，是否在调整大小时默认使用正方形图像。

crop_size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*，默认为 `{'height' : 289, 'width': 289}`)：应用 `center_crop` 后输出图像的尺寸。

resample (`Annotated[Union[int, PILImageResampling, NoneType], None]`, *kwargs*，默认值为 `3`) : 如果调整图像大小，则使用的重采样滤波器。它可以是枚举 `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*, *可选*，默认为 `False`) : 是否对图像进行居中裁剪。

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 数量。为向后兼容而添加，但在未来的模型中，应将其设置为处理器的属性。

rescale_offset (`bool`, *kwargs*, *可选*，默认为 `self.rescale_offset`) : 是否将图像重新缩放到 [-max_range/2, scale_range/2] 区间，而不是 [0, scale_range] 区间。

include_top (`bool`, *kwargs*, *可选*，默认为 `self.include_top`) : 如果设置为 True，则仅针对图像分类任务，再次使用标准差对图像进行归一化。

构建一个 EfficientNetImageProcessor 图像处理器。

#### preprocess[[transformers.EfficientNetImageProcessor.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']], *args, image_like_kwargs: dict[str, typing.Any] | None = None, **kwargs: *<class 'transformers.processing_utils.ImagesKwargs'>)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/image_processing_utils.py#L382)

**参数：**

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

image_like_kwargs (`dict[str, Any]`，*可选*)：用于额外图像类输入的开发者标志，这些输入也将被预处理。仅在以关键字参数传递输入不起作用时使用此标志。例如，`preprocess(images, masks=masks)` 是首选方式，但对于某些模型会导致参数优先级问题。在这种情况下，可以改用 `preprocess(images, image_like_inputs={"masks": masks})`。

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 数量。为向后兼容而添加，但在未来的模型中，应将其设置为处理器的属性。

**返回：** `~image_processing_base.BatchFeature`

- **data** (`dict`) -- 由 __call__ 方法返回的列表/数组/张量字典（例如 'pixel_values'）。
- **tensor_type** (`Union[None, str, TensorType]`，*可选*) -- 您可以在此处指定 tensor_type，以便在初始化时将 PyTorch/Numpy 张量中的整数列表进行转换。

预处理一张图像或一批图像。

## EfficientNetImageProcessorPil[[transformers.EfficientNetImageProcessorPil]]

#### transformers.EfficientNetImageProcessorPil[[transformers.EfficientNetImageProcessorPil]]

```python
transformers.EfficientNetImageProcessorPil(**kwargs: *<class 'transformers.models.efficientnet.image_processing_pil_efficientnet.EfficientNetImageProcessorKwargs'>)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/efficientnet/image_processing_pil_efficientnet.py#L44)

**参数：**

do_convert_rgb (`bool`, *kwargs*, *可选*) : 是否将图像转换为 RGB。

do_resize (`bool`, *kwargs*, *可选*, 默认为 `True`) : 是否调整图像大小。

size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*，默认为 `{'height' : 346, 'width': 346}`)：描述输入到模型的最大尺寸。

default_to_square (`bool`，*kwargs*，*可选*，默认为 `True`)：当 size 为整数时，是否在调整大小时默认使用正方形图像。

crop_size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*，默认为 `{'height' : 289, 'width': 289}`)：应用 `center_crop` 后输出图像的尺寸。

resample (`Annotated[Union[int, PILImageResampling, NoneType], None]`, *kwargs*，默认值为 `3`) : 如果调整图像大小，则使用的重采样滤波器。它可以是枚举 `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*, *可选*，默认为 `False`) : 是否对图像进行居中裁剪。

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 数量。为向后兼容而添加，但在未来的模型中，应将其设置为处理器的属性。

rescale_offset (`bool`, *kwargs*, *可选*，默认为 `self.rescale_offset`) : 是否将图像重新缩放到 [-max_range/2, scale_range/2] 区间，而不是 [0, scale_range] 区间。

include_top (`bool`, *kwargs*, *可选*，默认为 `self.include_top`) : 如果设置为 True，则仅针对图像分类任务，再次使用标准差对图像进行归一化。

构建一个 EfficientNetImageProcessor 图像处理器。

#### preprocess[[transformers.EfficientNetImageProcessorPil.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']], *args, image_like_kwargs: dict[str, typing.Any] | None = None, **kwargs: *<class 'transformers.processing_utils.ImagesKwargs'>)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/image_processing_utils.py#L382)

**参数：**

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

image_like_kwargs (`dict[str, Any]`，*可选*)：用于额外图像类输入的开发者标志，这些输入也将被预处理。仅在以关键字参数传递输入不起作用时使用此标志。例如，`preprocess(images, masks=masks)` 是首选方式，但对于某些模型会导致参数优先级问题。在这种情况下，可以改用 `preprocess(images, image_like_inputs={"masks": masks})`。

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 数量。为向后兼容而添加，但在未来的模型中，应将其设置为处理器的属性。

**返回：** `~image_processing_base.BatchFeature`

- **data** (`dict`) -- 由 __call__ 方法返回的列表/数组/张量字典（例如 'pixel_values'）。
- **tensor_type** (`Union[None, str, TensorType]`，*可选*) -- 您可以在此处指定 tensor_type，以便在初始化时将 PyTorch/Numpy 张量中的整数列表进行转换。

预处理一张图像或一批图像。

## EfficientNetModel[[transformers.EfficientNetModel]]

#### transformers.EfficientNetModel[[transformers.EfficientNetModel]]

```python
transformers.EfficientNetModel(config: EfficientNetConfig)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/efficientnet/modeling_efficientnet.py#L453)

**参数：**

config ([EfficientNetConfig](/docs/transformers/main/zh/model_doc/efficientnet#transformers.EfficientNetConfig))：模型配置类，包含模型的所有参数。通过配置文件进行初始化时，不会加载与模型关联的权重，仅加载配置。请查看 [from_pretrained()](/docs/transformers/main/zh/main_classes/model#transformers.PreTrainedModel.from_pretrained) 方法以加载模型权重。

未添加任何特定头部的裸 Efficientnet 模型，直接输出原始隐藏状态。

该模型继承自 [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.EfficientNetModel.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/efficientnet/modeling_efficientnet.py#L471)

**参数：**

pixel_values (`torch.Tensor`，形状为 `(batch_size, num_channels, image_size, image_size)`，*可选*) : 与输入图像对应的张量。可以使用 [EfficientNetImageProcessor](/docs/transformers/main/zh/model_doc/efficientnet#transformers.EfficientNetImageProcessor) 获取像素值。有关详细信息，请参阅 [EfficientNetImageProcessor.__call__()](/docs/transformers/main/zh/model_doc/molmo2#transformers.Molmo2ImageProcessor.__call__)（`processor_class` 使用 [EfficientNetImageProcessor](/docs/transformers/main/zh/model_doc/efficientnet#transformers.EfficientNetImageProcessor) 处理图像）。

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`），其包含的元素取决于配置（[EfficientNetConfig](/docs/transformers/main/zh/model_doc/efficientnet#transformers.EfficientNetConfig)）和输入。

[EfficientNetModel](/docs/transformers/main/zh/model_doc/efficientnet#transformers.EfficientNetModel) 的 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
```

## EfficientNetForImageClassification[[transformers.EfficientNetForImageClassification]]

#### transformers.EfficientNetForImageClassification[[transformers.EfficientNetForImageClassification]]

```python
transformers.EfficientNetForImageClassification(config: EfficientNetConfig)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/efficientnet/modeling_efficientnet.py#L516)

**参数：**

config ([EfficientNetConfig](/docs/transformers/main/zh/model_doc/efficientnet#transformers.EfficientNetConfig))：模型配置类，包含模型的所有参数。通过配置文件进行初始化时，不会加载与模型关联的权重，仅加载配置。请查看 [from_pretrained()](/docs/transformers/main/zh/main_classes/model#transformers.PreTrainedModel.from_pretrained) 方法以加载模型权重。

带有图像分类头（在池化特征之上添加一个线性层）的 EfficientNet 模型，例如用于 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.EfficientNetForImageClassification.forward]]

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

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/efficientnet/modeling_efficientnet.py#L529)

**参数：**

pixel_values (`torch.Tensor`，形状为 `(batch_size, num_channels, image_size, image_size)`，*可选*) : 与输入图像对应的张量。可以使用 [EfficientNetImageProcessor](/docs/transformers/main/zh/model_doc/efficientnet#transformers.EfficientNetImageProcessor) 获取像素值。有关详细信息，请参阅 [EfficientNetImageProcessor.__call__()](/docs/transformers/main/zh/model_doc/molmo2#transformers.Molmo2ImageProcessor.__call__)（`processor_class` 使用 [EfficientNetImageProcessor](/docs/transformers/main/zh/model_doc/efficientnet#transformers.EfficientNetImageProcessor) 处理图像）。

labels (`torch.LongTensor`，形状为 `(batch_size,)`，*可选*) : 用于计算图像分类/回归损失的标签。索引应在 `[0, ..., config.num_labels - 1]` 范围内。如果 `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) 而不是普通元组。

**返回：** [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`），其包含的元素取决于配置（[EfficientNetConfig](/docs/transformers/main/zh/model_doc/efficientnet#transformers.EfficientNetConfig)）和输入。

[EfficientNetForImageClassification](/docs/transformers/main/zh/model_doc/efficientnet#transformers.EfficientNetForImageClassification) 的 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, EfficientNetForImageClassification
>>> import torch
>>> from datasets import load_dataset

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

>>> image_processor = AutoImageProcessor.from_pretrained("google/efficientnet-b7")
>>> model = EfficientNetForImageClassification.from_pretrained("google/efficientnet-b7")

>>> 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])
...
```

