← 研究笔记
无需标签即可分类图像:运行 OpenCLIP

无需标签即可分类图像:运行 OpenCLIP

记录在断开网络的情况下运行 OpenCLIP 的过程。OpenCLIP 是 CLIP 的一个开源实现,可以在同一空间中比较图像和文本。我为测试编写了候选句子,OpenCLIP 以很高的置信度选出了正确描述。我没有使用来自既有分类器训练的标签集。

本文涉及的仓库

mlfoundations/open_clip

An open source implementation of CLIP.

14k Python Other

按照传统流程进行图像分类时,需要准备“狗”和“猫”等大量标签,然后训练分类器。OpenCLIP 将图像和文本嵌入同一个向量空间,因此无需为这项分类任务准备带标签的数据,也能从任意候选项中选出距离最近的文本。我安装了它,并在断网状态下测试了零样本分类。

OpenCLIP 是 OpenAI 的 CLIP 模型的开源实现和复现版本。它将图像和文本转换为嵌入向量,然后计算二者的相似度。OpenCLIP 的源代码采用 MIT License。(*1)

1. 安装

在网络可用时构建镜像,并在构建过程中获取 CLIP 模型权重,即 OpenAI 公开的 ViT-B-32。

FROM docker.io/library/python:3.12.13-slim
RUN pip install --no-cache-dir --quiet 'torch==2.13.0' 'torchvision==0.28.0' --index-url https://download.pytorch.org/whl/cpu
RUN pip install --no-cache-dir --quiet 'open_clip_torch==3.3.0'
COPY warmup_model.py /tmp/warmup_model.py
RUN python /tmp/warmup_model.py
WORKDIR /work
podman build -t open-clip-sandbox .

2. 无需训练分类器即可分类图像

我生成了一张表现“包含天空、草地和太阳的户外风景”的合成图像(蓝天 + 绿色地面 + 黄色太阳),然后让 OpenCLIP 从四个候选描述中选出最接近的一项。这次测试没有训练分类器。测试在断网状态下进行。

import torch
from PIL import Image, ImageDraw
import open_clip

model, _, preprocess = open_clip.create_model_and_transforms("ViT-B-32", pretrained="openai")
tokenizer = open_clip.get_tokenizer("ViT-B-32")

img = Image.new("RGB", (224, 224), color=(90, 160, 230))
draw = ImageDraw.Draw(img)
draw.rectangle((0, 160, 224, 224), fill=(60, 140, 60))
draw.ellipse((150, 20, 200, 70), fill=(250, 210, 60))

candidate_labels = [
    "a sunny outdoor landscape with grass and sky",
    "a photo of a busy city street at night",
    "a close-up photo of a plate of food",
    "a photo of a laptop computer on a desk",
]

image_input = preprocess(img).unsqueeze(0)
text_input = tokenizer(candidate_labels)

with torch.no_grad():
    image_features = model.encode_image(image_input)
    text_features = model.encode_text(text_input)
    image_features /= image_features.norm(dim=-1, keepdim=True)
    text_features /= text_features.norm(dim=-1, keepdim=True)
    similarity = (100.0 * image_features @ text_features.T).softmax(dim=-1)
podman run --rm --network none --memory 2g --cpus 2 --pids-limit 512 \
  -v "$(pwd)":/work -w /work open-clip-sandbox \
  python classify_demo.py

-v 选项会让容器可以读写指定目录。请在专门用于实验的空目录中运行此命令。

命令返回:

 92.6%  a sunny outdoor landscape with grass and sky
  7.3%  a close-up photo of a plate of food
  0.1%  a photo of a laptop computer on a desk
  0.0%  a photo of a busy city street at night

正确候选项的置信度达到 92.6%。三个无关候选项的概率都保持在较低水平。我在这次实验中只使用了这四个候选句子,没有用于其他任务,也没有将它们纳入之前的分类器训练。

你不必为每项任务都构建分类器

准备专用的带标签数据集并训练分类器,会增加图像分类的准备工作。像 OpenCLIP 这样的模型可以在同一空间中比较图像和文本。只需写出想要测试的候选描述,就可以跳过为该任务构建分类器。

来源

*1 OpenCLIP(GitHub),https://github.com/mlfoundations/open_clip,MIT License