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 个迁移学习数据集上实现了最先进的精度,参数数量减少了一个数量级。
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: 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, 默认为 3) — 输入通道的数量。 - image_size (
int
, optional, 默认为 600) — 输入图像尺寸。 - width_coefficient (
float
, optional, 默认为 2.0) — 每个阶段网络宽度的缩放系数。 - depth_coefficient (
float
, optional, 默认为 3.1) — 每个阶段网络深度的缩放系数。 - depth_divisor
int
, optional, 默认为 8) — 网络宽度的单位。 - kernel_sizes (
List[int]
, optional, 默认为[3, 3, 5, 3, 5, 5, 3]
) — 每个块中使用的内核大小列表。 - in_channels (
List[int]
, optional, 默认为[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) — Squeeze expansion ratio(压缩扩展比率)。 - hidden_act (
str
或function
, 可选, 默认为"silu"
) — 每个块中的非线性激活函数(函数或字符串)。 如果是字符串,则支持"gelu"
,"relu"
,"selu",
“gelu_new”,
“silu”和
“mish”` 。 - hiddem_dim (
int
, 可选, 默认为 1280) — 分类头之前的层的隐藏维度。 - pooling_type (
str
或function
, 可选, 默认为"mean"
) — 在密集分类头之前应用的最终池化类型。 可用选项为 ["mean"
,"max"
] - initializer_range (
float
, 可选, 默认为 0.02) — 用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。 - batch_norm_eps (
float
, 可选, 默认为 1e-3) — 批量归一化层使用的 epsilon 值。 - batch_norm_momentum (
float
, 可选, 默认为 0.99) — 批量归一化层使用的 momentum 值。 - dropout_rate (
float
, 可选, 默认为 0.5) — 在最终分类器层之前应用的 dropout 比率。 - drop_connect_rate (
float
, 可选, 默认为 0.2) — 跳跃连接的 dropout 率。
这是用于存储 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
< source >( 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]
可选, 默认为{"height" -- 346, "width": 346}
):resize
后图像的大小。 可以被preprocess
中的size
重写。 - resample (
PILImageResampling
filter, 可选, 默认为 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 (
int
或float
, 可选, 默认为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 (
float
或List[float]
, 可选, 默认为IMAGENET_STANDARD_MEAN
) — 如果要归一化图像,则使用的均值。 这是一个浮点数或浮点数列表,其长度是图像中通道数的长度。 可以被preprocess
方法中的image_mean
参数重写。 - image_std (
float
或List[float]
, 可选, 默认为IMAGENET_STANDARD_STD
) — 如果要归一化图像,则使用的标准差。 这是一个浮点数或浮点数列表,其长度是图像中通道数的长度。 可以被preprocess
方法中的image_std
参数重写。 - include_top (
bool
, optional, defaults toTrue
) — 是否再次缩放图像。如果输入用于图像分类,则应设置为 True。
构建 EfficientNet 图像处理器。
preprocess
< source >( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['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 = <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
, optional, defaults toself.do_resize
) — 是否调整图像大小。 - size (
Dict[str, int]
, optional, defaults toself.size
) —resize
之后图像的尺寸。 - resample (
PILImageResampling
, optional, defaults toself.resample
) — 如果调整图像大小,则使用的 PILImageResampling 过滤器。仅当do_resize
设置为True
时才有效。 - do_center_crop (
bool
, optional, defaults toself.do_center_crop
) — 是否对图像进行中心裁剪。 - crop_size (
Dict[str, int]
, optional, defaults toself.crop_size
) — 中心裁剪后图像的尺寸。如果图像的某一边小于crop_size
,则将用零填充,然后再裁剪。 - do_rescale (
bool
, optional, defaults toself.do_rescale
) — 是否将图像值重新缩放到 [0 - 1] 之间。 - rescale_factor (
float
, optional, defaults toself.rescale_factor
) — 如果do_rescale
设置为True
,则通过此缩放因子来缩放图像。 - rescale_offset (
bool
, optional, defaults toself.rescale_offset
) — 是否将图像重新缩放到 [-scale_range, scale_range] 而不是 [0, scale_range] 之间。 - do_normalize (
bool
, optional, defaults toself.do_normalize
) — 是否对图像进行归一化。 - image_mean (
float
orList[float]
, optional, defaults toself.image_mean
) — 图像均值。 - image_std (
float
orList[float]
, optional, defaults toself.image_std
) — 图像标准差。 - include_top (
bool
, optional, defaults toself.include_top
) — 如果设置为 True,则再次缩放图像以进行图像分类。 - return_tensors (
str
orTensorType
, optional) — 要返回的张量类型。可以是以下之一: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 (
ChannelDimension
orstr
, optional, defaults toChannelDimension.FIRST
) — 输出图像的通道维度格式。可以是以下之一:ChannelDimension.FIRST
: 图像格式为 (num_channels, height, width)。ChannelDimension.LAST
: 图像格式为 (height, width, num_channels)。
- input_data_format (
ChannelDimension
orstr
, optional) — 输入图像的通道维度格式。如果未设置,则从输入图像推断通道维度格式。可以是以下之一:"channels_first"
或ChannelDimension.FIRST
: 图像格式为 (num_channels, height, width)。"channels_last"
或ChannelDimension.LAST
: 图像格式为 (height, width, num_channels)。"none"
或ChannelDimension.NONE
: 图像格式为 (height, width)。
预处理一个图像或一批图像。
EfficientNetModel
class transformers.EfficientNetModel
< source >( config: EfficientNetConfig )
参数
- config (EfficientNetConfig) — 具有模型所有参数的模型配置类。使用配置文件初始化不会加载与模型关联的权重,仅加载配置。查看 from_pretrained() 方法来加载模型权重。
裸 EfficientNet 模型,输出原始特征,顶部没有任何特定的 head。此模型是 PyTorch torch.nn.Module 子类。将其用作常规 PyTorch 模块,并参阅 PyTorch 文档以了解与常规用法和行为相关的所有事项。
forward
< source >( pixel_values: FloatTensor = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None ) → transformers.modeling_outputs.BaseModelOutputWithPoolingAndNoAttention
或 tuple(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
, optional) — 是否返回 ModelOutput 而不是普通元组。
返回值
transformers.modeling_outputs.BaseModelOutputWithPoolingAndNoAttention
或 tuple(torch.FloatTensor)
一个 transformers.modeling_outputs.BaseModelOutputWithPoolingAndNoAttention
或 torch.FloatTensor
元组(如果传递了 return_dict=False
或当 config.return_dict=False
时),其中包含各种元素,具体取决于配置 (EfficientNetConfig) 和输入。
-
last_hidden_state (
torch.FloatTensor
of shape(batch_size, num_channels, height, width)
) — 模型最后一层输出的隐藏状态序列。 -
pooler_output (
torch.FloatTensor
of shape(batch_size, hidden_size)
) — 在空间维度上进行池化操作后的最后一层隐藏状态。 -
hidden_states (
tuple(torch.FloatTensor)
, optional, returned whenoutput_hidden_states=True
is passed or whenconfig.output_hidden_states=True
) —torch.FloatTensor
元组(对于嵌入的输出,如果模型具有嵌入层,则为一个;对于每层的输出,则为一个),形状为(batch_size, num_channels, height, width)
。模型在每一层输出的隐藏状态,加上可选的初始嵌入输出。
EfficientNetModel forward 方法,覆盖了 __call__
特殊方法。
尽管 forward 传递的配方需要在该函数内定义,但之后应调用 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 文档以了解所有与通用用法和行为相关的事项。
forward
< 源代码 >( 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.ImageClassifierOutputWithNoAttention 或 tuple(torch.FloatTensor)
参数
- pixel_values (
torch.FloatTensor
,形状为(batch_size, num_channels, height, width)
) — 像素值。像素值可以使用 AutoImageProcessor 获得。 有关详细信息,请参阅AutoImageProcessor.__call__()
。 - output_hidden_states (
bool
, 可选) — 是否返回所有层的隐藏状态。 有关更多详细信息,请参阅返回张量下的hidden_states
。 - return_dict (
bool
, 可选) — 是否返回 ModelOutput 而不是普通的元组。 - labels (
torch.LongTensor
,形状为(batch_size,)
, 可选) — 用于计算图像分类/回归损失的标签。索引应在[0, ..., config.num_labels - 1]
中。如果config.num_labels == 1
,则计算回归损失(均方误差损失),如果config.num_labels > 1
,则计算分类损失(交叉熵损失)。
返回值
transformers.modeling_outputs.ImageClassifierOutputWithNoAttention 或 tuple(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 的 forward 方法,覆盖了 __call__
特殊方法。
尽管 forward 传递的配方需要在该函数内定义,但之后应调用 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