Sub topic 11
Zero-shot classification with text prompts
This chapter assumes you know what a joint image-text embedding space is, how CLIP's two encoders produce normalized vectors, and how cosine similarity and softmax work. You should be comfortable with basic PyTorch tensor operations. Here you will turn a trained CLIP model into an image classifier without training it on any labeled classification data.
What "zero-shot" means here
A conventional classifier has a fixed output layer with one unit per class. Adding a class means collecting labels and retraining. CLIP has no such layer. During pretraining it only learned to place an image near the text that describes it.
Zero-shot classification uses that property. You describe each candidate class as a short piece of text. You embed the texts and the image, and you pick the class whose text embedding is most similar to the image embedding. The model never saw a labeled example for your task. The class list is supplied at inference time, which is why this is also called open-vocabulary recognition.
The text embeddings act as the weights of a classifier that you build on the fly. Each class name becomes one row of a weight matrix.
The algorithm step by step
- Choose the class names, for example
cat,dog,car. - Wrap each name in a prompt, for example
a photo of a cat. - Encode every prompt with the text encoder and normalize the result to unit length.
- Encode the image with the image encoder and normalize it.
- Compute the dot product between the image vector and each text vector. Because both are unit length, this is the cosine similarity.
- Multiply by the learned logit scale, which is the exponential of the learned temperature parameter. Apply softmax across the classes to get probabilities.
The softmax only ranks the classes you supplied. It never says "none of these". If the image shows a bicycle and your list is cat, dog, car, the probabilities still sum to 1 across those three.
Running it with Hugging Face
The following code loads a pretrained CLIP and classifies one image. Replace photo.jpg with a real image path.
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")
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)
probs = outputs.logits_per_image.softmax(dim=1)
print(dict(zip(labels, probs[0].tolist())))Some details of this code matter.
padding=Truepads the prompts to equal length so they can be batched. The text encoder uses the position of the end-of-text token to pool its output, so padding does not change the result.outputs.logits_per_imagehas shape(num_images, num_prompts). It already contains the logit scale, so you only need to apply softmax.torch.no_grad()avoids storing gradients, which saves memory during inference.- The processor resizes and center-crops the image to the resolution the model expects, and normalizes pixel values with CLIP's own mean and standard deviation.
Why the temperature matters at inference
Raw cosine similarities between an image and short texts are usually close together, often in a range such as 0.15 to 0.35. Softmax over values that close gives a nearly uniform distribution. CLIP's learned logit scale, which is about 100 for the released models, stretches the differences before softmax.
| Quantity | Typical value | Effect |
|---|---|---|
| Cosine similarity | 0.15 to 0.35 | Small spread between classes |
| Logit scale | about 100 | Multiplies the cosine values |
| Scaled logits | about 15 to 35 | Softmax gives a usable distribution |
The scale does not change which class wins, because it multiplies every logit by the same positive number. It only changes how confident the probabilities look. If you only need the top-1 prediction, you can use argmax on the cosine similarities directly.
Treat the probabilities with care. A probability of 0.95 does not mean the model is right 95% of the time. The values are relative scores among your listed classes, and they are often overconfident when none of the classes fits well.
Building the classifier once and reusing it
Encoding the prompts for every image is wasteful. The text side depends only on the class list, so compute it once and cache it. The following example builds a reusable classifier.
import torch
import torch.nn.functional as F
from PIL import Image
from transformers import CLIPModel, CLIPProcessor
model = CLIPModel.from_pretrained("openai/clip-vit-base-patch32").eval()
processor = CLIPProcessor.from_pretrained("openai/clip-vit-base-patch32")
labels = ["cat", "dog", "car"]
prompts = [f"a photo of a {label}" for label in labels]
with torch.no_grad():
text_inputs = processor(text=prompts, return_tensors="pt", padding=True)
text_emb = F.normalize(model.get_text_features(**text_inputs), dim=-1) # (classes, dim)
def classify(path):
image = Image.open(path).convert("RGB")
with torch.no_grad():
image_inputs = processor(images=image, return_tensors="pt")
image_emb = F.normalize(model.get_image_features(**image_inputs), dim=-1)
logits = model.logit_scale.exp() * image_emb @ text_emb.t()
probs = logits.softmax(dim=-1)[0]
return dict(zip(labels, probs.tolist()))
print(classify("photo.jpg"))The text_emb matrix plays the role of a linear layer's weights. Classifying an image costs one image-encoder forward pass and one small matrix multiplication, however many classes you have. Converting to RGB guards against grayscale or RGBA files, which the processor may otherwise handle inconsistently.
Prompt wording changes accuracy
The class name alone, such as cat, is a poor prompt. CLIP was trained on captions, not on single words. A full phrase is closer to the training distribution. The model also sees ambiguity: the word crane could mean a bird or a machine, and a single word gives no hint.
Common fixes include the following.
- Use a template such as
a photo of a {}. - Add context that matches your data, such as
a satellite photo of {}.ora photo of a {}, a type of pet. - Add a domain hint for ambiguous names, such as
a photo of a crane, a type of bird.
The next chapter covers templates and prompt ensembling in detail. For now, remember that the prompt is part of the model you are building, so you should evaluate it as you would any other hyperparameter.
Evaluating a zero-shot classifier
To measure accuracy, run the procedure over a labeled test set and compare predictions to the true labels. Use a held-out set that you did not use to choose prompts, or your estimate will be optimistic. Trying many prompt wordings and reporting the best one on the same test data is a form of tuning on the test set.
The following function computes top-1 accuracy from precomputed, normalized embeddings.
import torch
def top1_accuracy(image_emb, text_emb, targets):
# image_emb: (n, dim) normalized; text_emb: (classes, dim) normalized
# targets: (n,) integer class indices
similarity = image_emb @ text_emb.t()
predictions = similarity.argmax(dim=1)
return (predictions == targets).float().mean().item()Precomputing image embeddings once lets you compare many prompt sets quickly, because only the small text side changes.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Probabilities are nearly equal | Softmax applied to raw cosine values without the logit scale | Multiply by `logit_scale.exp()` or use `logits_per_image` |
| Results differ between runs of your own code and the library | Forgot to normalize embeddings before the dot product | Apply `F.normalize(..., dim=-1)` to both sides |
| Wrong class for ambiguous names | Single-word prompts | Add a template and context |
| Confident answer on an unrelated image | No "none of the above" option exists | Add a background class or a similarity threshold |
| Poor accuracy on fine-grained or specialized data | Pretraining data rarely covered the domain | Try domain-specific prompts or a linear probe |
| Slow evaluation | Text re-encoded for every image | Cache the text embeddings |
Where zero-shot works and where it struggles
Zero-shot CLIP does well on common object categories that appear often in web captions. It is weaker on tasks that captions rarely describe, such as counting objects, judging distances, reading fine detail, or telling apart narrow fine-grained categories. Very specialized domains, such as medical images, also tend to do poorly. In those cases a linear probe on the image embeddings, covered later, usually gives a large improvement. The final chapters on limitations return to these failure modes.
Exercise
You run zero-shot classification and get probabilities of 0.34, 0.33, and 0.33 for three classes, even though the top class is correct. Your code computes softmax over the raw cosine similarities between normalized embeddings. What is wrong, and how do you fix it without changing the predicted class?
Show answer
The cosine similarities lie in a narrow range, so softmax over them is almost uniform. The model's learned logit scale (about 100) was not applied. Multiply the similarities by model.logitscale.exp() before softmax, or use outputs.logitsper_image. The predicted class does not change, because multiplying all logits by the same positive constant keeps the ordering.
Exercise
You classify an image against the labels "bank", "crane", and "bat" with the bare words as prompts, and results look random. Give two changes to the prompts that should help, and say why.
Show answer
Wrap each word in a caption-like template such as "a photo of a {}." because CLIP was trained on captions rather than single words. Add context to resolve ambiguity, for example "a photo of a crane, a type of bird." or "a photo of a bat, a flying mammal." so the text embedding reflects the intended meaning.