Transformers 文档

EfficientNet

Hugging Face's logo
加入 Hugging Face 社区

并获得增强的文档体验

开始使用

EfficientNet

PyTorch

概述

EfficientNet模型由Mingxing Tan和Quoc V. Le在论文《EfficientNet: Rethinking Model Scaling for Convolutional Neural Networks》中提出。EfficientNets是一系列图像分类模型,它们在达到顶尖准确率的同时,比先前的模型小一个数量级且速度更快。

论文摘要如下:

卷积神经网络(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贡献。原始代码可以在这里找到。

EfficientNetConfig

class transformers.EfficientNetConfig

< >

( num_channels: int = 3 image_size: int = 600 width_coefficient: float = 2.0 depth_coefficient: float = 3.1 depth_divisor: int = 8 kernel_sizes: list = [3, 3, 5, 3, 5, 5, 3] in_channels: list = [32, 16, 24, 40, 80, 112, 192] out_channels: list = [16, 24, 40, 80, 112, 192, 320] depthwise_padding: list = [] strides: list = [1, 2, 2, 2, 1, 2, 1] num_block_repeats: list = [1, 2, 2, 3, 3, 4, 1] expand_ratios: list = [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 = 0.5 drop_connect_rate: float = 0.2 **kwargs )

参数

  • num_channels (int, 可选, 默认为 3) — 输入通道的数量。
  • image_size (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 (list[int], 可选, 默认为 `[32, 16, 24, 40, 80, 112, 192]`) — 每个块卷积层中使用的输入通道大小列表。
  • out_channels (list[int], 可选, 默认为 `[16, 24, 40, 80, 112, 192, 320]`) — 每个块卷积层中使用的输出通道大小列表。
  • depthwise_padding (list[int], 可选, 默认为 `[]`) — 具有方形填充的块索引列表。
  • strides (list[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) — 挤压扩展比。
  • hidden_act (strfunction, 可选, 默认为 "silu") — 每个块中的非线性激活函数(函数或字符串)。如果为字符串,则支持 "gelu", "relu", "selu", “gelu_new”, “silu”“mish”`。
  • hidden_dim (int, 可选, 默认为 1280) — 分类头之前层的隐藏维度。
  • pooling_type (strfunction, 可选, 默认为 "mean") — 在密集分类头之前应用的最终池化类型。可用选项为 ["mean", "max"]。
  • initializer_range (float, 可选, 默认为 0.02) — 用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。
  • batch_norm_eps (float, 可选, 默认为 1e-3) — 批归一化层使用的 epsilon 值。
  • batch_norm_momentum (float, 可选, 默认为 0.99) — 批归一化层使用的动量。
  • dropout_rate (float, 可选, 默认为 0.5) — 在最终分类器层之前应用的 dropout 率。
  • drop_connect_rate (float, 可选, 默认为 0.2) — 残差连接的 drop 率。

这是用于存储 EfficientNetModel 配置的配置类。它根据指定的参数实例化一个 EfficientNet 模型,定义模型架构。使用默认值实例化配置将产生与 EfficientNet google/efficientnet-b7 架构类似的配置。

配置对象继承自 PretrainedConfig,可用于控制模型输出。有关更多信息,请阅读 PretrainedConfig 的文档。

示例

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

class transformers.EfficientNetImageProcessor

< >

( do_resize: bool = True size: typing.Optional[dict[str, int]] = None resample: Resampling = 0 do_center_crop: bool = False crop_size: typing.Optional[dict[str, int]] = None rescale_factor: typing.Union[int, float] = 0.00392156862745098 rescale_offset: bool = False do_rescale: bool = True do_normalize: bool = True image_mean: typing.Union[float, list[float], NoneType] = None image_std: typing.Union[float, list[float], NoneType] = None include_top: bool = True **kwargs )

参数

  • do_resize (bool, 可选, 默认为 True) — 是否将图像的 (高度, 宽度) 维度调整到指定的 `size`。可在 `preprocess` 中通过 `do_resize` 参数覆盖。
  • size (dict[str, int], 可选, 默认为 {"height": 346, "width": 346}): `resize` 后的图像大小。可在 `preprocess` 中通过 `size` 参数覆盖。
  • resample (PILImageResampling 过滤器, 可选, 默认为 0) — 调整图像大小时使用的重采样过滤器。可在 `preprocess` 中通过 `resample` 参数覆盖。
  • do_center_crop (bool, 可选, 默认为 False) — 是否对图像进行中心裁剪。如果输入的任意一边小于 `crop_size`,图像将被填充 0,然后进行中心裁剪。可在 `preprocess` 中通过 `do_center_crop` 参数覆盖。
  • crop_size (dict[str, int], 可选, 默认为 {"height": 289, "width": 289}): 应用中心裁剪时期望的输出大小。可在 `preprocess` 中通过 `crop_size` 参数覆盖。
  • rescale_factor (intfloat, 可选, 默认为 1/255) — 缩放图像时使用的缩放因子。可在 `preprocess` 方法中通过 `rescale_factor` 参数覆盖。
  • rescale_offset (bool, 可选, 默认为 False) — 是否将图像缩放到 [-scale_range, scale_range] 之间,而不是 [0, scale_range]。可在 `preprocess` 方法中通过 `rescale_factor` 参数覆盖。
  • do_rescale (bool, 可选, 默认为 True) — 是否按指定的缩放因子 `rescale_factor` 缩放图像。可在 `preprocess` 方法中通过 `do_rescale` 参数覆盖。
  • do_normalize (bool, 可选, 默认为 True) — 是否对图像进行归一化。可在 `preprocess` 方法中通过 `do_normalize` 参数覆盖。
  • image_mean (floatlist[float], 可选, 默认为 IMAGENET_STANDARD_MEAN) — 归一化图像时使用的均值。这是一个浮点数或长度等于图像通道数的浮点数列表。可在 `preprocess` 方法中通过 `image_mean` 参数覆盖。
  • image_std (floatlist[float], 可选, 默认为 IMAGENET_STANDARD_STD) — 归一化图像时使用的标准差。这是一个浮点数或长度等于图像通道数的浮点数列表。可在 `preprocess` 方法中通过 `image_std` 参数覆盖。
  • include_top (bool, 可选, 默认为 True) — 是否再次缩放图像。如果输入用于图像分类,应设置为 True。

构建一个 EfficientNet 图像处理器。

preprocess

< >

( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']] do_resize: typing.Optional[bool] = None size: typing.Optional[dict[str, int]] = None resample = None do_center_crop: typing.Optional[bool] = None crop_size: typing.Optional[dict[str, int]] = None do_rescale: typing.Optional[bool] = None rescale_factor: typing.Optional[float] = None rescale_offset: typing.Optional[bool] = None do_normalize: typing.Optional[bool] = None image_mean: typing.Union[float, list[float], NoneType] = None image_std: typing.Union[float, list[float], NoneType] = None include_top: typing.Optional[bool] = None return_tensors: typing.Union[str, transformers.utils.generic.TensorType, NoneType] = None data_format: ChannelDimension = <ChannelDimension.FIRST: 'channels_first'> input_data_format: typing.Union[str, transformers.image_utils.ChannelDimension, NoneType] = None )

参数

  • images (ImageInput) — 待预处理的图像。需要单个或一批像素值在 0 到 255 范围内的图像。如果传入的图像像素值在 0 到 1 之间,请设置 do_rescale=False
  • do_resize (bool, 可选, 默认为 self.do_resize) — 是否调整图像大小。
  • size (dict[str, int], 可选, 默认为 self.size) — resize 后图像的大小。
  • resample (PILImageResampling, 可选, 默认为 self.resample) — 如果要调整图像大小,使用的 PILImageResampling 过滤器。仅在 do_resize 设置为 True 时有效。
  • do_center_crop (bool, 可选, 默认为 self.do_center_crop) — 是否对图像进行中心裁剪。
  • crop_size (dict[str, int], 可选, 默认为 self.crop_size) — 中心裁剪后图像的大小。如果图像的一个边缘小于 crop_size,它将被填充零然后裁剪。
  • do_rescale (bool, 可选, 默认为 self.do_rescale) — 是否将图像值重新缩放到 [0 - 1] 之间。
  • rescale_factor (float, 可选, 默认为 self.rescale_factor) — 如果 do_rescale 设置为 True,用于重新缩放图像的缩放因子。
  • rescale_offset (bool, 可选, 默认为 self.rescale_offset) — 是否将图像重新缩放到 [-scale_range, scale_range] 之间,而不是 [0, scale_range]。
  • do_normalize (bool, 可选, 默认为 self.do_normalize) — 是否对图像进行归一化。
  • image_mean (floatlist[float], 可选, 默认为 self.image_mean) — 图像均值。
  • image_std (floatlist[float], 可选, 默认为 self.image_std) — 图像标准差。
  • include_top (bool, 可选, 默认为 self.include_top) — 如果设置为 True,则为图像分类再次缩放图像。
  • return_tensors (strTensorType, 可选) — 要返回的张量类型。可以是以下之一:
    • None:返回一个 np.ndarray 列表。
    • TensorType.TENSORFLOW'tf':返回一个 tf.Tensor 类型的批处理。
    • TensorType.PYTORCH'pt':返回一个 torch.Tensor 类型的批处理。
    • TensorType.NUMPY'np':返回一个 np.ndarray 类型的批处理。
    • TensorType.JAX'jax':返回一个 jax.numpy.ndarray 类型的批处理。
  • data_format (ChannelDimensionstr, 可选, 默认为 ChannelDimension.FIRST) — 输出图像的通道维度格式。可以是以下之一:
    • ChannelDimension.FIRST:图像格式为(通道数, 高度, 宽度)。
    • ChannelDimension.LAST:图像格式为(高度, 宽度, 通道数)。
  • input_data_format (ChannelDimensionstr, 可选) — 输入图像的通道维度格式。如果未设置,将从输入图像中推断通道维度格式。可以是以下之一:
    • "channels_first"ChannelDimension.FIRST:图像格式为(通道数, 高度, 宽度)。
    • "channels_last"ChannelDimension.LAST:图像格式为(高度, 宽度, 通道数)。
    • "none"ChannelDimension.NONE:图像格式为(高度, 宽度)。

预处理一张或一批图像。

EfficientNetImageProcessorFast

class transformers.EfficientNetImageProcessorFast

< >

( **kwargs: typing_extensions.Unpack[transformers.models.efficientnet.image_processing_efficientnet_fast.EfficientNetFastImageProcessorKwargs] )

构建一个快速的 Efficientnet 图像处理器。

preprocess

< >

( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']] **kwargs: typing_extensions.Unpack[transformers.models.efficientnet.image_processing_efficientnet_fast.EfficientNetFastImageProcessorKwargs] ) <class 'transformers.image_processing_base.BatchFeature'>

参数

  • 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
  • do_resize (bool, 可选) — 是否调整图像大小。
  • size (dict[str, int], 可选) — 描述模型的最大输入尺寸。
  • default_to_square (bool, 可选) — 当 size 是一个整数时,是否默认调整为方形图像。
  • resample (Union[PILImageResampling, F.InterpolationMode, NoneType]) — 如果要调整图像大小,使用的重采样过滤器。可以是 PILImageResampling 枚举之一。仅在 do_resize 设置为 True 时有效。
  • do_center_crop (bool, 可选) — 是否对图像进行中心裁剪。
  • crop_size (dict[str, int], 可选) — 应用 center_crop 后输出图像的大小。
  • do_rescale (bool, 可选) — 是否重新缩放图像。
  • rescale_factor (Union[int, float, NoneType]) — 如果 do_rescale 设置为 True,用于重新缩放图像的缩放因子。
  • do_normalize (bool, 可选) — 是否对图像进行归一化。
  • image_mean (Union[float, list[float], NoneType]) — 用于归一化的图像均值。仅在 do_normalize 设置为 True 时有效。
  • image_std (Union[float, list[float], NoneType]) — 用于归一化的图像标准差。仅在 do_normalize 设置为 True 时有效。
  • do_convert_rgb (bool, 可选) — 是否将图像转换为 RGB 格式。
  • return_tensors (Union[str, ~utils.generic.TensorType, NoneType]) — 如果设置为 `pt`,则返回堆叠的张量,否则返回张量列表。
  • data_format (~image_utils.ChannelDimension, 可选) — 仅支持 ChannelDimension.FIRST。为与慢速处理器兼容而添加。
  • input_data_format (Union[str, ~image_utils.ChannelDimension, NoneType]) — 输入图像的通道维度格式。如果未设置,将从输入图像中推断通道维度格式。可以是以下之一:
    • "channels_first"ChannelDimension.FIRST:图像格式为(通道数, 高度, 宽度)。
    • "channels_last"ChannelDimension.LAST:图像格式为(高度, 宽度, 通道数)。
    • "none"ChannelDimension.NONE:图像格式为(高度, 宽度)。
  • device (torch.device, 可选) — 处理图像的设备。如果未设置,将从输入图像中推断设备。
  • disable_grouping (bool, 可选) — 是否禁用按大小对图像进行分组,以便单独处理而不是批量处理。如果为 None,则当图像在 CPU 上时,将设置为 True,否则设置为 False。此选择基于经验观察,详情请见:https://github.com/huggingface/transformers/pull/38157
  • rescale_offset (bool, 可选, 默认为 self.rescale_offset) — 是否将图像重新缩放到 [-max_range/2, scale_range/2] 之间,而不是 [0, scale_range]。
  • include_top (bool, 可选, 默认为 self.include_top) — 如果设置为 True,则为图像分类任务仅使用标准差再次对图像进行归一化。

返回

<class 'transformers.image_processing_base.BatchFeature'>

  • data (dict) — 由 call 方法返回的列表/数组/张量字典(“pixel_values”等)。
  • tensor_type (Union[None, str, TensorType], 可选) — 您可以在此处提供一个`tensor_type`,以便在初始化时将整数列表转换为PyTorch/TensorFlow/Numpy张量。

EfficientNetModel

class transformers.EfficientNetModel

< >

( config: EfficientNetConfig )

参数

  • config (EfficientNetConfig) — 包含模型所有参数的模型配置类。使用配置文件初始化不会加载与模型相关的权重,只会加载配置。请查看 from_pretrained() 方法来加载模型权重。

基础的 Efficientnet 模型,输出原始的隐藏状态,顶部没有任何特定的头。

此模型继承自 PreTrainedModel。请查阅超类文档以了解库为其所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、修剪头等)。

该模型也是 PyTorch 的 torch.nn.Module 子类。可以像常规的 PyTorch 模块一样使用它,并参考 PyTorch 文档了解所有与常规用法和行为相关的事项。

forward

< >

( pixel_values: typing.Optional[torch.FloatTensor] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None ) transformers.modeling_outputs.BaseModelOutputWithPoolingAndNoAttentiontuple(torch.FloatTensor)

参数

  • pixel_values (torch.FloatTensor,形状为 (batch_size, num_channels, image_size, image_size), 可选) — 对应于输入图像的张量。像素值可以使用 {image_processor_class} 获得。有关详细信息,请参阅 {image_processor_class}.__call__{processor_class} 使用 {image_processor_class} 处理图像)。
  • output_hidden_states (bool, 可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参阅返回张量下的 hidden_states
  • return_dict (bool, 可选) — 是否返回 ModelOutput 而不是普通的元组。

返回

transformers.modeling_outputs.BaseModelOutputWithPoolingAndNoAttentiontuple(torch.FloatTensor)

一个 transformers.modeling_outputs.BaseModelOutputWithPoolingAndNoAttention 或一个 torch.FloatTensor 元组(如果传递 return_dict=False 或当 config.return_dict=False 时),包含各种元素,具体取决于配置(EfficientNetConfig)和输入。

  • last_hidden_state (torch.FloatTensor, 形状为 (batch_size, num_channels, height, width)) — 模型最后一层输出的隐藏状态序列。

  • pooler_output (torch.FloatTensor, 形状为 (batch_size, hidden_size)) — 经过空间维度池化操作后的最后一层隐藏状态。

  • hidden_states (tuple(torch.FloatTensor), 可选, 当传递 output_hidden_states=Trueconfig.output_hidden_states=True 时返回) — torch.FloatTensor 的元组(如果模型有嵌入层,则第一个是嵌入层的输出,然后是每个层的输出),形状为 (batch_size, num_channels, height, width)

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

EfficientNetModel 的前向方法,重写了 __call__ 特殊方法。

虽然前向传递的配方需要在此函数内定义,但之后应调用 Module 实例而不是此函数,因为前者会处理运行前处理和后处理步骤,而后者会静默地忽略它们。

示例

EfficientNetForImageClassification

class transformers.EfficientNetForImageClassification

< >

( config )

参数

带有图像分类头的 EfficientNet 模型(在池化特征之上有一个线性层),例如用于 ImageNet。

此模型继承自 PreTrainedModel。请查阅超类文档以了解库为其所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、修剪头等)。

该模型也是 PyTorch 的 torch.nn.Module 子类。可以像常规的 PyTorch 模块一样使用它,并参考 PyTorch 文档了解所有与常规用法和行为相关的事项。

forward

< >

( pixel_values: typing.Optional[torch.FloatTensor] = None labels: typing.Optional[torch.LongTensor] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None ) transformers.modeling_outputs.ImageClassifierOutputWithNoAttentiontuple(torch.FloatTensor)

参数

  • pixel_values (torch.FloatTensor,形状为 (batch_size, num_channels, image_size, image_size), 可选) — 对应于输入图像的张量。像素值可以使用 {image_processor_class} 获得。有关详细信息,请参阅 {image_processor_class}.__call__{processor_class} 使用 {image_processor_class} 处理图像)。
  • labels (torch.LongTensor,形状为 (batch_size,), 可选) — 用于计算图像分类/回归损失的标签。索引应在 [0, ..., config.num_labels - 1] 范围内。如果 config.num_labels == 1,则计算回归损失(均方损失),如果 config.num_labels > 1,则计算分类损失(交叉熵)。
  • output_hidden_states (bool, 可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参阅返回张量下的 hidden_states
  • return_dict (bool, 可选) — 是否返回 ModelOutput 而不是普通的元组。

返回

transformers.modeling_outputs.ImageClassifierOutputWithNoAttentiontuple(torch.FloatTensor)

一个 transformers.modeling_outputs.ImageClassifierOutputWithNoAttention 或一个 torch.FloatTensor 元组(如果传递 return_dict=False 或当 config.return_dict=False 时),包含各种元素,具体取决于配置(EfficientNetConfig)和输入。

  • loss (形状为 (1,)torch.FloatTensor可选,当提供 labels 时返回) — 分类损失(如果 config.num_labels==1,则为回归损失)。
  • logits (形状为 (batch_size, config.num_labels)torch.FloatTensor) — 分类(如果 config.num_labels==1,则为回归)分数(SoftMax 之前)。
  • hidden_states (tuple(torch.FloatTensor), 可选, 当传递 output_hidden_states=Trueconfig.output_hidden_states=True 时返回) — torch.FloatTensor 的元组(如果模型有嵌入层,则第一个是嵌入层的输出,然后是每个阶段的输出),形状为 (batch_size, num_channels, height, width)。模型在每个阶段输出的隐藏状态(也称为特征图)。

EfficientNetForImageClassification 的前向方法,重写了 __call__ 特殊方法。

虽然前向传递的配方需要在此函数内定义,但之后应调用 Module 实例而不是此函数,因为前者会处理运行前处理和后处理步骤,而后者会静默地忽略它们。

示例

>>> 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])
...
< > 在 GitHub 上更新