Transformers documentation
EfficientNet
This model was published in HF papers on 2019-05-28 and contributed to Hugging Face Transformers on 2023-02-20.
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
< source >( transformers_version: str | None = Nonearchitectures: list[str] | None = Noneoutput_hidden_states: bool | None = Falsereturn_dict: bool | None = Truedtype: typing.Union[str, ForwardRef('torch.dtype'), NoneType] = Nonechunk_size_feed_forward: int = 0is_encoder_decoder: bool = Falseid2label: dict[int, str] | dict[str, str] | None = Nonelabel2id: dict[str, int] | dict[str, str] | None = Noneproblem_type: typing.Optional[typing.Literal['regression', 'single_label_classification', 'multi_label_classification']] = Nonenum_channels: int = 3image_size: int | list[int] | tuple[int, int] = 600width_coefficient: float = 2.0depth_coefficient: float = 3.1depth_divisor: int = 8kernel_sizes: list[int] | tuple[int, ...] = (3, 3, 5, 3, 5, 5, 3)in_channels: list[int] | tuple[int, ...] = (32, 16, 24, 40, 80, 112, 192)out_channels: list[int] | tuple[int, ...] = (16, 24, 40, 80, 112, 192, 320)depthwise_padding: list[int] | tuple[int, ...] = ()strides: list[int] | tuple[int, ...] = (1, 2, 2, 2, 1, 2, 1)num_block_repeats: list[int] | tuple[int, ...] = (1, 2, 2, 3, 3, 4, 1)expand_ratios: list[int] | tuple[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 | int = 0.5drop_connect_rate: float | int = 0.2 )
Parameters
- num_channels (
int, optional, defaults to3) — The number of input channels. - image_size (
Union[int, list[int], tuple[int, int]], optional, defaults to600) — The size (resolution) of each image. - 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 (
Union[list[int], tuple[int, ...]], optional, defaults to(32, 16, 24, 40, 80, 112, 192)) — The number of input channels. - 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 (
Union[list[int], tuple[int, ...]], optional, defaults to(1, 2, 2, 2, 1, 2, 1)) — Stride at each stage of the model. - 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, optional, defaults toswish) — The non-linear activation function (function or string) in the decoder. For example,"gelu","relu","silu", etc. - hidden_dim (
int, optional, defaults to2560) — Dimension of the hidden representations. - pooling_type (
strorfunction, 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 to0.02) — The standard deviation of the truncated_normal_initializer for initializing all weight matrices. - batch_norm_eps (
float, optional, defaults to0.001) — 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 (
Union[float, int], optional, defaults to0.5) — The ratio for all dropout layers. - 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 a 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 google/efficientnet-b7
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.configEfficientNetImageProcessor
class transformers.EfficientNetImageProcessor
< source >( **kwargs: Unpack )
Parameters
- do_convert_rgb (
bool, kwargs, optional) — Whether to convert the image to RGB. - do_resize (
bool, kwargs, optional, defaults toTrue) — Whether to resize the image. - size (
Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs, defaults to{'height' -- 346, 'width': 346}): Describes the maximum input dimensions to the model. - default_to_square (
bool, kwargs, optional, defaults toTrue) — Whether to default to a square image when resizing, if size is an int. - crop_size (
Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs, defaults to{'height' -- 289, 'width': 289}): Size of the output image after applyingcenter_crop. - resample (
Annotated[Union[int, PILImageResampling, NoneType], None], kwargs, defaults toResampling.BICUBIC) — Resampling filter to use if resizing the image. This can be one of the enumPILImageResampling. Only has an effect ifdo_resizeis set toTrue. - do_rescale (
bool, kwargs, optional, defaults toTrue) — Whether to rescale the image. - rescale_factor (
float, kwargs, optional, defaults to0.00392156862745098) — Rescale factor to rescale the image by ifdo_rescaleis set toTrue. - do_normalize (
bool, kwargs, optional, defaults toTrue) — Whether to normalize the image. - image_mean (
Union[float, list[float], tuple[float, ...]], kwargs, optional, defaults to[0.5, 0.5, 0.5]) — Image mean to use for normalization. Only has an effect ifdo_normalizeis set toTrue. - image_std (
Union[float, list[float], tuple[float, ...]], kwargs, optional, defaults to[0.5, 0.5, 0.5]) — Image standard deviation to use for normalization. Only has an effect ifdo_normalizeis set toTrue. - do_pad (
bool, kwargs, optional) — Whether to pad the image. Padding is done either to the largest size in the batch or to a fixed square size per image. The exact padding strategy depends on the model. - pad_size (
Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — The size in{"height": int, "width" int}to pad the images to. Must be larger than any image size provided for preprocessing. Ifpad_sizeis not provided, images will be padded to the largest height and width in the batch. Applied only whendo_pad=True. - do_center_crop (
bool, kwargs, optional, defaults toFalse) — Whether to center crop the image. - data_format (
Union[str, ~image_utils.ChannelDimension], kwargs, optional) — OnlyChannelDimension.FIRSTis supported. Added for compatibility with slow processors. - input_data_format (
Union[str, ~image_utils.ChannelDimension], kwargs, 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"orChannelDimension.FIRST: image in (num_channels, height, width) format."channels_last"orChannelDimension.LAST: image in (height, width, num_channels) format."none"orChannelDimension.NONE: image in (height, width) format.
- device (
Annotated[Union[str, torch.device, NoneType], None], kwargs) — The device to process the videos on. If unset, the device is inferred from the input videos. - return_tensors (
Annotated[str | ~utils.generic.TensorType | None, None], kwargs) — Returns stacked tensors if set to'pt', otherwise returns a list of tensors. - disable_grouping (
bool, kwargs, optional) — Whether to disable grouping of images by size to process them individually and not in batches. If None, will be set to True if the images are on CPU, and False otherwise. This choice is based on empirical observations, as detailed here: https://github.com/huggingface/transformers/pull/38157 - image_seq_length (
int, kwargs, optional) — The number of image tokens to be used for each image in the input. Added for backward compatibility but this should be set as a processor attribute in future models. - rescale_offset (
bool, kwargs, optional, defaults toself.rescale_offset) — Whether to rescale the image between [-max_range/2, scale_range/2] instead of [0, scale_range]. - include_top (
bool, kwargs, optional, defaults toself.include_top) — Normalize the image again with the standard deviation only for image classification if set to True.
Constructs a EfficientNetImageProcessor image processor.
preprocess
< source >( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']]*args**kwargs: Unpack ) → ~image_processing_base.BatchFeature
Parameters
- images (
Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]]) — 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, setdo_rescale=False. - do_convert_rgb (
bool, kwargs, optional) — Whether to convert the image to RGB. - do_resize (
bool, kwargs, optional) — Whether to resize the image. - size (
Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — Describes the maximum input dimensions to the model. - default_to_square (
bool, kwargs, optional) — Whether to default to a square image when resizing, if size is an int. - crop_size (
Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — Size of the output image after applyingcenter_crop. - resample (
Annotated[Union[int, PILImageResampling, NoneType], None], kwargs) — Resampling filter to use if resizing the image. This can be one of the enumPILImageResampling. Only has an effect ifdo_resizeis set toTrue. - do_rescale (
bool, kwargs, optional) — Whether to rescale the image. - rescale_factor (
float, kwargs, optional) — Rescale factor to rescale the image by ifdo_rescaleis set toTrue. - do_normalize (
bool, kwargs, optional) — Whether to normalize the image. - image_mean (
Union[float, list[float], tuple[float, ...]], kwargs, optional) — Image mean to use for normalization. Only has an effect ifdo_normalizeis set toTrue. - image_std (
Union[float, list[float], tuple[float, ...]], kwargs, optional) — Image standard deviation to use for normalization. Only has an effect ifdo_normalizeis set toTrue. - do_pad (
bool, kwargs, optional) — Whether to pad the image. Padding is done either to the largest size in the batch or to a fixed square size per image. The exact padding strategy depends on the model. - pad_size (
Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — The size in{"height": int, "width" int}to pad the images to. Must be larger than any image size provided for preprocessing. Ifpad_sizeis not provided, images will be padded to the largest height and width in the batch. Applied only whendo_pad=True. - do_center_crop (
bool, kwargs, optional) — Whether to center crop the image. - data_format (
Union[str, ~image_utils.ChannelDimension], kwargs, optional) — OnlyChannelDimension.FIRSTis supported. Added for compatibility with slow processors. - input_data_format (
Union[str, ~image_utils.ChannelDimension], kwargs, 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"orChannelDimension.FIRST: image in (num_channels, height, width) format."channels_last"orChannelDimension.LAST: image in (height, width, num_channels) format."none"orChannelDimension.NONE: image in (height, width) format.
- device (
Annotated[Union[str, torch.device, NoneType], None], kwargs) — The device to process the videos on. If unset, the device is inferred from the input videos. - return_tensors (
Annotated[str | ~utils.generic.TensorType | None, None], kwargs) — Returns stacked tensors if set to'pt', otherwise returns a list of tensors. - disable_grouping (
bool, kwargs, optional) — Whether to disable grouping of images by size to process them individually and not in batches. If None, will be set to True if the images are on CPU, and False otherwise. This choice is based on empirical observations, as detailed here: https://github.com/huggingface/transformers/pull/38157 - image_seq_length (
int, kwargs, optional) — The number of image tokens to be used for each image in the input. Added for backward compatibility but this should be set as a processor attribute in future models.
Returns
~image_processing_base.BatchFeature
- data (
dict) — Dictionary of lists/arrays/tensors returned by the call method (‘pixel_values’, etc.). - tensor_type (
Union[None, str, TensorType], optional) — You can give a tensor_type here to convert the lists of integers in PyTorch/Numpy Tensors at initialization.
EfficientNetImageProcessorPil
class transformers.EfficientNetImageProcessorPil
< source >( **kwargs: Unpack )
Parameters
- do_convert_rgb (
bool, kwargs, optional) — Whether to convert the image to RGB. - do_resize (
bool, kwargs, optional, defaults toTrue) — Whether to resize the image. - size (
Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs, defaults to{'height' -- 346, 'width': 346}): Describes the maximum input dimensions to the model. - default_to_square (
bool, kwargs, optional, defaults toTrue) — Whether to default to a square image when resizing, if size is an int. - crop_size (
Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs, defaults to{'height' -- 289, 'width': 289}): Size of the output image after applyingcenter_crop. - resample (
Annotated[Union[int, PILImageResampling, NoneType], None], kwargs, defaults toResampling.BICUBIC) — Resampling filter to use if resizing the image. This can be one of the enumPILImageResampling. Only has an effect ifdo_resizeis set toTrue. - do_rescale (
bool, kwargs, optional, defaults toTrue) — Whether to rescale the image. - rescale_factor (
float, kwargs, optional, defaults to0.00392156862745098) — Rescale factor to rescale the image by ifdo_rescaleis set toTrue. - do_normalize (
bool, kwargs, optional, defaults toTrue) — Whether to normalize the image. - image_mean (
Union[float, list[float], tuple[float, ...]], kwargs, optional, defaults to[0.5, 0.5, 0.5]) — Image mean to use for normalization. Only has an effect ifdo_normalizeis set toTrue. - image_std (
Union[float, list[float], tuple[float, ...]], kwargs, optional, defaults to[0.5, 0.5, 0.5]) — Image standard deviation to use for normalization. Only has an effect ifdo_normalizeis set toTrue. - do_pad (
bool, kwargs, optional) — Whether to pad the image. Padding is done either to the largest size in the batch or to a fixed square size per image. The exact padding strategy depends on the model. - pad_size (
Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — The size in{"height": int, "width" int}to pad the images to. Must be larger than any image size provided for preprocessing. Ifpad_sizeis not provided, images will be padded to the largest height and width in the batch. Applied only whendo_pad=True. - do_center_crop (
bool, kwargs, optional, defaults toFalse) — Whether to center crop the image. - data_format (
Union[str, ~image_utils.ChannelDimension], kwargs, optional) — OnlyChannelDimension.FIRSTis supported. Added for compatibility with slow processors. - input_data_format (
Union[str, ~image_utils.ChannelDimension], kwargs, 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"orChannelDimension.FIRST: image in (num_channels, height, width) format."channels_last"orChannelDimension.LAST: image in (height, width, num_channels) format."none"orChannelDimension.NONE: image in (height, width) format.
- device (
Annotated[Union[str, torch.device, NoneType], None], kwargs) — The device to process the videos on. If unset, the device is inferred from the input videos. - return_tensors (
Annotated[str | ~utils.generic.TensorType | None, None], kwargs) — Returns stacked tensors if set to'pt', otherwise returns a list of tensors. - disable_grouping (
bool, kwargs, optional) — Whether to disable grouping of images by size to process them individually and not in batches. If None, will be set to True if the images are on CPU, and False otherwise. This choice is based on empirical observations, as detailed here: https://github.com/huggingface/transformers/pull/38157 - image_seq_length (
int, kwargs, optional) — The number of image tokens to be used for each image in the input. Added for backward compatibility but this should be set as a processor attribute in future models. - rescale_offset (
bool, kwargs, optional, defaults toself.rescale_offset) — Whether to rescale the image between [-max_range/2, scale_range/2] instead of [0, scale_range]. - include_top (
bool, kwargs, optional, defaults toself.include_top) — Normalize the image again with the standard deviation only for image classification if set to True.
Constructs a EfficientNetImageProcessor image processor.
preprocess
< source >( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']]*args**kwargs: Unpack ) → ~image_processing_base.BatchFeature
Parameters
- images (
Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]]) — 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, setdo_rescale=False. - do_convert_rgb (
bool, kwargs, optional) — Whether to convert the image to RGB. - do_resize (
bool, kwargs, optional) — Whether to resize the image. - size (
Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — Describes the maximum input dimensions to the model. - default_to_square (
bool, kwargs, optional) — Whether to default to a square image when resizing, if size is an int. - crop_size (
Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — Size of the output image after applyingcenter_crop. - resample (
Annotated[Union[int, PILImageResampling, NoneType], None], kwargs) — Resampling filter to use if resizing the image. This can be one of the enumPILImageResampling. Only has an effect ifdo_resizeis set toTrue. - do_rescale (
bool, kwargs, optional) — Whether to rescale the image. - rescale_factor (
float, kwargs, optional) — Rescale factor to rescale the image by ifdo_rescaleis set toTrue. - do_normalize (
bool, kwargs, optional) — Whether to normalize the image. - image_mean (
Union[float, list[float], tuple[float, ...]], kwargs, optional) — Image mean to use for normalization. Only has an effect ifdo_normalizeis set toTrue. - image_std (
Union[float, list[float], tuple[float, ...]], kwargs, optional) — Image standard deviation to use for normalization. Only has an effect ifdo_normalizeis set toTrue. - do_pad (
bool, kwargs, optional) — Whether to pad the image. Padding is done either to the largest size in the batch or to a fixed square size per image. The exact padding strategy depends on the model. - pad_size (
Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — The size in{"height": int, "width" int}to pad the images to. Must be larger than any image size provided for preprocessing. Ifpad_sizeis not provided, images will be padded to the largest height and width in the batch. Applied only whendo_pad=True. - do_center_crop (
bool, kwargs, optional) — Whether to center crop the image. - data_format (
Union[str, ~image_utils.ChannelDimension], kwargs, optional) — OnlyChannelDimension.FIRSTis supported. Added for compatibility with slow processors. - input_data_format (
Union[str, ~image_utils.ChannelDimension], kwargs, 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"orChannelDimension.FIRST: image in (num_channels, height, width) format."channels_last"orChannelDimension.LAST: image in (height, width, num_channels) format."none"orChannelDimension.NONE: image in (height, width) format.
- device (
Annotated[Union[str, torch.device, NoneType], None], kwargs) — The device to process the videos on. If unset, the device is inferred from the input videos. - return_tensors (
Annotated[str | ~utils.generic.TensorType | None, None], kwargs) — Returns stacked tensors if set to'pt', otherwise returns a list of tensors. - disable_grouping (
bool, kwargs, optional) — Whether to disable grouping of images by size to process them individually and not in batches. If None, will be set to True if the images are on CPU, and False otherwise. This choice is based on empirical observations, as detailed here: https://github.com/huggingface/transformers/pull/38157 - image_seq_length (
int, kwargs, optional) — The number of image tokens to be used for each image in the input. Added for backward compatibility but this should be set as a processor attribute in future models.
Returns
~image_processing_base.BatchFeature
- data (
dict) — Dictionary of lists/arrays/tensors returned by the call method (‘pixel_values’, etc.). - tensor_type (
Union[None, str, TensorType], optional) — You can give a tensor_type here to convert the lists of integers in PyTorch/Numpy Tensors at initialization.
EfficientNetModel
class transformers.EfficientNetModel
< source >( 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 hidden-states without any specific head on top.
This model inherits from PreTrainedModel. Check the superclass documentation for the generic methods the library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads etc.)
This model is also 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
< source >( pixel_values: typing.Optional[torch.FloatTensor] = Noneoutput_hidden_states: bool | None = Nonereturn_dict: bool | None = None**kwargs ) → BaseModelOutputWithPoolingAndNoAttention or tuple(torch.FloatTensor)
Parameters
- pixel_values (
torch.FloatTensorof shape(batch_size, num_channels, image_size, image_size), optional) — The tensors corresponding to the input images. Pixel values can be obtained using EfficientNetImageProcessor. SeeEfficientNetImageProcessor.__call__()for details (processor_classuses EfficientNetImageProcessor for processing images). - output_hidden_states (
bool, optional) — Whether or not to return the hidden states of all layers. Seehidden_statesunder returned tensors for more detail. - return_dict (
bool, optional) — Whether or not to return a ModelOutput instead of a plain tuple.
Returns
BaseModelOutputWithPoolingAndNoAttention or tuple(torch.FloatTensor)
A 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.
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
Moduleinstance afterwards instead of this since the former takes care of running the pre and post processing steps while the latter silently ignores them.
last_hidden_state (
torch.FloatTensorof shape(batch_size, num_channels, height, width)) — Sequence of hidden-states at the output of the last layer of the model.pooler_output (
torch.FloatTensorof shape(batch_size, hidden_size)) — Last layer hidden-state after a pooling operation on the spatial dimensions.hidden_states (
tuple(torch.FloatTensor), optional, returned whenoutput_hidden_states=Trueis passed or whenconfig.output_hidden_states=True) — Tuple oftorch.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.
EfficientNetForImageClassification
class transformers.EfficientNetForImageClassification
< source >( config )
Parameters
- config (EfficientNetForImageClassification) — 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 inherits from PreTrainedModel. Check the superclass documentation for the generic methods the library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads etc.)
This model is also 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
< source >( pixel_values: typing.Optional[torch.FloatTensor] = Nonelabels: typing.Optional[torch.LongTensor] = Noneoutput_hidden_states: bool | None = Nonereturn_dict: bool | None = None**kwargs ) → ImageClassifierOutputWithNoAttention or tuple(torch.FloatTensor)
Parameters
- pixel_values (
torch.FloatTensorof shape(batch_size, num_channels, image_size, image_size), optional) — The tensors corresponding to the input images. Pixel values can be obtained using EfficientNetImageProcessor. SeeEfficientNetImageProcessor.__call__()for details (processor_classuses EfficientNetImageProcessor for processing images). - labels (
torch.LongTensorof shape(batch_size,), optional) — Labels for computing the image classification/regression loss. Indices should be in[0, ..., config.num_labels - 1]. Ifconfig.num_labels == 1a regression loss is computed (Mean-Square loss), Ifconfig.num_labels > 1a classification loss is computed (Cross-Entropy). - output_hidden_states (
bool, optional) — Whether or not to return the hidden states of all layers. Seehidden_statesunder returned tensors for more detail. - return_dict (
bool, optional) — Whether or not to return a ModelOutput instead of a plain tuple.
Returns
ImageClassifierOutputWithNoAttention or tuple(torch.FloatTensor)
A 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.
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
Moduleinstance afterwards instead of this since the former takes care of running the pre and post processing steps while the latter silently ignores them.
- loss (
torch.FloatTensorof shape(1,), optional, returned whenlabelsis provided) — Classification (or regression if config.num_labels==1) loss. - logits (
torch.FloatTensorof shape(batch_size, config.num_labels)) — Classification (or regression if config.num_labels==1) scores (before SoftMax). - hidden_states (
tuple(torch.FloatTensor), optional, returned whenoutput_hidden_states=Trueis passed or whenconfig.output_hidden_states=True) — Tuple oftorch.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.
Example:
>>> 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])
...