Sub topic 11
Zero-Shot Classification with CLIP Text Prompts
Prerequisites and the basic idea
This chapter assumes that you know Python, PyTorch tensors, softmax, and vector similarity. It also assumes that you understand that CLIP has an image encoder and a text encoder that produce vectors in the same embedding space.
Zero-shot classification means classifying an image without training a classifier on labeled examples from the target classes. Instead, you write the class names as text prompts. CLIP embeds the image and each prompt, then selects the prompt with the highest image-text similarity.
For example, instead of training a classifier for cat, dog, and car, you can compare an image with:
- “a photo of a cat”
- “a photo of a dog”
- “a photo of a car”
The prompt whose embedding is closest to the image embedding becomes the prediction.
From prompts to probabilities
During CLIP training, matching image-caption pairs were pulled together while mismatched pairs were pushed apart. The resulting similarity scores are called logits. A learned logit scale, also called the inverse temperature, controls how sharply the scores differ.
For a set of prompts \(t1, \ldots, tK\) and an image embedding \(v\), CLIP computes:
s_k = \exp(\alpha) \frac{v \cdot t_k}{\|v\|\|t_k\|}Here, \(\alpha\) is the learned logit-scale parameter. Applying softmax to the scores gives a probability distribution over the candidate classes:
p_k = \frac{\exp(s_k)}{\sum_j \exp(s_j)}These probabilities describe the model's preference among the prompts. They are not guaranteed to be calibrated probabilities in the statistical sense.
Running a classifier
The following example uses a pretrained CLIP model from Hugging Face. The processor applies the image transformations and tokenizes the text.
import torch
from PIL import Image
from transformers import CLIPModel, CLIPProcessor
model = CLIPModel.from_pretrained("openai/clip-vit-base-patch32")
processor = CLIPProcessor.from_pretrained("openai/clip-vit-base-patch32")
image = Image.open("photo.jpg").convert("RGB")
labels = ["cat", "dog", "car"]
prompts = [f"a photo of a {label}" for label in labels]
inputs = processor(
text=prompts,
images=image,
return_tensors="pt",
padding=True,
)
with torch.no_grad():
outputs = model(**inputs)
probabilities = outputs.logits_per_image.softmax(dim=1)[0]
prediction_index = probabilities.argmax().item()
print("prediction:", labels[prediction_index])
print("scores:", dict(zip(labels, probabilities.tolist())))The rows of logits_per_image correspond to images, and its columns correspond to prompts. With one image and three prompts, its shape is (1, 3). The argmax selects the prompt with the largest score.
Prompt design and prompt ensembling
Prompt wording affects performance because the text encoder represents the entire phrase, not only the class noun. “A photo of a dog” may work better than simply “dog” for photographic data.
A more stable method is prompt ensembling. Create several templates, such as “a photo of a {}” and “an image of a {}”. Encode every version, average the normalized text embeddings for each class, and compare the image with those averages. This reduces dependence on one arbitrary wording.
Exercise
If two prompts describe the same class but one uses “a photo of a bird” and the other uses “a drawing of a bird,” why might their scores differ?
Show answer
The text encoder represents the surrounding words, so the prompts describe different visual distributions. The image may match one style more closely than the other.