CLIP 零样本图像分类实战:无需训练的多类别识别流程

📅 2026/7/22 21:41:22 👁️ 阅读次数 📝 编程学习
CLIP 零样本图像分类实战:无需训练的多类别识别流程

CLIP 零样本图像分类实战:无需训练的多类别识别流程


这篇教程根据我复现 OpenAI CLIP 分类流程时整理,重点演示依赖安装、分类数据准备、文本 prompt 配置和零样本推理。

本文整理自我的学习和项目复现过程,尽量按实操顺序保留 notebook 的关键步骤,同时把数据集获取方式调整为适合中文教程发布的写法。

本文会重点跑通以下流程:

  • 安装 CLIP 依赖
  • 从数据集后台获取分类或检测数据
  • 整理类别名和候选文本 prompt
  • 运行 CLIP 零样本推理
  • 查看不同 prompt 对分类效果的影响

如果你正在系统学习目标检测、实例分割、OCR、多目标跟踪或视觉大模型,建议收藏本文;配套 notebook、示例图片和运行环境说明后续会继续整理。如果环境配置卡住,可以在评论区说明具体报错。

📚 文章目录

  • CLIP 零样本图像分类实战:无需训练的多类别识别流程
    • ⚙️ 安装 CLIP 依赖
    • 📦 从数据集后台获取数据
    • 🏷️ 整理类别与 Prompt
    • 🧪 运行 CLIP 推理
    • 📌 结束说明
    • 📌 小结
    • 📚 同系列教程汇总

⚙️ 安装 CLIP 依赖

先安装 CLIP 运行所需依赖并确认 CUDA 环境。

#installing some dependencies, CLIP was release in PyTorchimportsubprocess CUDA_version=[sforsinsubprocess.check_output(["nvcc","--version"]).decode("UTF-8").split(", ")ifs.startswith("release")][0].split(" ")[-1]print("CUDA version:",CUDA_version)ifCUDA_version=="10.0":torch_version_suffix="+cu100"elifCUDA_version=="10.1":torch_version_suffix="+cu101"elifCUDA_version=="10.2":torch_version_suffix=""else:torch_version_suffix="+cu110"!pip install torch==1.7.1{torch_version_suffix}torchvision==0.8.2{torch_version_suffix}-f https://download.pytorch.org/whl/torch_stable.html ftfy regeximportnumpyasnpimporttorchimportosprint("Torch version:",torch.__version__)os.kill(os.getpid(),9)#Your notebook process will restart after these installs
# 克隆 CLIP 仓库!git clone https://github.com/openai/CLIP.git%cd CLIP

📦 从数据集后台获取数据

准备分类或检测图片数据,用于后续零样本推理测试。

fromtypesimportSimpleNamespace# 从数据集后台下载 CLIP 分类 格式数据集后,修改 DATASET_DIR 指向解压目录。DATASET_DIR="/content/dataset"# 修改为数据集后台导出的数据集目录dataset=SimpleNamespace(location=DATASET_DIR,version="1",name="custom-dataset")
# 数据集已在上一单元配置,如需更换数据,请修改 DATASET_DIR。print(dataset.location)
dataset.location

🏷️ 整理类别与 Prompt

读取类别目录,并编辑候选文本描述。Prompt 质量会直接影响 CLIP 分类效果。

importos#our the classes and images we want to test are stored in folders in the test setclass_names=os.listdir(dataset.location+'/test/')class_names.remove('_tokenization.txt')class_names
# 可以先准备一份默认 prompt 文件,再根据自己的类别逐步优化文本描述。#CLIP gets a lot better with the right prompting!#be sure the tokenizations are in the same order as your class_names above!%cat{dataset.location}/test/_tokenization.txt
# 按需编辑 prompt,并确保顺序与类别列表一致%%writefile{dataset.location}/test/_tokenization.txt The paper signinrock paper scissors The rock signinrock paper scissors The scissors signinrock paper scissors
candidate_captions=[]withopen(dataset.location+'/test/_tokenization.txt')asf:candidate_captions=f.read().splitlines()

🧪 运行 CLIP 推理

加载图片和候选文本,计算图文相似度并输出预测类别。

importtorchimportclipfromPILimportImageimportglobdefargmax(iterable):returnmax(enumerate(iterable),key=lambdax:x[1])[0]device="cuda"iftorch.cuda.is_available()else"cpu"model,transform=clip.load("ViT-B/32",device=device)correct=[]#define our target classificaitons, you can should experiment with these strings of text as you see fit, though, make sure they are in the same order as your class names abovetext=clip.tokenize(candidate_captions).to(device)forclsinclass_names:class_correct=[]test_imgs=glob.glob(dataset.location+'/test/'+cls+'/*.jpg')forimgintest_imgs:#print(img)image=transform(Image.open(img)).unsqueeze(0).to(device)withtorch.no_grad():image_features=model.encode_image(image)text_features=model.encode_text(text)logits_per_image,logits_per_text=model(image,text)probs=logits_per_image.softmax(dim=-1).cpu().numpy()pred=class_names[argmax(list(probs)[0])]#print(pred)ifpred==cls:correct.append(1)class_correct.append(1)else:correct.append(0)class_correct.append(0)print('accuracy on class '+cls+' is :'+str(sum(class_correct)/len(class_correct)))print('accuracy on all is : '+str(sum(correct)/len(correct)))

📌 结束说明

这里保留 notebook 原有结束单元,实际发布时重点看前面的推理结果。

# 本单元作为 notebook 结束占位。print("CLIP zero-shot classification workflow completed.")

📌 小结

这篇教程完整整理了CLIP 零样本图像分类的核心复现流程。实际操作时,建议先确认 GPU、依赖版本、数据集路径和模型权重路径,再逐段运行 notebook。

后续我会继续按源项目顺序整理同系列中的目标检测、实例分割、OCR、多目标跟踪和视觉大模型教程。

📚 同系列教程汇总

  • Google Gemini 3.5 Flash 零样本目标检测教程:从提示词到可视化结果

  • GLM-OCR 文档识别实战教程:从验证码、公式到车牌 OCR

  • RF-DETR + ByteTrack 多目标跟踪实战教程:从命令行到 Python 视频轨迹可视化

  • SAM 3 图像分割实战教程:文本、框和点提示的多种分割方式

  • SAM 3 视频分割实战教程:用文本提示分割并跟踪视频中的目标

  • CLIP 零样本图像分类实战:无需训练的多类别识别流程-本文