资讯动态

Hugging Face Transformers 中的 MobileNet V1:深度可分离卷积、配置细节与图像分类实战

发布时间:2026/9/8 18:45:43 来源:尧图企业网站定制
Hugging Face Transformers 中的 MobileNet V1深度可分离卷积、配置细节与图像分类实战【免费下载链接】transformers Transformers: the model-definition framework for state-of-the-art machine learning models in text, vision, audio, and multimodal models, for both inference and training.项目地址: https://gitcode.com/GitHub_Trending/tra/transformers导读本文围绕 Transformers 仓库中mobilenet_v1模型的官方文档见 docs/source/en/model_doc/mobilenet_v1.md展开系统讲解 MobileNet V1 这一面向移动端与嵌入式视觉任务的高效卷积网络在 Transformers 中的实现与用法。读完本文你将掌握用pipeline与AutoModelForImageClassification两种方式完成图像分类推理理解 checkpoint 命名规则、tf_padding、depth_multiplier等核心配置的作用了解该实现与原始 TensorFlow 版本在行为上的差异与限制。什么是 MobileNet V1MobileNet V1 是一个专为端侧on-device或嵌入式视觉任务设计的高效卷积神经网络家族。它通过引入**深度可分离卷积depth-wise separable convolution**来替代标准卷积大幅削减计算量与参数量是移动端图像分类的经典轻量化主干网络之一。它的高效性体现在两个可调超参数上宽度乘子width multiplier记为alpha以系数方式整体缩放每一层的通道数图像分辨率乘子image resolution multiplier通过改变输入分辨率来平衡延迟与精度。从源码看Transformers 的 PyTorch 实现modeling_mobilenet_v1.py完整保留了这一设计每个MobileNetV1ConvLayer由Conv2d BatchNorm2d 激活组成modeling_mobilenet_v1.py网络体按深度卷积depthwisegroupsin_channels→ 1×1 逐点卷积pointwise的配对方式堆叠 13 个块共 26 层卷积modeling_mobilenet_v1.py默认激活函数为relu6与 MobileNet 原论文一致特征图在主干网络中总共下采样 32 倍对应配置测试中的output_stride32见 tests/models/mobilenet_v1/test_modeling_mobilenet_v1.py。该模型于 2022-11-21 由社区贡献进入 TransformersPyTorch 是其支持的框架。仓库还提供从原始 TensorFlow checkpoint 转换到 PyTorch 的脚本 convert_original_tf_checkpoint_to_pytorch.py官方原始权重以google/*组织名发布checkpoint 命名模式为mobilenet_v1_{depth_multiplier}_{resolution}。快速上手图像分类推理官方文档给出了两种等价的使用方式均基于预训练权重google/mobilenet_v1_1.0_224。方式一使用 pipelinepipeline是开箱即用的高层封装只需指定任务与模型名from transformers import pipeline pipeline pipeline( taskimage-classification, modelgoogle/mobilenet_v1_1.0_224, device0 ) pipeline(https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg)其中device0指定将模型加载到第一张 GPU 上不传该参数则使用 CPU。将图片 URL 直接传给pipeline即可完成一次完整的下载图片 → 预处理 → 前向推理 → Top-K 分类结果流程。方式二使用 AutoModel AutoImageProcessor需要细粒度控制时用AutoImageProcessor与AutoModelForImageClassification组合import requests import torch from PIL import Image from transformers import AutoImageProcessor, AutoModelForImageClassification image_processor AutoImageProcessor.from_pretrained( google/mobilenet_v1_1.0_224, ) model AutoModelForImageClassification.from_pretrained( google/mobilenet_v1_1.0_224, device_mapauto, ) url https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg image Image.open(requests.get(url, streamTrue).raw) inputs image_processor(image, return_tensorspt).to(model.device) with torch.no_grad(): logits model(**inputs).logits predicted_class_id logits.argmax(dim-1).item() class_labels model.config.id2label predicted_class_label class_labels[predicted_class_id] print(fThe predicted class label is: {predicted_class_label})这段代码的要点device_mapauto让模型自动分布到可用设备用image_processor对 PIL 图片做预处理并返回 PyTorch 张量在torch.no_grad()下取得logits通过argmax(dim-1)取最高得分索引再经config.id2label映射为可读的类别标签。集成测试验证仓库的集成测试用一张小猫样例图验证了这一推理路径。MobileNetV1ForImageClassification在该输入下输出形状为(1, 1001)的 logits且 CPU/GPU 上 top-3 logits 与期望值[-4.1739, -1.1233, 3.1205]一致见 tests/models/mobilenet_v1/test_modeling_mobilenet_v1.py。这意味着上面的示例代码在仓库环境下可直接复现出正确的分类结果。模型使用须知Notescheckpoint 命名与输入分辨率命名模式为mobilenet_v1_{depth_multiplier}_{resolution}例如mobilenet_v1_1.0_224中的1.0是深度乘子depth multiplier、224是训练用图像分辨率虽然模型基于固定尺寸训练但架构本身可接受不同尺寸的输入最小 32×32。预处理细节由MobileNetV1ImageProcessor或 PIL 后端MobileNetV1ImageProcessorPil处理。从源码看处理器默认先把最短边 resize 到 256、再做 224×224 中心裁剪随后依次执行 rescale 与按 ImageNet 均值/标准差归一化见 image_processing_mobilenet_v1.py。类别数1000 还是 1001MobileNet 在 ImageNet-1k1000 类上预训练但模型实际预测1001 个类别——额外的第 0 类是背景background类。这一点在集成测试中被显式断言logits 形状为(1, 1001)tests/models/mobilenet_v1/test_modeling_mobilenet_v1.py。因此直接使用官方权重时分类头输出维度是 1001而不是 1000。tf_padding控制填充规则原始 TensorFlow checkpoint 的填充量是在推理时依据输入图像尺寸动态决定的。为完全对齐 TF 行为Transformers 默认在卷积层启用 TensorFlow SAME 填充规则。若想使用 PyTorch 原生的填充行为可将tf_paddingFalse传入MobileNetV1Configfrom transformers import MobileNetV1Config config MobileNetV1Config.from_pretrained(google/mobilenet_v1_1.0_224, tf_paddingTrue)其底层实现在 modeling_mobilenet_v1.pyapply_tf_padding依据特征图尺寸、卷积核大小与步长计算各边应补零的量再经nn.functional.pad以常数 0 填充MobileNetV1ConvLayer.forward会在config.tf_padding为真时先手动补边再执行卷积modeling_mobilenet_v1.py。与原始实现的差异与不支持项官方文档明确列出以下限制使用前需注意池化方式实现使用全局平均池化AdaptiveAvgPool2d((1, 1))见 modeling_mobilenet_v1.py而非原始可选的 7×7/stride-2 平均池化。对更大的输入池化输出会大于 1×1 像素output_stride 固定为 32实现不支持其它output_stride取值。原版在更小 stride 下会使用空洞卷积dilated convolution防止空间分辨率进一步下降hidden states 是整体的output_hidden_statesTrue返回全部 26 个 stage 的中间隐状态测试中断言len(hidden_states) 26见 tests/models/mobilenet_v1/test_modeling_mobilenet_v1.py无法只抽取特定层输出供其它下游用途不含量化模型原始 checkpoint 中的量化版本因包含去量化权重的 FakeQuantization 运算未被纳入实现。MobileNetV1Config 配置参数MobileNetV1Config继承PreTrainedConfigmodel_type mobilenet_v1。除通用配置属性如num_labels、id2label、output_hidden_states等外其关键字段与默认值如下均可在实例化时覆盖configuration_mobilenet_v1.py参数默认值说明num_channels3输入图像通道数RGBimage_size224训练/预期输入图像尺寸支持整数或(高, 宽)元组depth_multiplier1.0深度乘子width multiplier / alpha缩放每层通道数validate_architecture强制要求其大于 0见 configuration_mobilenet_v1.pymin_depth8所有层的通道数下限防止缩放后通道过少hidden_actrelu6卷积层激活函数tf_paddingTrue是否在卷积层使用 TensorFlow SAME 填充规则classifier_dropout_prob0.999分类头 dropout 概率见 modeling_mobilenet_v1.pyinitializer_range0.02权重初始化范围layer_norm_eps0.001BatchNorm 的eps典型用法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深度乘子的实际作用可从建模代码中看到初始层数depth32每层实际通道数为max(int(depth * config.depth_multiplier), config.min_depth)在步长为 2 的降采样点深度倍增见 modeling_mobilenet_v1.py。对照测试的取值方式测试用depth_multiplier0.25、image_size32、output_stride32组合出last_hidden_size 1024 * 0.25 256并验证输出形状(batch, 256, 1, 1)见 tests/models/mobilenet_v1/test_modeling_mobilenet_v1.py。预处理两个 Image Processor 与默认流水线MobileNetV1 提供了两个功能等价、后端不同的图像处理器MobileNetV1ImageProcessor基于 Torchvision 后端image_processing_mobilenet_v1.pyMobileNetV1ImageProcessorPil基于 PillowPIL后端image_processing_pil_mobilenet_v1.py。二者的preprocess都实现统一的默认预处理流水线类属性配置两份源码中完全一致属性默认值含义resampleBILINEAR缩放时使用的重采样算法image_mean/image_stdImageNet 标准值归一化均值与标准差size{shortest_edge: 256}先按最短边缩放到 256crop_size{height: 224, width: 224}中心裁剪到 224×224do_resize/do_center_crop/do_rescale/do_normalize均为True依次执行缩放、中心裁剪、重缩放像素到[0,1]、归一化标准流程即resize(最短边 256, 双线性) → center_crop(224×224) → rescale → normalize(ImageNet mean/std)。这些参数在实际使用中可通过from_pretrained加载 checkpoint 附带的preprocessor_config.json得到也可在实例化时传入覆盖。模型 API 与输出结构MobileNetV1Model基础主干模型输入为pixel_values输出无注意力权重。前向传播在 modeling_mobilenet_v1.py 中实现依次经过conv_stem与 26 层主干后由自适应平均池化得到pooler_output最终返回BaseModelOutputWithPoolingAndNoAttention包含last_hidden_state、pooler_output与可选的hidden_states。由于是纯卷积网络它没有 attention、不用input_ids/inputs_embeds测试中对这些用例做了显式跳过见 tests/models/mobilenet_v1/test_modeling_mobilenet_v1.py。MobileNetV1ForImageClassification在主干之上叠加分类头Dropout Linear线性层输出通道数取自主干最后一层卷积的out_channelsmodeling_mobilenet_v1.py。forward支持返回logits形状(batch_size, num_labels)传入labels形状(batch_size,)时自动计算损失num_labels 1用均方误差做回归num_labels 1用交叉熵做分类modeling_mobilenet_v1.py支持output_hidden_states与return_dict开关。它同时被接入 Transformers 的 pipeline 与 auto 映射机制模型测试中注册了image-feature-extraction主干与image-classification分类模型两个 pipeline 任务映射见 tests/models/mobilenet_v1/test_modeling_mobilenet_v1.py这也是本文开头两种推理方式能够直接工作的前提。小结在 Transformers 中MobileNet V1 是一个轻量卷积骨干 分类头的完整视觉模型其核心是深度可分离卷积与depth_multiplier/分辨率两个缩放旋钮配合tf_padding等配置还原原始 TensorFlow 权重行为。使用上pipeline适合快速推理AutoModelForImageClassificationAutoImageProcessor适合精细化控制同时需要注意 1001 类输出、output_stride固定为 32、无 attention、不含量化权重等实现边界。相关源码与测试可进一步参考 src/transformers/models/mobilenet_v1/ 目录下的实现文件及 tests/models/mobilenet_v1/ 下的测试套件。【免费下载链接】transformers Transformers: the model-definition framework for state-of-the-art machine learning models in text, vision, audio, and multimodal models, for both inference and training.项目地址: https://gitcode.com/GitHub_Trending/tra/transformers创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考

读完文章,也想定制专属网站?

尧图设计师 24 小时内与您沟通定制方案

免费获取报价