EfficientNet
Last updated
Last updated
The EfficientNet model was proposed in 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 . The original code can be found .
( num_channels: int = 3image_size: int = 600width_coefficient: float = 2.0depth_coefficient: float = 3.1depth_divisor: int = 8kernel_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.25hidden_act: str = 'swish'hidden_dim: int = 2560pooling_type: str = 'mean'initializer_range: float = 0.02batch_norm_eps: float = 0.001batch_norm_momentum: float = 0.99dropout_rate: float = 0.5drop_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.
Example:
Copied
( do_resize: bool = Truesize: typing.Dict[str, int] = Noneresample: Resampling = 0do_center_crop: bool = Falsecrop_size: typing.Dict[str, int] = Nonerescale_factor: typing.Union[int, float] = 0.00392156862745098rescale_offset: bool = Falsedo_rescale: bool = Truedo_normalize: bool = Trueimage_mean: typing.Union[float, typing.List[float], NoneType] = Noneimage_std: typing.Union[float, typing.List[float], NoneType] = Noneinclude_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 PILImageResampling.NEAREST
) — 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
.
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.
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_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: 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 = Nonesize: typing.Dict[str, int] = Noneresample = Nonedo_center_crop: bool = Nonecrop_size: typing.Dict[str, int] = Nonedo_rescale: bool = Nonerescale_factor: float = Nonerescale_offset: bool = Nonedo_normalize: bool = Noneimage_mean: typing.Union[float, typing.List[float], NoneType] = Noneimage_std: typing.Union[float, typing.List[float], NoneType] = Noneinclude_top: bool = Nonereturn_tensors: typing.Union[str, transformers.utils.generic.TensorType, NoneType] = Nonedata_format: ChannelDimension = <ChannelDimension.FIRST: 'channels_first'>input_data_format: typing.Union[str, transformers.image_utils.ChannelDimension, NoneType] = None**kwargs )
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.
( config: EfficientNetConfig )
Parameters
forward
( pixel_values: FloatTensor = Noneoutput_hidden_states: typing.Optional[bool] = Nonereturn_dict: typing.Optional[bool] = None ) → transformers.modeling_outputs.BaseModelOutputWithPoolingAndNoAttention
or tuple(torch.FloatTensor)
Parameters
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.
Returns
transformers.modeling_outputs.BaseModelOutputWithPoolingAndNoAttention
or tuple(torch.FloatTensor)
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.
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:
Copied
( config )
Parameters
EfficientNet Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for ImageNet.
forward
Parameters
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.
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
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.
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:
Copied
This is the configuration class to store the configuration of a . 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 architecture.
Configuration objects inherit from and can be used to control the model outputs. Read the documentation from for more information.
config () — 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 method to load the model weights.
The bare EfficientNet model outputting raw features without any specific head on top. This model is a PyTorch subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior.
pixel_values (torch.FloatTensor
of shape (batch_size, num_channels, height, width)
) — Pixel values. Pixel values can be obtained using . See AutoImageProcessor.__call__()
for details.
return_dict (bool
, optional) — Whether or not to return a instead of a plain tuple.
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 () and inputs.
The forward method, overrides the __call__
special method.
config () — 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 method to load the model weights.
This model is a PyTorch subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior.
( pixel_values: FloatTensor = Nonelabels: typing.Optional[torch.LongTensor] = Noneoutput_hidden_states: typing.Optional[bool] = Nonereturn_dict: typing.Optional[bool] = None ) → or tuple(torch.FloatTensor)
pixel_values (torch.FloatTensor
of shape (batch_size, num_channels, height, width)
) — Pixel values. Pixel values can be obtained using . See AutoImageProcessor.__call__()
for details.
return_dict (bool
, optional) — Whether or not to return a instead of a plain tuple.
or tuple(torch.FloatTensor)
A 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 () and inputs.
The forward method, overrides the __call__
special method.