Transformers 文档
MobileNet V1
获得增强的文档体验
开始
MobileNet V1
概览
MobileNet 模型在 MobileNets: Efficient Convolutional Neural Networks for Mobile Vision Applications 论文中提出,作者是 Andrew G. Howard, Menglong Zhu, Bo Chen, Dmitry Kalenichenko, Weijun Wang, Tobias Weyand, Marco Andreetto, Hartwig Adam。
论文摘要如下:
我们提出了一类名为 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 填充行为,请创建一个 `tf_padding = False` 的 MobileNetV1Config。
不支持的功能
MobileNetV1Model 输出的是最后隐藏状态的全局池化版本。在原始模型中,可以使用步幅为 2 的 7x7 平均池化层来代替全局池化。对于较大的输入,这会产生大于 1x1 像素的池化输出。HuggingFace 实现不支持此功能。
目前无法指定 `output_stride`。对于较小的输出步幅,原始模型会调用空洞卷积以防止空间分辨率进一步降低。HuggingFace 模型的输出步幅始终为 32。
原始 TensorFlow 检查点包含量化模型。我们不支持这些模型,因为它们包含额外的“FakeQuantization”操作来反量化权重。
通常的做法是从索引为 5、11、12、13 的逐点层提取输出以用于下游目的。使用 `output_hidden_states=True` 会返回所有中间层的输出。目前无法将其限制为特定层。
资源
以下是官方 Hugging Face 和社区(标有 🌎)资源的列表,可帮助您开始使用 MobileNetV1。
如果您有兴趣提交资源以包含在此处,请随时打开 Pull Request,我们将对其进行审核!理想情况下,资源应展示一些新内容,而不是重复现有资源。
MobileNetV1Config
class 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
, 可选, 默认为 3) — 输入通道数。 - image_size (
int
, 可选, 默认为 224) — 每张图片的大小(分辨率)。 - depth_multiplier (
float
, 可选, 默认为 1.0) — 缩小或扩大每一层中的通道数。默认为 1.0,网络以 32 个通道开始。有时也称为“alpha”或“宽度乘数”。 - min_depth (
int
, 可选, 默认为 8) — 所有层将至少具有这么多通道。 - hidden_act (
str
或function
, 可选, 默认为"relu6"
) — Transformer 编码器和卷积层中的非线性激活函数(函数或字符串)。 - tf_padding (
bool
, 可选, 默认为True
) — 是否在卷积层上使用 TensorFlow 填充规则。 - classifier_dropout_prob (
float
, 可选, 默认为 0.999) — 附加分类器的 dropout 比率。 - initializer_range (
float
, 可选, 默认为 0.02) — 用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。 - layer_norm_eps (
float
, 可选, 默认为 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
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: 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] = <ChannelDimension.FIRST: 'channels_first'> input_data_format: typing.Union[transformers.image_utils.ChannelDimension, str, NoneType] = None )
参数
- images (
ImageInput
) — 要预处理的图像。 期望是像素值范围为 0 到 255 的单张或多张图像。 如果传入像素值在 0 到 1 之间的图像,请设置do_rescale=False
。 - do_resize (
bool
, *可选的*, 默认为self.do_resize
) — 是否调整图像大小。 - size (
Dict[str, int]
, *可选的*, 默认为self.size
) — 调整大小后图像的尺寸。 图像的最短边将调整为 size[“shortest_edge”],最长边会调整以保持输入的长宽比。 - resample (
PILImageResampling
过滤器, *可选的*, 默认为self.resample
) — 如果调整图像大小,则使用的PILImageResampling
过滤器,例如PILImageResampling.BILINEAR
。 仅在do_resize
设置为True
时有效。 - do_center_crop (
bool
, *可选的*, 默认为self.do_center_crop
) — 是否对图像进行中心裁剪。 - crop_size (
Dict[str, int]
, *可选的*, 默认为self.crop_size
) — 中心裁剪的尺寸。 仅在do_center_crop
设置为True
时有效。 - do_rescale (
bool
, *可选的*, 默认为self.do_rescale
) — 是否将图像值重新缩放到 [0 - 1] 之间。 - rescale_factor (
float
, *可选的*, 默认为self.rescale_factor
) — 如果do_rescale
设置为True
,则用于重新缩放图像的重新缩放因子。 - do_normalize (
bool
, *可选的*, 默认为self.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
, *可选的*) — 返回的张量类型。 可以是以下之一:- Unset: 返回
np.ndarray
列表。 TensorType.TENSORFLOW
或'tf'
: 返回tf.Tensor
类型的批次。TensorType.PYTORCH
或'pt'
: 返回torch.Tensor
类型的批次。TensorType.NUMPY
或'np'
: 返回np.ndarray
类型的批次。TensorType.JAX
或'jax'
: 返回jax.numpy.ndarray
类型的批次。
- Unset: 返回
- data_format (
ChannelDimension
或str
, *可选的*, 默认为ChannelDimension.FIRST
) — 输出图像的通道维度格式。 可以是以下之一:"channels_first"
或ChannelDimension.FIRST
: (num_channels, height, width) 格式的图像。"channels_last"
或ChannelDimension.LAST
: (height, width, num_channels) 格式的图像。- Unset: 使用输入图像的通道维度格式。
- 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
class transformers.MobileNetV1ImageProcessor
< source >( do_resize: bool = True size: typing.Optional[typing.Dict[str, int]] = None resample: Resampling = <Resampling.BILINEAR: 2> do_center_crop: bool = True crop_size: typing.Dict[str, int] = None do_rescale: bool = True rescale_factor: typing.Union[int, float] = 0.00392156862745098 do_normalize: bool = True image_mean: typing.Union[float, typing.List[float], NoneType] = None image_std: typing.Union[float, typing.List[float], NoneType] = None **kwargs )
参数
- 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]
, 可选, 默认为{"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 图像处理器。
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: 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] = <ChannelDimension.FIRST: 'channels_first'> input_data_format: typing.Union[transformers.image_utils.ChannelDimension, str, NoneType] = None )
参数
- images (
ImageInput
) — 要预处理的图像。 接受像素值范围为 0 到 255 的单个或批量图像。如果传入像素值在 0 到 1 之间的图像,请设置do_rescale=False
。 - do_resize (
bool
, 可选, 默认为self.do_resize
) — 是否调整图像大小。 - size (
Dict[str, int]
, 可选, 默认为self.size
) — 调整大小后图像的尺寸。图像的最短边调整为 size[“shortest_edge”],最长边调整为保持输入宽高比。 - resample (
PILImageResampling
过滤器, 可选, 默认为self.resample
) — 如果调整图像大小,则使用的PILImageResampling
过滤器,例如PILImageResampling.BILINEAR
。仅在do_resize
设置为True
时生效。 - do_center_crop (
bool
, 可选, 默认为self.do_center_crop
) — 是否对图像进行中心裁剪。 - crop_size (
Dict[str, int]
, 可选, 默认为self.crop_size
) — 中心裁剪的大小。仅在do_center_crop
设置为True
时生效。 - do_rescale (
bool
, 可选, 默认为self.do_rescale
) — 是否将图像值重新缩放到 [0 - 1] 之间。 - rescale_factor (
float
, 可选, 默认为self.rescale_factor
) — 如果do_rescale
设置为True
,则用于重新缩放图像的缩放因子。 - do_normalize (
bool
, 可选, 默认为self.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
, 可选) — 返回张量的类型。可以是以下之一:- Unset: 返回
np.ndarray
列表。 TensorType.TENSORFLOW
或'tf'
: 返回tf.Tensor
类型的批次。TensorType.PYTORCH
或'pt'
: 返回torch.Tensor
类型的批次。TensorType.NUMPY
或'np'
: 返回np.ndarray
类型的批次。TensorType.JAX
或'jax'
: 返回jax.numpy.ndarray
类型的批次。
- Unset: 返回
- data_format (
ChannelDimension
或str
, 可选, 默认为ChannelDimension.FIRST
) — 输出图像的通道维度格式。可以是以下之一:"channels_first"
或ChannelDimension.FIRST
: 图像格式为 (num_channels, height, width)。"channels_last"
或ChannelDimension.LAST
: 图像格式为 (height, width, num_channels)。- Unset: 使用输入图像的通道维度格式。
- 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
class transformers.MobileNetV1Model
< source >( config: MobileNetV1Config add_pooling_layer: bool = True )
参数
- config (MobileNetV1Config) — 带有模型所有参数的模型配置类。使用配置文件初始化不会加载与模型相关的权重,仅加载配置。查看 from_pretrained() 方法来加载模型权重。
不带任何特定头部,输出原始隐藏状态的裸 MobileNetV1 模型。此模型是 PyTorch torch.nn.Module 子类。 可将其用作常规 PyTorch 模块,并参阅 PyTorch 文档以了解所有与常规用法和行为相关的事项。
forward
< 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
,形状为(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
class transformers.MobileNetV1ForImageClassification
< source >( config: MobileNetV1Config )
参数
- config (MobileNetV1Config) — 带有模型所有参数的模型配置类。 使用配置文件初始化不会加载与模型关联的权重,仅加载配置。 查看 from_pretrained() 方法以加载模型权重。
带有图像分类头(池化特征之上的线性层)的 MobileNetV1 模型,例如用于 ImageNet。
此模型是 PyTorch torch.nn.Module 子类。 将其用作常规 PyTorch 模块,并参阅 PyTorch 文档以了解所有与常规用法和行为相关的事项。
forward
< 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
,形状为(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