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 上更新

© . This site is unofficial and not affiliated with Hugging Face, Inc.