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_version10.0:torch_version_suffixcu100elifCUDA_version10.1:torch_version_suffixcu101elifCUDA_version10.2:torch_version_suffixelse:torch_version_suffixcu110!pip install torch1.7.1{torch_version_suffix}torchvision0.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# 修改为数据集后台导出的数据集目录datasetSimpleNamespace(locationDATASET_DIR,version1,namecustom-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_namesos.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 scissorscandidate_captions[]withopen(dataset.location/test/_tokenization.txt)asf:candidate_captionsf.read().splitlines() 运行 CLIP 推理加载图片和候选文本计算图文相似度并输出预测类别。importtorchimportclipfromPILimportImageimportglobdefargmax(iterable):returnmax(enumerate(iterable),keylambdax:x[1])[0]devicecudaiftorch.cuda.is_available()elsecpumodel,transformclip.load(ViT-B/32,devicedevice)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 abovetextclip.tokenize(candidate_captions).to(device)forclsinclass_names:class_correct[]test_imgsglob.glob(dataset.location/test/cls/*.jpg)forimgintest_imgs:#print(img)imagetransform(Image.open(img)).unsqueeze(0).to(device)withtorch.no_grad():image_featuresmodel.encode_image(image)text_featuresmodel.encode_text(text)logits_per_image,logits_per_textmodel(image,text)probslogits_per_image.softmax(dim-1).cpu().numpy()predclass_names[argmax(list(probs)[0])]#print(pred)ifpredcls: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 文档识别实战教程从验证码、公式到车牌 OCRRF-DETR ByteTrack 多目标跟踪实战教程从命令行到 Python 视频轨迹可视化SAM 3 图像分割实战教程文本、框和点提示的多种分割方式SAM 3 视频分割实战教程用文本提示分割并跟踪视频中的目标CLIP 零样本图像分类实战无需训练的多类别识别流程-本文