# MobileCLIP2 型号对比与图片分类

对比 S0、S2 与更大的型号，再用自己的标签运行图文匹配。MobileCLIP2 生成适用于分类和检索的向量；需要自然语言回答时可使用 FastVLM。

Canonical URL: https://aiidelist.com/zh/blog/mobileclip2-zh

Language: zh

Published: 2026-09-24

Updated: 2026-09-24

MOBILECLIP2 · IMAGE CLASSIFICATION

对比 S0、S2 与更大的型号，再用自己的标签运行图文匹配。MobileCLIP2 生成适用于分类和检索的向量；需要自然语言回答时可使用 FastVLM。

[S0 / S2 本站实测：24 张图片、CPU 耗时与内存 →](/zh/blog/mobileclip2-s0-vs-s2-zh)

## 选择哪个 MobileCLIP2 型号？

图像编码器最小的 S0 适合起步。S2 的公开 ImageNet 准确率从 71.5% 提升至 77.2%。选择更大型号前，应在自己的图片上验证收益，并测量内存与计算成本。

| 型号 | 图像编码器（百万参数） | 文本编码器（百万参数） | ImageNet top-1（%） |
| --- | --- | --- | --- |
| [S0 ↗](https://huggingface.co/apple/MobileCLIP2-S0) | 11.4 | 63.4 | 71.5 |
| [S2 ↗](https://huggingface.co/apple/MobileCLIP2-S2) | 35.7 | 63.4 | 77.2 |
| [B ↗](https://huggingface.co/apple/MobileCLIP2-B) | 86.3 | 63.4 | 79.4 |
| [S3 ↗](https://huggingface.co/apple/MobileCLIP2-S3) | 125.1 | 123.6 | 80.7 |
| [L-14 ↗](https://huggingface.co/apple/MobileCLIP2-L-14) | 304.3 | 123.6 | 81.9 |
| [S4 ↗](https://huggingface.co/apple/MobileCLIP2-S4) | 321.6 | 123.6 | 81.9 |

数值来自 Apple 模型卡，核对于 2026-09-12。ImageNet 零样本 top-1 是该基准上的准确率，不代表你的图片的准确率。 [Apple model card](https://huggingface.co/apple/MobileCLIP2-S0)

## 运行自己的图片分类

1. 创建 Python 环境并安装下方依赖。
2. 下载 mobileclip2.py，与待测图片放在同一目录。
3. 执行命令，提供至少两个候选标签。首次运行会下载模型权重。
4. 检查 JSON 排名，更换标签验证它是否适合你的任务。

Python · macOS / Linux

```text
python -m venv .venv
source .venv/bin/activate
python -m pip install "open_clip_torch==3.3.0" "timm==1.0.29" torch pillow
curl -fLO https://fastvlm.net/examples/mobileclip2.py
python mobileclip2.py image.png --model S0 --labels "a receipt" "a chart" "a photograph"
```

[下载 Python 示例 ↓](/fastvlm/downloads/mobileclip2.py)mobileclip2.py

```text
"""Classify a local image against candidate labels with MobileCLIP2.

Install: python -m pip install "open_clip_torch==3.3.0" "timm==1.0.29" torch pillow
Run: python mobileclip2.py image.png --labels 'a receipt' 'a chart' 'a photograph'
Uses the timm/OpenCLIP adaptation of Apple's weights, downloaded on first run.
Source: https://huggingface.co/timm/MobileCLIP2-S0-OpenCLIP
"""
import argparse
import json
from pathlib import Path

import open_clip
import torch
from PIL import Image
from timm.utils import reparameterize_model

def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('image', type=Path)
    parser.add_argument('--model', choices=['S0', 'S2', 'B', 'S3', 'L-14', 'S4'], default='S0')
    parser.add_argument('--labels', nargs='+', required=True)
    args = parser.parse_args()
    if not args.image.is_file():
        parser.error('The image file does not exist.')
    if len(args.labels) < 2:
        parser.error('Provide at least two candidate labels.')
    name = 'MobileCLIP2-' + args.model
    device = 'cuda' if torch.cuda.is_available() else 'cpu'
    model, _, preprocess = open_clip.create_model_and_transforms(name, pretrained='dfndr2b')
    model = reparameterize_model(model.eval()).to(device)
    tokenizer = open_clip.get_tokenizer(name)
    image = preprocess(Image.open(args.image).convert('RGB')).unsqueeze(0).to(device)
    text = tokenizer(args.labels).to(device)
    with torch.inference_mode():
        image_features = model.encode_image(image)
        text_features = model.encode_text(text)
        image_features /= image_features.norm(dim=-1, keepdim=True)
        text_features /= text_features.norm(dim=-1, keepdim=True)
        scores = (100.0 * image_features @ text_features.T).softmax(dim=-1)[0].cpu().tolist()
    results = sorted(zip(args.labels, scores), key=lambda item: item[1], reverse=True)
    print(json.dumps({'model': name, 'scores': [{'label': label, 'score': score} for label, score in results],
        'note': 'Relative scores within the supplied labels, not calibrated probabilities.'}, indent=2))

if __name__ == '__main__':
    main()
```

预期输出：包含模型名与按分数排序的标签的 JSON。分数仅相对于当前候选集，不是经过校准的概率。建议同时测试相关与无关标签。

示例使用 timm/OpenCLIP 适配版。Apple 原始 checkpoint 与 OpenCLIP 兼容文件的命名和加载方式不同。

## 如何选择 MobileCLIP、MobileCLIP2、CLIP 和 FastVLM？

- MobileCLIP → MobileCLIP2：在同样尺寸、预处理和自有标注图片上对比。第二代改进了训练方法，不应把第一代的速度倍数直接套用到所有第二代型号。
- CLIP / SigLIP 替代方案：保持图片、候选标签和设备一致，同时比较准确率、延迟与内存。
- FastVLM：如果任务需要文字解释而不是标签排序，选择生成式图片问答。

[体验 FastVLM 图片问答 →](/zh/fastvlm/demo#image-playground)

## 常见问题

- 找不到型号：更新 open_clip_torch 和 timm，检查 open_clip.list_models() 是否包含 MobileCLIP2-S0。
- 结果异常：使用 eval 模式，以及模型对应的 preprocess 和 tokenizer。
- 下载失败：检查 Hugging Face 网络连接与磁盘空间。

## 来源与下载

[Apple GitHub ↗](https://github.com/apple-aiml-research/ml-mobileclip) · [timm / OpenCLIP ↗](https://huggingface.co/timm/MobileCLIP2-S0-OpenCLIP) · [Paper ↗](https://arxiv.org/abs/2508.20691)
