Transformers 文档

EfficientNet

EfficientNet

概述

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贡献。 原始代码可以在这里找到。

EfficientNet配置

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: typing.List[int] = [3, 3, 5, 3, 5, 5, 3] in_channels: typing.List[int] = [32, 16, 24, 40, 80, 112, 192] out_channels: typing.List[int] = [16, 24, 40, 80, 112, 192, 320] depthwise_padding: typing.List[int] = [] strides: typing.List[int] = [1, 2, 2, 2, 1, 2, 1] num_block_repeats: typing.List[int] = [1, 2, 2, 3, 3, 4, 1] expand_ratios: typing.List[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 = 0.5 drop_connect_rate: float = 0.2 **kwargs )

参数

  • num_channels (int, optional, defaults to 3) — 输入通道的数量。
  • image_size (int, optional, 默认为 600) — 输入图像的大小。
  • width_coefficient (float, 可选, 默认为 2.0) — 每个阶段网络宽度的缩放系数。
  • depth_coefficient (float, optional, 默认为 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], optional, defaults to []) — 具有方形填充的块索引列表。
  • strides (List[int], optional, defaults to [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, optional, defaults to 0.25) — 挤压扩展比率.
  • hidden_act (strfunction, 可选, 默认为 "silu") — 每个块中的非线性激活函数(函数或字符串)。如果是字符串,支持 "gelu", "relu", "selu", “gelu_new”, “silu”“mish”`。
  • hiddem_dim (int, optional, 默认为 1280) — 分类头之前的层的隐藏维度。
  • pooling_type (strfunction, 可选, 默认为 "mean") — 在应用密集分类头之前要应用的最终池化类型。可用的选项是 ["mean", "max"]
  • initializer_range (float, 可选, 默认为 0.02) — 用于初始化所有权重矩阵的截断正态初始化器的标准差。
  • batch_norm_eps (float, optional, defaults to 1e-3) — 批归一化层使用的epsilon值。
  • batch_norm_momentum (float, optional, defaults to 0.99) — 批量归一化层使用的动量。
  • dropout_rate (float, optional, defaults to 0.5) — 在最终分类器层之前应用的丢弃率。
  • drop_connect_rate (float, optional, defaults to 0.2) — 跳过连接的丢弃率。

这是用于存储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

transformers.EfficientNetImageProcessor

< >

( do_resize: bool = True size: typing.Dict[str, int] = None resample: Resampling = 0 do_center_crop: bool = False crop_size: typing.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, typing.List[float], NoneType] = None image_std: typing.Union[float, typing.List[float], NoneType] = None include_top: bool = True **kwargs )

参数

  • do_resize (bool, 可选, 默认为 True) — 是否将图像的(高度,宽度)尺寸调整为指定的 size。可以在 preprocess 中被 do_resize 覆盖。
  • size (Dict[str, int] optional, defaults to {"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图像处理器。

预处理

< >

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

参数

  • 图像 (ImageInput) — 要预处理的图像。期望输入单个或批量的图像,像素值范围在0到255之间。如果传入的图像像素值在0到1之间,请设置 do_rescale=False.
  • do_resize (bool, optional, defaults to self.do_resize) — 是否调整图像大小.
  • size (Dict[str, int], 可选, 默认为 self.size) — 图像在resize之后的大小.
  • resample (PILImageResampling, 可选, 默认为 self.resample) — 如果调整图像大小,则使用的PILImageResampling过滤器。仅在do_resize设置为True时有效。
  • do_center_crop (bool, optional, defaults to self.do_center_crop) — 是否对图像进行中心裁剪。
  • crop_size (Dict[str, int], 可选, 默认为 self.crop_size) — 图像中心裁剪后的大小。如果图像的某一边小于 crop_size,它将被填充零然后裁剪
  • do_rescale (bool, optional, defaults to self.do_rescale) — 是否将图像值缩放到 [0 - 1] 之间。
  • rescale_factor (float, optional, defaults to self.rescale_factor) — 如果do_rescale设置为True,则用于重新缩放图像的重新缩放因子。
  • rescale_offset (bool, optional, defaults to self.rescale_offset) — 是否在[-scale_range, scale_range]之间重新缩放图像,而不是在[0, scale_range]之间。
  • do_normalize (bool, optional, defaults to 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: 图像格式为 (num_channels, height, width)。
    • ChannelDimension.LAST: 图像格式为 (height, width, num_channels)。
  • input_data_format (ChannelDimensionstr, 可选) — 输入图像的通道维度格式。如果未设置,则从输入图像推断通道维度格式。可以是以下之一:
    • "channels_first"ChannelDimension.FIRST: 图像格式为 (num_channels, height, width)。
    • "channels_last"ChannelDimension.LAST: 图像格式为 (height, width, num_channels)。
    • "none"ChannelDimension.NONE: 图像格式为 (height, width)。

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

EfficientNetModel

transformers.EfficientNetModel

< >

( config: EfficientNetConfig )

参数

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

裸的EfficientNet模型输出原始特征,没有任何特定的头部。 此模型是PyTorch torch.nn.Module 的子类。将其 用作常规的PyTorch模块,并参考PyTorch文档以获取与一般使用和行为相关的所有事项。

前进

< >

( pixel_values: 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 of shape (batch_size, num_channels, height, width)) — 像素值。像素值可以使用AutoImageProcessor获取。详情请参见 AutoImageProcessor.__call__().
  • 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=True 或当 config.output_hidden_states=True 时返回) — 由 torch.FloatTensor 组成的元组(一个用于嵌入层的输出,如果模型有嵌入层,+ 一个用于每一层的输出)形状为 (batch_size, num_channels, height, width)

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

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

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

示例:

>>> from transformers import AutoImageProcessor, EfficientNetModel
>>> import torch
>>> from datasets import load_dataset

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

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

>>> inputs = image_processor(image, return_tensors="pt")

>>> with torch.no_grad():
...     outputs = model(**inputs)

>>> last_hidden_states = outputs.last_hidden_state
>>> list(last_hidden_states.shape)
[1, 768, 7, 7]

EfficientNetForImageClassification

class transformers.EfficientNetForImageClassification

< >

( config )

参数

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

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

该模型是一个PyTorch torch.nn.Module 子类。将其用作常规的PyTorch模块,并参考PyTorch文档以获取与一般使用和行为相关的所有信息。

前进

< >

( pixel_values: 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 of shape (batch_size, num_channels, height, width)) — 像素值。像素值可以使用AutoImageProcessor获取。详情请参见 AutoImageProcessor.__call__().
  • output_hidden_states (bool, optional) — 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回张量下的hidden_states
  • return_dict (bool, 可选) — 是否返回一个ModelOutput而不是一个普通的元组。
  • labels (torch.LongTensor of shape (batch_size,), optional) — 用于计算图像分类/回归损失的标签。索引应在 [0, ..., config.num_labels - 1] 范围内。如果 config.num_labels == 1,则计算回归损失(均方损失),如果 config.num_labels > 1,则计算分类损失(交叉熵)。

返回

transformers.modeling_outputs.ImageClassifierOutputWithNoAttentiontuple(torch.FloatTensor)

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

  • loss (torch.FloatTensor 形状为 (1,)可选,当提供 labels 时返回) — 分类(或回归,如果 config.num_labels==1)损失。
  • logits (torch.FloatTensor 形状为 (batch_size, config.num_labels)) — 分类(或回归,如果 config.num_labels==1)得分(在 SoftMax 之前)。
  • hidden_states (tuple(torch.FloatTensor)可选,当传递 output_hidden_states=True 或当 config.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", trust_remote_code=True)
>>> 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])
tabby, tabby cat
< > Update on GitHub