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 零样本图像分类实战无需训练的多类别识别流程-本文

相关新闻

最新新闻

SerenityOS 命令行选项解析指南:getopt 与 getopt_long 用法、返回值与底层实现

SerenityOS 命令行选项解析指南:getopt 与 getopt_long 用法、返回值与底层实现

SerenityOS 命令行选项解析指南:getopt 与 getopt_long 用法、返回值与底层实现 【免费下载链接】serenity The Serenity Operating System 🐞 项目地址: https://gitcode.com/GitHub_Trending/se/serenity 导读 本文以 getopt(3) 手册 为核心&a…

2026/9/29 2:52:50
轻量服务器还是ECS?大促云服务器选购与避坑实战指南

轻量服务器还是ECS?大促云服务器选购与避坑实战指南

每年大促节点,群里永远有人在问同一个问题:“38元的轻量服务器到底怎么抢?为什么我每次点进去都是已售罄?68元直购和99元的ECS我到底选哪个?”作为一个常年帮团队和自己采购云服务器的老用户,我太清楚这种纠…

2026/9/29 2:52:51
为 AI 代理的 Review 动作编写 Cedar 审批门控策略:review-agent-governance 策略编写实战指南

为 AI 代理的 Review 动作编写 Cedar 审批门控策略:review-agent-governance 策略编写实战指南

为 AI 代理的 Review 动作编写 Cedar 审批门控策略:review-agent-governance 策略编写实战指南 【免费下载链接】agents Multi-harness agentic plugin marketplace for Claude Code, Codex, Cursor, OpenCode, GitHub Copilot, and Google Antigravity 项目地址:…

2026/9/29 1:29:30
PaddleOCR 手写数学公式识别算法 CAN 实战指南:Counting-Aware Network 训练、评估与推理部署

PaddleOCR 手写数学公式识别算法 CAN 实战指南:Counting-Aware Network 训练、评估与推理部署

PaddleOCR 手写数学公式识别算法 CAN 实战指南:Counting-Aware Network 训练、评估与推理部署 【免费下载链接】PaddleOCR Turn any PDF or image document into structured data for your AI. A powerful, lightweight OCR toolkit that bridges the gap between i…

2026/9/29 1:39:24
Spring源码解析:构造器注入的类型转换与候选匹配机制

Spring源码解析:构造器注入的类型转换与候选匹配机制

/* MD / 富文本中的 .toc(含博客园搬家等嵌套结构);.toc-box 在侧栏,不受影响 */#content_views .toc,/* 编辑器常在目录前后插入空 p(:empty 仍占 20px),一并去掉避免顶空隙 */#content_views.markdown_views > p:empty:has(+ .toc),#content_views.markdown_views …

2026/9/28 17:20:49
openai-agents-python 多模型接入指南:深入解析 AnyLLMModel 适配层与 any-llm 路由

openai-agents-python 多模型接入指南:深入解析 AnyLLMModel 适配层与 any-llm 路由

openai-agents-python 多模型接入指南:深入解析 AnyLLMModel 适配层与 any-llm 路由 【免费下载链接】openai-agents-python A lightweight, powerful framework for multi-agent workflows 项目地址: https://gitcode.com/GitHub_Trending/op/openai-agents-pyth…

2026/9/29 2:52:53

日新闻

周新闻