Transformers 文档

MobileNet V1

Hugging Face's logo
加入 Hugging Face 社区

并获得增强的文档体验

开始使用

该模型于 2017-04-17 在 HF 论文中发布,并于 2022-11-21 贡献给 Hugging Face Transformers。

PyTorch

MobileNet V1

MobileNet V1 是一系列专为端侧或嵌入式视觉任务优化的高效卷积神经网络。它通过使用深度可分离卷积(depth-wise separable convolutions)代替标准卷积来实现这种高效性。该架构允许通过两个主要超参数——宽度倍增器(alpha)和图像分辨率倍增器,在延迟和准确度之间轻松进行权衡。

你可以在 Google 组织下找到所有原始的 MobileNet 检查点。

点击右侧侧边栏中的 MobileNet V1 模型,查看如何将 MobileNet 应用于不同视觉任务的更多示例。

下面的示例演示了如何使用 PipelineAutoModel 类来对图像进行分类。

流水线
自动模型
from transformers import pipeline


pipeline = pipeline(
    task="image-classification",
    model="google/mobilenet_v1_1.0_224",
    device=0
)
pipeline("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg")

注意事项

  • 检查点名称遵循 mobilenet_v1_{depth_multiplier}_{resolution} 模式,例如 mobilenet_v1_1.0_224。其中 1.0 是深度倍增器,224 是图像分辨率。

  • 虽然模型是在特定尺寸的图像上训练的,但其架构支持不同尺寸的图像(最小为 32x32)。MobileNetV1ImageProcessor 负责处理必要的预处理。

  • MobileNet 在包含 1000 个类别的 ImageNet-1k 数据集上进行预训练。然而,该模型实际上预测 1001 个类别。多出的一个类别是额外的“背景”类(索引为 0)。

  • 原始的 TensorFlow 检查点在推理时确定填充(padding)量,因为这取决于输入图像的尺寸。要使用原生 PyTorch 的填充行为,请在 MobileNetV1Config 中设置 tf_padding=False

    from transformers import MobileNetV1Config
    
    config = MobileNetV1Config.from_pretrained("google/mobilenet_v1_1.0_224", tf_padding=True)
  • Transformers 实现不支持以下特性。

    • 使用全局平均池化,而非可选的步长为 2 的 7x7 平均池化。对于较大的输入,这会产生大于 1x1 像素的池化输出。
    • 不支持其他 output_stride 值(固定为 32)。对于更小的 output_strides,原始实现使用扩张卷积(dilated convolution)来防止空间分辨率进一步降低(这需要扩张卷积支持)。
    • output_hidden_states=True 会返回所有中间隐藏状态。无法为了其他下游用途而专门提取特定层的输出。
    • 不包括原始检查点中的量化模型,因为它们包含用于对权重进行反量化的“FakeQuantization”(伪量化)操作。

MobileNetV1Config

class transformers.MobileNetV1Config

< >

( transformers_version: str | None = None architectures: list[str] | None = None output_hidden_states: bool | None = False return_dict: bool | None = True dtype: typing.Union[str, ForwardRef('torch.dtype'), NoneType] = None chunk_size_feed_forward: int = 0 is_encoder_decoder: bool = False id2label: dict[int, str] | dict[str, str] | None = None label2id: dict[str, int] | dict[str, str] | None = None problem_type: typing.Optional[typing.Literal['regression', 'single_label_classification', 'multi_label_classification']] = None num_channels: int = 3 image_size: int | list[int] | tuple[int, int] = 224 depth_multiplier: float | int = 1.0 min_depth: int = 8 hidden_act: str = 'relu6' tf_padding: bool = True classifier_dropout_prob: float | int = 0.999 initializer_range: float = 0.02 layer_norm_eps: float = 0.001 )

参数

  • num_channels (int, 可选, 默认为 3) — 输入通道的数量。
  • image_size (Union[int, list[int], tuple[int, int]], 可选, 默认为 224) — 每张图像的大小(分辨率)。
  • depth_multiplier (Union[float, int], 可选, 默认为 1.0) — 缩小或扩大每一层的通道数。这有时也称为“alpha”或“宽度倍增器”。
  • min_depth (int, 可选, 默认为 8) — 所有层将至少具有这么多通道。
  • hidden_act (str, 可选, 默认为 relu6) — 解码器中的非线性激活函数(函数或字符串)。例如,"gelu", "relu", "silu" 等。
  • tf_padding (bool, 可选, 默认为 True) — 是否在卷积层上使用 TensorFlow 填充规则。
  • classifier_dropout_prob (Union[float, int], 可选, 默认为 0.999) — 分类器的丢弃(dropout)比例。
  • initializer_range (float, 可选, 默认为 0.02) — 用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。
  • layer_norm_eps (float, 可选, 默认为 0.001) — 层归一化(layer normalization)层使用的 epsilon 值。

这是用于存储 MobileNetV1Model 配置的配置类。它用于根据指定的参数实例化 MobileNet V1 模型,定义模型架构。使用默认参数实例化配置将产生与 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

MobileNetV1ImageProcessor

class transformers.MobileNetV1ImageProcessor

< >

( **kwargs: typing_extensions.Unpack[transformers.processing_utils.ImagesKwargs] )

参数

  • **kwargs (ImagesKwargs, 可选) — 额外的图像预处理选项。上面列出了模型特定的关键字参数;完整支持的参数列表请参见 TypedDict 类。

构造一个 MobileNetV1 图像处理器。

preprocess

< >

( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']] *args **kwargs: typing_extensions.Unpack[transformers.processing_utils.ImagesKwargs] ) ~image_processing_base.BatchFeature

参数

  • images (Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]]) — 待预处理的图像。期望单张或一批像素值在 0 到 255 之间的图像。如果传入像素值在 0 到 1 之间的图像,请设置 do_rescale=False
  • return_tensors (strTensorType, 可选) — 如果设置为 'pt',则返回堆叠的张量,否则返回张量列表。
  • **kwargs (ImagesKwargs, 可选) — 额外的图像预处理选项。上面列出了模型特定的关键字参数;完整支持的参数列表请参见 TypedDict 类。

返回

~image_processing_base.BatchFeature

  • data (dict) — 由 call 方法返回的列表/数组/张量字典(“pixel_values”等)。
  • tensor_type (Union[None, str, TensorType], optional) — 您可以在此处提供 tensor_type 以在初始化时将整数列表转换为 PyTorch/Numpy 张量。

MobileNetV1ImageProcessorPil

class transformers.MobileNetV1ImageProcessorPil

< >

( **kwargs: typing_extensions.Unpack[transformers.processing_utils.ImagesKwargs] )

参数

  • **kwargs (ImagesKwargs, 可选) — 额外的图像预处理选项。上面列出了模型特定的关键字参数;完整支持的参数列表请参见 TypedDict 类。

构造一个 MobileNetV1 图像处理器。

preprocess

< >

( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']] *args **kwargs: typing_extensions.Unpack[transformers.processing_utils.ImagesKwargs] ) ~image_processing_base.BatchFeature

参数

  • images (Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]]) — 待预处理的图像。期望单张或一批像素值在 0 到 255 之间的图像。如果传入像素值在 0 到 1 之间的图像,请设置 do_rescale=False
  • return_tensors (strTensorType, 可选) — 如果设置为 'pt',则返回堆叠的张量,否则返回张量列表。
  • **kwargs (ImagesKwargs, 可选) — 额外的图像预处理选项。上面列出了模型特定的关键字参数;完整支持的参数列表请参见 TypedDict 类。

返回

~image_processing_base.BatchFeature

  • data (dict) — 由 call 方法返回的列表/数组/张量字典(“pixel_values”等)。
  • tensor_type (Union[None, str, TensorType], optional) — 您可以在此处提供 tensor_type 以在初始化时将整数列表转换为 PyTorch/Numpy 张量。

MobileNetV1Model

class transformers.MobileNetV1Model

< >

( config: MobileNetV1Config add_pooling_layer: bool = True )

参数

  • config (MobileNetV1Config) — 包含模型所有参数的模型配置类。使用配置文件进行初始化不会加载与模型相关的权重,只加载配置。请查看 from_pretrained() 方法来加载模型权重。
  • add_pooling_layer (bool, 可选, 默认为 True) — 是否添加池化层。

基础 MobileNet V1 模型,输出原始隐藏状态,顶部没有任何特定头结构。

该模型继承自 PreTrainedModel。请查看超类文档以了解该库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、剪枝头部等)。

此模型也是一个 PyTorch torch.nn.Module 子类。像普通的 PyTorch Module 一样使用它,并参考 PyTorch 文档了解一般用法和行为的所有相关信息。

forward

< >

( pixel_values: torch.Tensor | None = None output_hidden_states: bool | None = None return_dict: bool | None = None **kwargs ) BaseModelOutputWithPoolingAndNoAttentiontuple(torch.FloatTensor)

参数

  • pixel_values (形状为 (batch_size, num_channels, image_size, image_size)torch.Tensor, 可选) — 对应于输入图像的张量。像素值可以使用 MobileNetV1ImageProcessor 获取。详见 MobileNetV1ImageProcessor.__call__()processor_class 使用 MobileNetV1ImageProcessor 进行图像处理)。
  • output_hidden_states (bool, 可选) — 是否返回所有层的隐藏状态。详见返回张量下的 hidden_states
  • return_dict (bool, 可选) — 是否返回 ModelOutput 而非普通元组。

返回

BaseModelOutputWithPoolingAndNoAttentiontuple(torch.FloatTensor)

一个 BaseModelOutputWithPoolingAndNoAttentiontorch.FloatTensor 元组(如果传递了 return_dict=Falseconfig.return_dict=False),取决于配置 (MobileNetV1Config) 和输入,包含各种元素。

MobileNetV1Model 的前向传播(forward)方法,重写了 __call__ 特殊方法。

虽然 forward pass 的实现需要在此函数中定义,但你应该在之后调用 Module 实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会静默地忽略它们。

  • last_hidden_state (torch.FloatTensor, 形状为 (batch_size, num_channels, height, width)) — 模型最后一层输出的隐藏状态序列。

  • pooler_output (torch.FloatTensor, 形状为 (batch_size, hidden_size)) — 经过空间维度池化操作后的最后一层隐藏状态。

  • hidden_states (tuple(torch.FloatTensor), optional, 当传入 output_hidden_states=Trueconfig.output_hidden_states=True 时返回) — torch.FloatTensor 的元组(如果模型有嵌入层,则包含一个嵌入层输出,加上每层的一个输出),形状为 (batch_size, num_channels, height, width)

    模型在每个层输出的隐藏状态以及可选的初始嵌入输出。

示例

MobileNetV1ForImageClassification

class transformers.MobileNetV1ForImageClassification

< >

( config: MobileNetV1Config )

参数

  • config (MobileNetV1Config) — 包含模型所有参数的模型配置类。使用配置文件进行初始化不会加载与模型相关的权重,只加载配置。请查看 from_pretrained() 方法来加载模型权重。

MobileNetV1 模型,顶部带有一个图像分类头(池化特征之上的一个线性层),例如用于 ImageNet。

该模型继承自 PreTrainedModel。请查看超类文档以了解该库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、剪枝头部等)。

此模型也是一个 PyTorch torch.nn.Module 子类。像普通的 PyTorch Module 一样使用它,并参考 PyTorch 文档了解一般用法和行为的所有相关信息。

forward

< >

( pixel_values: torch.Tensor | None = None output_hidden_states: bool | None = None labels: torch.Tensor | None = None return_dict: bool | None = None **kwargs ) ImageClassifierOutputWithNoAttentiontuple(torch.FloatTensor)

参数

  • pixel_values (形状为 (batch_size, num_channels, image_size, image_size)torch.Tensor, 可选) — 对应于输入图像的张量。像素值可以使用 MobileNetV1ImageProcessor 获取。详见 MobileNetV1ImageProcessor.__call__()processor_class 使用 MobileNetV1ImageProcessor 进行图像处理)。
  • output_hidden_states (bool, 可选) — 是否返回所有层的隐藏状态。详见返回张量下的 hidden_states
  • labels (形状为 (batch_size,)torch.LongTensor, 可选) — 用于计算图像分类/回归损失的标签。索引应在 [0, ..., config.num_labels - 1] 范围内。如果 config.num_labels == 1,则计算回归损失(均方误差损失)。如果 config.num_labels > 1,则计算分类损失(交叉熵损失)。
  • return_dict (bool, 可选) — 是否返回 ModelOutput 而非普通元组。

返回

ImageClassifierOutputWithNoAttentiontuple(torch.FloatTensor)

一个 ImageClassifierOutputWithNoAttentiontorch.FloatTensor 元组(如果传递了 return_dict=Falseconfig.return_dict=False),取决于配置 (MobileNetV1Config) 和输入,包含各种元素。

MobileNetV1ForImageClassification 的前向传播(forward)方法,重写了 __call__ 特殊方法。

虽然 forward pass 的实现需要在此函数中定义,但你应该在之后调用 Module 实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会静默地忽略它们。

  • loss (形状为 (1,)torch.FloatTensor可选,当提供 labels 时返回) — 分类损失(如果 config.num_labels==1,则为回归损失)。
  • logits (形状为 (batch_size, config.num_labels)torch.FloatTensor) — 分类(如果 config.num_labels==1,则为回归)分数(SoftMax 之前)。
  • hidden_states (tuple(torch.FloatTensor), optional, 当传入 output_hidden_states=Trueconfig.output_hidden_states=True 时返回) — torch.FloatTensor 的元组(如果模型有嵌入层,则包含一个嵌入层输出,加上每阶段的一个输出),形状为 (batch_size, num_channels, height, width)。模型在每个阶段输出的隐藏状态(也称为特征图)。

示例

>>> from transformers import AutoImageProcessor, MobileNetV1ForImageClassification
>>> import torch
>>> from datasets import load_dataset

>>> dataset = load_dataset("huggingface/cats-image")
>>> 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])
...
在 GitHub 上更新

© . This site is unofficial and not affiliated with Hugging Face, Inc.