Transformers documentation

EfficientNet

Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

EfficientNet

Overview

The EfficientNet model was proposed in EfficientNet: Rethinking Model Scaling for Convolutional Neural Networks by Mingxing Tan and Quoc V. Le. EfficientNets are a family of image classification models, which achieve state-of-the-art accuracy, yet being an order-of-magnitude smaller and faster than previous models.

The abstract from the paper is the following:

Convolutional Neural Networks (ConvNets) are commonly developed at a fixed resource budget, and then scaled up for better accuracy if more resources are available. In this paper, we systematically study model scaling and identify that carefully balancing network depth, width, and resolution can lead to better performance. Based on this observation, we propose a new scaling method that uniformly scales all dimensions of depth/width/resolution using a simple yet highly effective compound coefficient. We demonstrate the effectiveness of this method on scaling up MobileNets and ResNet. To go even further, we use neural architecture search to design a new baseline network and scale it up to obtain a family of models, called EfficientNets, which achieve much better accuracy and efficiency than previous ConvNets. In particular, our EfficientNet-B7 achieves state-of-the-art 84.3% top-1 accuracy on ImageNet, while being 8.4x smaller and 6.1x faster on inference than the best existing ConvNet. Our EfficientNets also transfer well and achieve state-of-the-art accuracy on CIFAR-100 (91.7%), Flowers (98.8%), and 3 other transfer learning datasets, with an order of magnitude fewer parameters.

This model was contributed by adirik. The original code can be found here.

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 )

Parameters

  • num_channels (int, optional, defaults to 3) — The number of input channels.
  • image_size (int, optional, defaults to 600) — The input image size.
  • width_coefficient (float, optional, defaults to 2.0) — Scaling coefficient for network width at each stage.
  • depth_coefficient (float, optional, defaults to 3.1) — Scaling coefficient for network depth at each stage.
  • depth_divisor int, optional, defaults to 8) — A unit of network width.
  • kernel_sizes (List[int], optional, defaults to [3, 3, 5, 3, 5, 5, 3]) — List of kernel sizes to be used in each block.
  • in_channels (List[int], optional, defaults to [32, 16, 24, 40, 80, 112, 192]) — List of input channel sizes to be used in each block for convolutional layers.
  • out_channels (List[int], optional, defaults to [16, 24, 40, 80, 112, 192, 320]) — List of output channel sizes to be used in each block for convolutional layers.
  • depthwise_padding (List[int], optional, defaults to []) — List of block indices with square padding.
  • strides (List[int], optional, defaults to [1, 2, 2, 2, 1, 2, 1]) — List of stride sizes to be used in each block for convolutional layers.
  • num_block_repeats (List[int], optional, defaults to [1, 2, 2, 3, 3, 4, 1]) — List of the number of times each block is to repeated.
  • expand_ratios (List[int], optional, defaults to [1, 6, 6, 6, 6, 6, 6]) — List of scaling coefficient of each block.
  • squeeze_expansion_ratio (float, optional, defaults to 0.25) — Squeeze expansion ratio.
  • hidden_act (str or function, optional, defaults to "silu") — The non-linear activation function (function or string) in each block. If string, "gelu", "relu", "selu", “gelu_new”, “silu”and“mish”` are supported.
  • hiddem_dim (int, optional, defaults to 1280) — The hidden dimension of the layer before the classification head.
  • pooling_type (str or function, optional, defaults to "mean") — Type of final pooling to be applied before the dense classification head. Available options are ["mean", "max"]
  • initializer_range (float, optional, defaults to 0.02) — The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
  • batch_norm_eps (float, optional, defaults to 1e-3) — The epsilon used by the batch normalization layers.
  • batch_norm_momentum (float, optional, defaults to 0.99) — The momentum used by the batch normalization layers.
  • dropout_rate (float, optional, defaults to 0.5) — The dropout rate to be applied before final classifier layer.
  • drop_connect_rate (float, optional, defaults to 0.2) — The drop rate for skip connections.

This is the configuration class to store the configuration of a EfficientNetModel. It is used to instantiate an EfficientNet model according to the specified arguments, defining the model architecture. Instantiating a configuration with the defaults will yield a similar configuration to that of the EfficientNet google/efficientnet-b7 architecture.

Configuration objects inherit from PretrainedConfig and can be used to control the model outputs. Read the documentation from PretrainedConfig for more information.

Example:

>>> 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: Dict = None resample: Resampling = 0 do_center_crop: bool = False crop_size: Dict = None rescale_factor: Union = 0.00392156862745098 rescale_offset: bool = False do_rescale: bool = True do_normalize: bool = True image_mean: Union = None image_std: Union = None include_top: bool = True **kwargs )

Parameters

  • do_resize (bool, optional, defaults to True) — Whether to resize the image’s (height, width) dimensions to the specified size. Can be overridden by do_resize in preprocess.
  • size (Dict[str, int] optional, defaults to {"height" -- 346, "width": 346}): Size of the image after resize. Can be overridden by size in preprocess.
  • resample (PILImageResampling filter, optional, defaults to 0) — Resampling filter to use if resizing the image. Can be overridden by resample in preprocess.
  • do_center_crop (bool, optional, defaults to False) — Whether to center crop the image. If the input size is smaller than crop_size along any edge, the image is padded with 0’s and then center cropped. Can be overridden by do_center_crop in preprocess.
  • crop_size (Dict[str, int], optional, defaults to {"height" -- 289, "width": 289}): Desired output size when applying center-cropping. Can be overridden by crop_size in preprocess.
  • rescale_factor (int or float, optional, defaults to 1/255) — Scale factor to use if rescaling the image. Can be overridden by the rescale_factor parameter in the preprocess method.
  • rescale_offset (bool, optional, defaults to False) — Whether to rescale the image between [-scale_range, scale_range] instead of [0, scale_range]. Can be overridden by the rescale_factor parameter in the preprocess method.
  • do_rescale (bool, optional, defaults to True) — Whether to rescale the image by the specified scale rescale_factor. Can be overridden by the do_rescale parameter in the preprocess method.
  • do_normalize (bool, optional, defaults to True) — Whether to normalize the image. Can be overridden by the do_normalize parameter in the preprocess method.
  • image_mean (float or List[float], optional, defaults to IMAGENET_STANDARD_MEAN) — Mean to use if normalizing the image. This is a float or list of floats the length of the number of channels in the image. Can be overridden by the image_mean parameter in the preprocess method.
  • image_std (float or List[float], optional, defaults to IMAGENET_STANDARD_STD) — Standard deviation to use if normalizing the image. This is a float or list of floats the length of the number of channels in the image. Can be overridden by the image_std parameter in the preprocess method.
  • include_top (bool, optional, defaults to True) — Whether to rescale the image again. Should be set to True if the inputs are used for image classification.

Constructs a EfficientNet image processor.

preprocess

< >

( images: Union do_resize: bool = None size: Dict = None resample = None do_center_crop: bool = None crop_size: Dict = None do_rescale: bool = None rescale_factor: float = None rescale_offset: bool = None do_normalize: bool = None image_mean: Union = None image_std: Union = None include_top: bool = None return_tensors: Union = None data_format: ChannelDimension = <ChannelDimension.FIRST: 'channels_first'> input_data_format: Union = None )

Parameters

  • images (ImageInput) — Image to preprocess. Expects a single or batch of images with pixel values ranging from 0 to 255. If passing in images with pixel values between 0 and 1, set do_rescale=False.
  • do_resize (bool, optional, defaults to self.do_resize) — Whether to resize the image.
  • size (Dict[str, int], optional, defaults to self.size) — Size of the image after resize.
  • resample (PILImageResampling, optional, defaults to self.resample) — PILImageResampling filter to use if resizing the image Only has an effect if do_resize is set to True.
  • do_center_crop (bool, optional, defaults to self.do_center_crop) — Whether to center crop the image.
  • crop_size (Dict[str, int], optional, defaults to self.crop_size) — Size of the image after center crop. If one edge the image is smaller than crop_size, it will be padded with zeros and then cropped
  • do_rescale (bool, optional, defaults to self.do_rescale) — Whether to rescale the image values between [0 - 1].
  • rescale_factor (float, optional, defaults to self.rescale_factor) — Rescale factor to rescale the image by if do_rescale is set to True.
  • rescale_offset (bool, optional, defaults to self.rescale_offset) — Whether to rescale the image between [-scale_range, scale_range] instead of [0, scale_range].
  • do_normalize (bool, optional, defaults to self.do_normalize) — Whether to normalize the image.
  • image_mean (float or List[float], optional, defaults to self.image_mean) — Image mean.
  • image_std (float or List[float], optional, defaults to self.image_std) — Image standard deviation.
  • include_top (bool, optional, defaults to self.include_top) — Rescales the image again for image classification if set to True.
  • return_tensors (str or TensorType, optional) — The type of tensors to return. Can be one of:
    • None: Return a list of np.ndarray.
    • TensorType.TENSORFLOW or 'tf': Return a batch of type tf.Tensor.
    • TensorType.PYTORCH or 'pt': Return a batch of type torch.Tensor.
    • TensorType.NUMPY or 'np': Return a batch of type np.ndarray.
    • TensorType.JAX or 'jax': Return a batch of type jax.numpy.ndarray.
  • data_format (ChannelDimension or str, optional, defaults to ChannelDimension.FIRST) — The channel dimension format for the output image. Can be one of:
    • ChannelDimension.FIRST: image in (num_channels, height, width) format.
    • ChannelDimension.LAST: image in (height, width, num_channels) format.
  • input_data_format (ChannelDimension or str, optional) — The channel dimension format for the input image. If unset, the channel dimension format is inferred from the input image. Can be one of:
    • "channels_first" or ChannelDimension.FIRST: image in (num_channels, height, width) format.
    • "channels_last" or ChannelDimension.LAST: image in (height, width, num_channels) format.
    • "none" or ChannelDimension.NONE: image in (height, width) format.

Preprocess an image or batch of images.

EfficientNetModel

class transformers.EfficientNetModel

< >

( config: EfficientNetConfig )

Parameters

  • config (EfficientNetConfig) — Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the from_pretrained() method to load the model weights.

The bare EfficientNet model outputting raw features without any specific head on top. This model is a PyTorch torch.nn.Module subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior.

forward

< >

( pixel_values: FloatTensor = None output_hidden_states: Optional = None return_dict: Optional = None ) β†’ transformers.modeling_outputs.BaseModelOutputWithPoolingAndNoAttention or tuple(torch.FloatTensor)

Parameters

  • pixel_values (torch.FloatTensor of shape (batch_size, num_channels, height, width)) — Pixel values. Pixel values can be obtained using AutoImageProcessor. See AutoImageProcessor.__call__() for details.
  • output_hidden_states (bool, optional) — Whether or not to return the hidden states of all layers. See hidden_states under returned tensors for more detail.
  • return_dict (bool, optional) — Whether or not to return a ModelOutput instead of a plain tuple.

Returns

transformers.modeling_outputs.BaseModelOutputWithPoolingAndNoAttention or tuple(torch.FloatTensor)

A transformers.modeling_outputs.BaseModelOutputWithPoolingAndNoAttention or a tuple of torch.FloatTensor (if return_dict=False is passed or when config.return_dict=False) comprising various elements depending on the configuration (EfficientNetConfig) and inputs.

  • last_hidden_state (torch.FloatTensor of shape (batch_size, num_channels, height, width)) β€” Sequence of hidden-states at the output of the last layer of the model.

  • pooler_output (torch.FloatTensor of shape (batch_size, hidden_size)) β€” Last layer hidden-state after a pooling operation on the spatial dimensions.

  • hidden_states (tuple(torch.FloatTensor), optional, returned when output_hidden_states=True is passed or when config.output_hidden_states=True) β€” Tuple of torch.FloatTensor (one for the output of the embeddings, if the model has an embedding layer, + one for the output of each layer) of shape (batch_size, num_channels, height, width).

    Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.

The EfficientNetModel forward method, overrides the __call__ special method.

Although the recipe for forward pass needs to be defined within this function, one should call the Module instance afterwards instead of this since the former takes care of running the pre and post processing steps while the latter silently ignores them.

Example:

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

Parameters

  • config (EfficientNetConfig) — Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the from_pretrained() method to load the model weights.

EfficientNet Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for ImageNet.

This model is a PyTorch torch.nn.Module subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior.

forward

< >

( pixel_values: FloatTensor = None labels: Optional = None output_hidden_states: Optional = None return_dict: Optional = None ) β†’ transformers.modeling_outputs.ImageClassifierOutputWithNoAttention or tuple(torch.FloatTensor)

Parameters

  • pixel_values (torch.FloatTensor of shape (batch_size, num_channels, height, width)) — Pixel values. Pixel values can be obtained using AutoImageProcessor. See AutoImageProcessor.__call__() for details.
  • output_hidden_states (bool, optional) — Whether or not to return the hidden states of all layers. See hidden_states under returned tensors for more detail.
  • return_dict (bool, optional) — Whether or not to return a ModelOutput instead of a plain tuple.
  • labels (torch.LongTensor of shape (batch_size,), optional) — Labels for computing the image classification/regression loss. Indices should be in [0, ..., config.num_labels - 1]. If config.num_labels == 1 a regression loss is computed (Mean-Square loss), If config.num_labels > 1 a classification loss is computed (Cross-Entropy).

Returns

transformers.modeling_outputs.ImageClassifierOutputWithNoAttention or tuple(torch.FloatTensor)

A transformers.modeling_outputs.ImageClassifierOutputWithNoAttention or a tuple of torch.FloatTensor (if return_dict=False is passed or when config.return_dict=False) comprising various elements depending on the configuration (EfficientNetConfig) and inputs.

  • loss (torch.FloatTensor of shape (1,), optional, returned when labels is provided) β€” Classification (or regression if config.num_labels==1) loss.
  • logits (torch.FloatTensor of shape (batch_size, config.num_labels)) β€” Classification (or regression if config.num_labels==1) scores (before SoftMax).
  • hidden_states (tuple(torch.FloatTensor), optional, returned when output_hidden_states=True is passed or when config.output_hidden_states=True) β€” Tuple of torch.FloatTensor (one for the output of the embeddings, if the model has an embedding layer, + one for the output of each stage) of shape (batch_size, num_channels, height, width). Hidden-states (also called feature maps) of the model at the output of each stage.

The EfficientNetForImageClassification forward method, overrides the __call__ special method.

Although the recipe for forward pass needs to be defined within this function, one should call the Module instance afterwards instead of this since the former takes care of running the pre and post processing steps while the latter silently ignores them.

Example:

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