以傳統流程分類影像時,需要準備許多標籤,例如「狗」和「貓」,再訓練分類器。OpenCLIP 將影像和文字嵌入同一個向量空間,因此無需為分類任務準備標註資料,就能從任意候選項中選出最接近的文字。我安裝了 OpenCLIP,並在網路中斷的狀態下測試 zero-shot 分類。
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