> ## Documentation Index
> Fetch the complete documentation index at: https://aegean.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# CLIP Zero-Shot Classification

> Zero-shot CLIP on CIFAR-10, prompt ensembles and a comparison with a linear probe.

[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/pantelis/eng-ai-agents/blob/main/notebooks/vlm/clip/zero-shot/clip_zero_shot.ipynb)

A trained CLIP model can classify images into categories it was never trained on, without a single labeled example. This section shows that the procedure is an ordinary linear classifier whose weights are written in English, measures it on the 10,000 test images of CIFAR-10, and compares it with a classifier trained on labeled examples. The notation follows the [CLIP section](https://aegean.ai/aiml-common/lectures/vlm/clip/index.md): $\boldsymbol\ell$ is an image, $\mathbf{t}$ a text, $f_\ell$ and $f_t$ the two encoders, and $\mathbf{z}_\ell = f_\ell(\boldsymbol\ell)$ and $\mathbf{z}_t = f_t(\mathbf{t})$ their unit-length embeddings.

## Zero-shot classification is a linear classifier

For classes $y \in \{1, \dots, K\}$, write a prompt $\mathbf{t}^y$ for each class, such as "a photo of a dog.", and embed it, $\mathbf{w}_y = f_t(\mathbf{t}^y)$. For an image with embedding $\mathbf{z}_\ell$, predict the class whose prompt is most similar:

$$
\hat{y} = \arg\max_y \; \mathbf{w}_y^\top \mathbf{z}_\ell .
$$

This is a linear classifier on the image embedding. The weight matrix $W = [\mathbf{w}_1, \dots, \mathbf{w}_K]^\top$ has one row per class, and the scores $W \mathbf{z}_\ell$ followed by a softmax give class probabilities, exactly as in [logistic regression](https://aegean.ai/aiml-common/lectures/classification/logistic-regression/index.md). The difference is where the weights come from. Logistic regression fits $W$ to labeled images. Zero-shot classification computes $W$ from text, so changing the classes means changing the prompts, and no image of the new classes is needed. The quality of the classifier then depends on two things: how well the image embedding separates the classes, and how well the prompts point at them.

> [accordion] Code
>
> ```python theme={null}
> import numpy as np
> import torch
> import torch.nn.functional as F
> from torch.utils.data import DataLoader
> from torchvision import datasets
> from transformers import AutoModel, AutoProcessor
>
> device = "cuda" if torch.cuda.is_available() else "cpu"
> torch.manual_seed(0)
>
> model = AutoModel.from_pretrained("openai/clip-vit-base-patch32").to(device).eval()
> processor = AutoProcessor.from_pretrained("openai/clip-vit-base-patch32")
> print(f"[INFO] device: {device}")
> ```

```output theme={null}
[INFO] device: cuda
```

## Embedding the data

The image encoder runs once over the CIFAR-10 test set and once over the training set. Every classifier below, zero-shot or trained, works on these frozen embeddings. The images are $32 \times 32$ and are enlarged to $224 \times 224$ by the processor, which makes this a harder test than the photos CLIP was trained on.

> [accordion] Code
>
> ```python theme={null}
> @torch.no_grad()
> def embed_images(dataset, batch_size=500):
>     loader = DataLoader(dataset, batch_size=batch_size, collate_fn=lambda b: b, num_workers=4)
>     feats, labels = [], []
>     for batch in loader:
>         x = processor(images=[im for im, _ in batch], return_tensors="pt").to(device)
>         feats.append(F.normalize(model.get_image_features(**x).pooler_output, dim=-1).float().cpu())
>         labels += [y for _, y in batch]
>     return torch.cat(feats), torch.tensor(labels)
>
>
> @torch.no_grad()
> def embed_texts(texts):
>     x = processor(text=texts, return_tensors="pt", padding=True).to(device)
>     return F.normalize(model.get_text_features(**x).pooler_output, dim=-1).float().cpu()
>
>
> train_set = datasets.CIFAR10("data", train=True, download=True)
> test_set = datasets.CIFAR10("data", train=False, download=True)
> CLASSES = test_set.classes
> Z_test, y_test = embed_images(test_set)
> Z_train, y_train = embed_images(train_set)
> print(f"[INFO] test embeddings {tuple(Z_test.shape)}, training embeddings {tuple(Z_train.shape)}")
> ```

```output theme={null}
[INFO] test embeddings (10000, 512), training embeddings (50000, 512)
```

## Prompts

Radford et al. found that the bare class name is a weak prompt (Radford et al., 2021). Captions on the web are sentences, not single words, and a single word can be ambiguous: "crane" is a bird and a machine. Wrapping the name in a sentence such as `a photo of a \{class\}.` moves the prompt closer to the captions the text encoder was trained on. Averaging the embeddings of several such sentences, *prompt ensembling*, gives a weight vector that depends less on the wording of any one of them. The cell compares the three choices.

> [accordion] Code
>
> ```python theme={null}
> TEMPLATES = [
>     "a photo of a {}.",
>     "a blurry photo of a {}.",
>     "a low resolution photo of a {}.",
>     "a pixelated photo of a {}.",
>     "a photo of the small {}.",
>     "a photo of the big {}.",
>     "a black and white photo of a {}.",
>     "a drawing of a {}.",
> ]
>
>
> def accuracy(W, Z=Z_test, y=y_test):
>     return ((Z @ W.T).argmax(1) == y).float().mean().item()
>
>
> W_name = embed_texts(CLASSES)
> W_photo = embed_texts([f"a photo of a {c}." for c in CLASSES])
> W_ensemble = F.normalize(
>     torch.stack([embed_texts([t.format(c) for t in TEMPLATES]).mean(0) for c in CLASSES]), dim=-1
> )
> for name, W in [("class name", W_name), ('"a photo of a {class}."', W_photo),
>                 (f"ensemble of {len(TEMPLATES)} templates", W_ensemble)]:
>     print(f"{name:<32} test accuracy {accuracy(W):.3f}")
> ```

```output theme={null}
class name                       test accuracy 0.874
"a photo of a {class}."          test accuracy 0.883
ensemble of 8 templates          test accuracy 0.896
```

The bare class names give 87.4% on the test set, the single template 88.3% and the ensemble of eight templates 89.6%. The gains are modest here because the ten CIFAR-10 names are common, unambiguous words. On data sets with rare or ambiguous class names, Radford et al. report much larger gains from the same two steps.

![Output from cell 5](https://mintcdn.com/aegeanaiinc/bnmY3M_RtHn28AKl/aiml-common/lectures/vlm/clip/zero-shot/images/cell_5_output_1.png?fit=max\&auto=format\&n=bnmY3M_RtHn28AKl\&q=85\&s=9118a6b57bc81257ce3f70c9ca2f1087)

Most errors fall between classes that look alike at $32 \times 32$ pixels. Cats and dogs are confused in both directions (7% each), 13% of the deer are called horses, and frogs, the weakest class at 78%, go to cats and birds. Horses (98%), ships (96%) and trucks (95%) are almost always right.

## Zero-shot against a linear probe

How good is a classifier written in English, compared with one trained on labeled images? A *linear probe* answers this on the same embedding. It trains a logistic regression on the frozen image embeddings of $k$ labeled images per class and is tested on the same 10,000 test images. Both classifiers are linear in $\mathbf{z}_\ell$, so the comparison measures only where the weights come from. Radford et al. found that, averaged over 27 data sets, zero-shot CLIP matched a linear probe trained with 4 examples per class.

> [accordion] Code
>
> ```python theme={null}
> from sklearn.linear_model import LogisticRegression
>
> rng = np.random.default_rng(0)
> by_class = [np.flatnonzero(y_train.numpy() == c) for c in range(10)]
> shots = [1, 2, 4, 8, 16, 64, 256]
> probe = {}
> for k in shots:
>     accs = []
>     for seed in range(5 if k <= 16 else 1):  # average the small-k runs over 5 draws
>         r = np.random.default_rng(seed)
>         idx = np.concatenate([r.choice(ix, k, replace=False) for ix in by_class])
>         clf = LogisticRegression(max_iter=2000, C=10.0).fit(Z_train[idx], y_train[idx])
>         accs.append(clf.score(Z_test, y_test))
>     probe[k] = float(np.mean(accs))
>     print(f"linear probe, {k:>3} examples per class: test accuracy {probe[k]:.3f}")
>
> full = LogisticRegression(max_iter=3000, C=10.0).fit(Z_train, y_train)
> probe_full = full.score(Z_test, y_test)
> print(f"linear probe, all 5,000 per class:   test accuracy {probe_full:.3f}")
> print(f"zero-shot, prompt ensemble:          test accuracy {accuracy(W_ensemble):.3f}")
> ```

```output theme={null}
linear probe,   1 examples per class: test accuracy 0.654
linear probe,   2 examples per class: test accuracy 0.793
linear probe,   4 examples per class: test accuracy 0.843
linear probe,   8 examples per class: test accuracy 0.869
linear probe,  16 examples per class: test accuracy 0.899
linear probe,  64 examples per class: test accuracy 0.924
linear probe, 256 examples per class: test accuracy 0.930
linear probe, all 5,000 per class:   test accuracy 0.950
zero-shot, prompt ensemble:          test accuracy 0.896
```

![Output from cell 7](https://mintcdn.com/aegeanaiinc/bnmY3M_RtHn28AKl/aiml-common/lectures/vlm/clip/zero-shot/images/cell_7_output_1.png?fit=max\&auto=format\&n=bnmY3M_RtHn28AKl\&q=85\&s=c83e21dab02631dd90d2ad4b862ed482)

The zero-shot classifier (89.6%) is as accurate as a linear probe trained with 16 labeled images per class (89.9%), and clearly more accurate than one trained with 4 per class (84.3%). With all 5,000 images per class the probe reaches 95.0%, so the image embedding holds more information about these classes than the text prompts manage to point at. Prompts give a good classifier when there are no labels, and a few hundred labeled images are enough to do better.

## Exercises

1. Add the eight templates one at a time, in the order given, and plot the accuracy against the number of templates.
2. Replace "automobile" with "car" and "airplane" with "plane" in the prompts. Does the accuracy change? What does this tell you about choosing class names?
3. Initialize the weights of the logistic regression with the zero-shot weights $W$ (scaled by 100) and train it with 4 examples per class. Does starting from the text help?
4. Evaluate the zero-shot classifier on CIFAR-100, which has 100 classes. How does the gap to the linear probe change with the number of classes?

## Key references

Radford et al. introduced zero-shot transfer with CLIP and compared it with linear probes on 27 data sets (Radford et al., 2021).

## References

* Radford, A., Kim, J., Hallacy, C., Ramesh, A., Goh, G., et al. (2021). *Learning transferable visual models from natural language supervision*. arXiv \[cs.CV]. [Link](http://arxiv.org/abs/2103.00020)

***

Found an error on this page? [Report an issue](https://github.com/aegean-ai/eaia-feedback/issues/new?template=page-issue.yml\&page=/aiml-common/lectures/vlm/clip/zero-shot).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.