MobileNet V1
概述
MobileNet模型由Andrew G. Howard、Menglong Zhu、Bo Chen、Dmitry Kalenichenko、Weijun Wang、Tobias Weyand、Marco Andreetto和Hartwig Adam在MobileNets: Efficient Convolutional Neural Networks for Mobile Vision Applications中提出。
论文的摘要如下:
我们提出了一类名为MobileNets的高效模型,适用于移动和嵌入式视觉应用。MobileNets基于一种简化的架构,使用深度可分离卷积来构建轻量级深度神经网络。我们引入了两个简单的全局超参数,有效地在延迟和准确性之间进行权衡。这些超参数允许模型构建者根据问题的约束选择适合其应用的模型大小。我们展示了在资源和准确性权衡方面的广泛实验,并与其他流行模型在ImageNet分类上的表现进行了比较,显示出强大的性能。然后,我们展示了MobileNets在包括目标检测、细粒度分类、面部属性和大规模地理定位在内的广泛应用和用例中的有效性。
该模型由matthijs贡献。原始代码和权重可以在这里找到。
使用提示
检查点被命名为mobilenet_v1_depth_size,例如mobilenet_v1_1.0_224,其中1.0是深度乘数(有时也称为“alpha”或宽度乘数),224是模型训练时输入图像的分辨率。
尽管检查点是在特定大小的图像上训练的,但该模型将适用于任何大小的图像。支持的最小图像大小为32x32。
可以使用MobileNetV1ImageProcessor来为模型准备图像。
可用的图像分类检查点是在ImageNet-1k(也称为ILSVRC 2012,包含130万张图像和1000个类别)上预训练的。然而,模型预测1001个类别:来自ImageNet的1000个类别加上一个额外的“背景”类别(索引0)。
原始的TensorFlow检查点使用与PyTorch不同的填充规则,要求模型在推理时确定填充量,因为这取决于输入图像的大小。要使用原生的PyTorch填充行为,请创建一个MobileNetV1Config,并设置
tf_padding = False
。
不支持的功能:
MobileNetV1Model 输出最后一个隐藏状态的全局池化版本。在原始模型中,可以使用步幅为2的7x7平均池化层来代替全局池化。对于较大的输入,这将产生大于1x1像素的池化输出。HuggingFace的实现不支持这一点。
目前无法指定
output_stride
。对于较小的输出步幅,原始模型会调用扩张卷积以防止空间分辨率进一步降低。HuggingFace模型的输出步幅始终为32。原始的TensorFlow检查点包括量化模型。我们不支持这些模型,因为它们包含额外的“FakeQuantization”操作来反量化权重。
通常为了下游目的,会从点积层中提取索引为5、11、12、13的输出。使用
output_hidden_states=True
会返回所有中间层的输出。目前没有办法将其限制在特定的层。
资源
一份官方的Hugging Face和社区(由🌎表示)资源列表,帮助您开始使用MobileNetV1。
- MobileNetV1ForImageClassification 由这个 示例脚本 和 笔记本 支持。
- 另请参阅:图像分类任务指南
如果您有兴趣提交资源以包含在此处,请随时打开一个 Pull Request,我们将进行审核!理想情况下,资源应展示一些新内容,而不是重复现有资源。
MobileNetV1Config
类 transformers.MobileNetV1Config
< source >( num_channels = 3 image_size = 224 depth_multiplier = 1.0 min_depth = 8 hidden_act = 'relu6' tf_padding = True classifier_dropout_prob = 0.999 initializer_range = 0.02 layer_norm_eps = 0.001 **kwargs )
参数
- num_channels (
int
, optional, defaults to 3) — 输入通道的数量。 - image_size (
int
, optional, 默认为 224) — 每张图片的大小(分辨率)。 - depth_multiplier (
float
, 可选, 默认为 1.0) — 缩小或扩展每层中的通道数。默认值为 1.0,这意味着网络从 32 个通道开始。这有时也被称为“alpha”或“宽度乘数”。 - min_depth (
int
, optional, defaults to 8) — 所有层将至少有这么多通道。 - hidden_act (
str
或function
, 可选, 默认为"relu6"
) — Transformer编码器和卷积层中的非线性激活函数(函数或字符串)。 - tf_padding (
bool
, 可选, 默认为True
) — 是否在卷积层上使用TensorFlow的填充规则。 - classifier_dropout_prob (
float
, optional, defaults to 0.999) — 附加分类器的丢弃比例。 - initializer_range (
float
, optional, 默认为 0.02) — 用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。 - layer_norm_eps (
float
, optional, defaults to 0.001) — 层归一化层使用的epsilon值。
这是用于存储MobileNetV1Model配置的配置类。它用于根据指定的参数实例化一个MobileNetV1模型,定义模型架构。使用默认值实例化配置将产生与MobileNetV1 google/mobilenet_v1_1.0_224架构类似的配置。
配置对象继承自PretrainedConfig,可用于控制模型输出。阅读PretrainedConfig的文档以获取更多信息。
示例:
>>> from transformers import MobileNetV1Config, MobileNetV1Model
>>> # Initializing a "mobilenet_v1_1.0_224" style configuration
>>> configuration = MobileNetV1Config()
>>> # Initializing a model from the "mobilenet_v1_1.0_224" style configuration
>>> model = MobileNetV1Model(configuration)
>>> # Accessing the model configuration
>>> configuration = model.config
MobileNetV1FeatureExtractor
预处理
< source >( 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: typing.Optional[bool] = None size: typing.Dict[str, int] = None resample: Resampling = None do_center_crop: bool = None crop_size: typing.Dict[str, int] = None do_rescale: typing.Optional[bool] = None rescale_factor: typing.Optional[float] = None do_normalize: typing.Optional[bool] = None image_mean: typing.Union[float, typing.List[float], NoneType] = None image_std: typing.Union[float, typing.List[float], NoneType] = None return_tensors: typing.Union[str, transformers.utils.generic.TensorType, NoneType] = None data_format: typing.Union[str, transformers.image_utils.ChannelDimension] =
参数
- 图像 (
ImageInput
) — 要预处理的图像。期望输入单个或批量的图像,像素值范围在0到255之间。如果传入的图像像素值在0到1之间,请设置do_rescale=False
. - do_resize (
bool
, optional, defaults toself.do_resize
) — 是否调整图像大小. - size (
Dict[str, int]
, 可选, 默认为self.size
) — 调整大小后图像的尺寸。图像的最短边调整为size[“shortest_edge”],最长边调整以保持输入的宽高比。 - resample (
PILImageResampling
filter, optional, defaults toself.resample
) —PILImageResampling
过滤器用于调整图像大小,例如PILImageResampling.BILINEAR
。仅在do_resize
设置为True
时有效。 - do_center_crop (
bool
, optional, defaults toself.do_center_crop
) — 是否对图像进行中心裁剪. - crop_size (
Dict[str, int]
, 可选, 默认为self.crop_size
) — 中心裁剪的大小。仅在do_center_crop
设置为True
时有效。 - do_rescale (
bool
, optional, defaults toself.do_rescale
) — 是否将图像值缩放到 [0 - 1] 之间。 - rescale_factor (
float
, optional, defaults toself.rescale_factor
) — 如果do_rescale
设置为True
,则用于重新缩放图像的重新缩放因子。 - do_normalize (
bool
, optional, defaults toself.do_normalize
) — 是否对图像进行归一化处理。 - image_mean (
float
或List[float]
, 可选, 默认为self.image_mean
) — 如果do_normalize
设置为True
,则使用的图像均值。 - image_std (
float
或List[float]
, 可选, 默认为self.image_std
) — 如果do_normalize
设置为True
,则使用的图像标准差。 - return_tensors (
str
或TensorType
, 可选) — 返回的张量类型。可以是以下之一:- 未设置:返回一个
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
或str
, 可选, 默认为ChannelDimension.FIRST
) — 输出图像的通道维度格式。可以是以下之一:"channels_first"
或ChannelDimension.FIRST
: 图像格式为 (num_channels, height, width)。"channels_last"
或ChannelDimension.LAST
: 图像格式为 (height, width, num_channels)。- 未设置:使用输入图像的通道维度格式。
- input_data_format (
ChannelDimension
或str
, 可选) — 输入图像的通道维度格式。如果未设置,则从输入图像推断通道维度格式。可以是以下之一:"channels_first"
或ChannelDimension.FIRST
: 图像格式为 (num_channels, height, width)。"channels_last"
或ChannelDimension.LAST
: 图像格式为 (height, width, num_channels)。"none"
或ChannelDimension.NONE
: 图像格式为 (height, width)。
预处理一张图像或一批图像。
MobileNetV1ImageProcessor
类 transformers.MobileNetV1ImageProcessor
< source >( do_resize: bool = True size: typing.Optional[typing.Dict[str, int]] = None resample: Resampling =
参数
- do_resize (
bool
, 可选, 默认为True
) — 是否将图像的(高度,宽度)尺寸调整为指定的size
。可以在preprocess
方法中被do_resize
覆盖。 - size (
Dict[str, int]
可选, 默认为{"shortest_edge" -- 256}
): 调整大小后的图像尺寸。图像的短边将调整为size[“shortest_edge”],长边将调整以保持输入的宽高比。可以在preprocess
方法中通过size
覆盖此设置。 - resample (
PILImageResampling
, 可选, 默认为PILImageResampling.BILINEAR
) — 如果调整图像大小,则使用的重采样过滤器。可以在preprocess
方法中通过resample
参数覆盖。 - do_center_crop (
bool
, 可选, 默认为True
) — 是否对图像进行中心裁剪。如果输入尺寸在任何一边小于crop_size
,图像将用0填充,然后进行中心裁剪。可以通过preprocess
方法中的do_center_crop
参数进行覆盖。 - crop_size (
Dict[str, int]
, optional, defaults to{"height" -- 224, "width": 224}
): 应用中心裁剪时的期望输出大小。仅在do_center_crop
设置为True
时有效。 可以通过preprocess
方法中的crop_size
参数进行覆盖。 - do_rescale (
bool
, 可选, 默认为True
) — 是否通过指定的比例rescale_factor
来重新缩放图像。可以在preprocess
方法中通过do_rescale
参数进行覆盖。 - rescale_factor (
int
或float
, 可选, 默认为1/255
) — 如果重新缩放图像,则使用的缩放因子。可以在preprocess
方法中通过rescale_factor
参数覆盖此值。 - do_normalize —
是否对图像进行归一化。可以在
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
参数进行覆盖。
构建一个MobileNetV1图像处理器。
预处理
< source >( 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: typing.Optional[bool] = None size: typing.Dict[str, int] = None resample: Resampling = None do_center_crop: bool = None crop_size: typing.Dict[str, int] = None do_rescale: typing.Optional[bool] = None rescale_factor: typing.Optional[float] = None do_normalize: typing.Optional[bool] = None image_mean: typing.Union[float, typing.List[float], NoneType] = None image_std: typing.Union[float, typing.List[float], NoneType] = None return_tensors: typing.Union[str, transformers.utils.generic.TensorType, NoneType] = None data_format: typing.Union[str, transformers.image_utils.ChannelDimension] =
参数
- 图像 (
ImageInput
) — 要预处理的图像。期望输入单个或批量的图像,像素值范围在0到255之间。如果传入的图像像素值在0到1之间,请设置do_rescale=False
. - do_resize (
bool
, optional, defaults toself.do_resize
) — 是否调整图像大小. - size (
Dict[str, int]
, 可选, 默认为self.size
) — 调整大小后的图像尺寸。图像的最短边将调整为size[“shortest_edge”],最长边将调整以保持输入的宽高比。 - resample (
PILImageResampling
filter, optional, defaults toself.resample
) —PILImageResampling
过滤器用于调整图像大小,例如PILImageResampling.BILINEAR
。仅在do_resize
设置为True
时有效。 - do_center_crop (
bool
, optional, defaults toself.do_center_crop
) — 是否对图像进行中心裁剪。 - crop_size (
Dict[str, int]
, 可选, 默认为self.crop_size
) — 中心裁剪的大小。仅在do_center_crop
设置为True
时有效。 - do_rescale (
bool
, optional, defaults toself.do_rescale
) — 是否将图像值缩放到 [0 - 1] 之间。 - rescale_factor (
float
, 可选, 默认为self.rescale_factor
) — 如果do_rescale
设置为True
,则用于重新缩放图像的重新缩放因子。 - do_normalize (
bool
, optional, defaults toself.do_normalize
) — 是否对图像进行归一化处理。 - image_mean (
float
或List[float]
, 可选, 默认为self.image_mean
) — 如果do_normalize
设置为True
,则使用的图像均值。 - image_std (
float
或List[float]
, 可选, 默认为self.image_std
) — 如果do_normalize
设置为True
,则使用的图像标准差。 - return_tensors (
str
或TensorType
, 可选) — 返回的张量类型。可以是以下之一:- 未设置:返回一个
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
或str
, 可选, 默认为ChannelDimension.FIRST
) — 输出图像的通道维度格式。可以是以下之一:"channels_first"
或ChannelDimension.FIRST
: 图像格式为 (num_channels, height, width)。"channels_last"
或ChannelDimension.LAST
: 图像格式为 (height, width, num_channels)。- 未设置:使用输入图像的通道维度格式。
- input_data_format (
ChannelDimension
或str
, 可选) — 输入图像的通道维度格式。如果未设置,则从输入图像推断通道维度格式。可以是以下之一:"channels_first"
或ChannelDimension.FIRST
: 图像格式为 (num_channels, height, width)。"channels_last"
或ChannelDimension.LAST
: 图像格式为 (height, width, num_channels)。"none"
或ChannelDimension.NONE
: 图像格式为 (height, width)。
预处理一张图像或一批图像。
MobileNetV1Model
类 transformers.MobileNetV1Model
< source >( config: MobileNetV1Config add_pooling_layer: bool = True )
参数
- config (MobileNetV1Config) — 包含模型所有参数的模型配置类。 使用配置文件初始化不会加载与模型相关的权重,只会加载配置。查看 from_pretrained() 方法以加载模型权重。
裸的MobileNetV1模型输出原始隐藏状态,没有任何特定的头部。 这个模型是PyTorch torch.nn.Module 的子类。将其用作常规的PyTorch模块,并参考PyTorch文档以获取与一般使用和行为相关的所有信息。
前进
< source >( pixel_values: typing.Optional[torch.Tensor] = 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获取。详情请参见 MobileNetV1ImageProcessor.call(). - output_hidden_states (
bool
, 可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回张量下的hidden_states
。 - return_dict (
bool
, 可选) — 是否返回一个 ModelOutput 而不是一个普通的元组。
返回
transformers.modeling_outputs.BaseModelOutputWithPoolingAndNoAttention
或 tuple(torch.FloatTensor)
一个 transformers.modeling_outputs.BaseModelOutputWithPoolingAndNoAttention
或一个由
torch.FloatTensor
组成的元组(如果传递了 return_dict=False
或当 config.return_dict=False
时),包含各种
元素,具体取决于配置(MobileNetV1Config)和输入。
-
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=True
或当config.output_hidden_states=True
时返回) — 由torch.FloatTensor
组成的元组(一个用于嵌入层的输出,如果模型有嵌入层,+ 一个用于每一层的输出)形状为(batch_size, num_channels, height, width)
。模型在每一层输出处的隐藏状态加上可选的初始嵌入输出。
MobileNetV1Model 的前向方法,重写了 __call__
特殊方法。
尽管前向传递的配方需要在此函数内定义,但之后应该调用Module
实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。
示例:
>>> from transformers import AutoImageProcessor, MobileNetV1Model
>>> 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/mobilenet_v1_1.0_224")
>>> model = MobileNetV1Model.from_pretrained("google/mobilenet_v1_1.0_224")
>>> 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, 1024, 7, 7]
MobileNetV1ForImageClassification
类 transformers.MobileNetV1ForImageClassification
< source >( config: MobileNetV1Config )
参数
- config (MobileNetV1Config) — 包含模型所有参数的模型配置类。 使用配置文件初始化不会加载与模型相关的权重,只会加载配置。查看 from_pretrained() 方法以加载模型权重。
MobileNetV1模型,顶部带有图像分类头(在池化特征之上的线性层),例如用于ImageNet。
该模型是一个PyTorch torch.nn.Module 子类。将其用作常规的PyTorch模块,并参考PyTorch文档以获取与一般使用和行为相关的所有信息。
前进
< source >( pixel_values: typing.Optional[torch.Tensor] = None output_hidden_states: typing.Optional[bool] = None labels: typing.Optional[torch.Tensor] = None return_dict: typing.Optional[bool] = None ) → transformers.modeling_outputs.ImageClassifierOutputWithNoAttention 或 tuple(torch.FloatTensor)
参数
- pixel_values (
torch.FloatTensor
of shape(batch_size, num_channels, height, width)
) — 像素值。像素值可以使用AutoImageProcessor获取。详情请参见 MobileNetV1ImageProcessor.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
时),包含各种
元素,具体取决于配置(MobileNetV1Config)和输入。
- 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)
。模型在每个阶段输出的隐藏状态(也称为特征图)。
MobileNetV1ForImageClassification 的前向方法,重写了 __call__
特殊方法。
尽管前向传递的配方需要在此函数内定义,但之后应该调用Module
实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。
示例:
>>> from transformers import AutoImageProcessor, MobileNetV1ForImageClassification
>>> 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/mobilenet_v1_1.0_224")
>>> model = MobileNetV1ForImageClassification.from_pretrained("google/mobilenet_v1_1.0_224")
>>> 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