Sub topic 14
Linear probes and evaluating learned features
This chapter assumes you know how CLIP's image encoder produces a normalized embedding, and that you are comfortable with PyTorch tensors, softmax, cross-entropy, and train/validation/test splits. You do not need to have trained a CLIP model yourself.
Why evaluate features at all
CLIP is trained on image-text pairs, not on labeled classes. So the question "is the model any good?" needs a protocol. Two protocols dominate the CLIP literature:
- Zero-shot evaluation asks how well the model classifies using only text prompts, with no labeled training images from the target dataset.
- Linear-probe evaluation asks how good the frozen image features are when a simple classifier is trained on top of them.
These answer different questions. Zero-shot measures how well the text side and image side agree. A linear probe measures how much linearly usable class information is stored in the image embedding itself. A model can do well on one and poorly on the other.
What a linear probe is
A linear probe is a single linear layer (often logistic regression) trained on top of a frozen encoder.
- Pass every training image through the image encoder once. Keep the resulting feature vectors.
- Train a linear classifier on those vectors and their labels.
- Report accuracy on a held-out test set.
The encoder never changes. Because the classifier is linear, it cannot invent new structure. If it reaches high accuracy, the classes were already separable by a hyperplane in the feature space. That is why a linear probe is a common measure of representation quality.
Probe versus fine-tuning
Fine-tuning updates the encoder weights too. It usually reaches higher accuracy on the target dataset, but it mixes two effects: how good the pretrained features were, and how much the new training changed them. A linear probe isolates the first effect. It is also cheap. You run the encoder once, cache the features, and train only the head.
The trade-off is that a probe can underrate features that are useful but not linearly separable. It can also overrate a model on datasets where the classes happen to be easy to separate.
| Protocol | Trains encoder | Needs labels | What it measures |
|---|---|---|---|
| Zero-shot | No | No | Image-text alignment on the task |
| Linear probe | No | Yes | Linear separability of image features |
| Fine-tuning | Yes | Yes | Best achievable accuracy after adaptation |
Implementing a linear probe
The recipe is to extract features once, then fit a classifier. The code below uses Hugging Face CLIP and scikit-learn. It assumes you have lists of training and test images with integer labels.
import numpy as np
import torch
import torch.nn.functional as F
from sklearn.linear_model import LogisticRegression
from transformers import CLIPModel, CLIPProcessor
device = "cuda" if torch.cuda.is_available() else "cpu"
model = CLIPModel.from_pretrained("openai/clip-vit-base-patch32").to(device).eval()
processor = CLIPProcessor.from_pretrained("openai/clip-vit-base-patch32")
@torch.no_grad()
def extract_features(images, batch_size=64):
"""Return an (N, dim) array of L2-normalized image embeddings."""
chunks = []
for start in range(0, len(images), batch_size):
batch = images[start:start + batch_size]
inputs = processor(images=batch, return_tensors="pt").to(device)
feats = model.get_image_features(**inputs)
chunks.append(F.normalize(feats, dim=-1).cpu())
return torch.cat(chunks).numpy()
def linear_probe(train_images, train_labels, test_images, test_labels, C=0.316):
x_train = extract_features(train_images)
x_test = extract_features(test_images)
clf = LogisticRegression(C=C, max_iter=1000)
clf.fit(x_train, np.asarray(train_labels))
return clf.score(x_test, np.asarray(test_labels))Call linear_probe with lists of PIL images and integer labels. It returns test accuracy as a float.
Choosing the regularization strength
C in scikit-learn is the inverse of the L2 regularization strength: a smaller C means a stronger penalty. The CLIP paper tuned this value per dataset with a hyperparameter search on a validation split. The default of 0.316 above is only a starting point. Selecting C on the test set leaks information and inflates the result. Hold out a validation split, or use cross-validation on the training set.
Probing with few labels
A linear probe is also used in the few-shot setting, where you have only 1, 2, 4, 8, or 16 labeled examples per class. Two things change:
- With very few examples, strong regularization matters more, because the classifier can overfit easily.
- You should repeat the experiment over several random draws of the examples and report the mean and spread. A single draw can be misleading.
The CLIP paper found that zero-shot CLIP matched the average of a linear probe trained on a handful of labeled examples per class. It took more labeled examples before a probe on the same features overtook zero-shot. Treat that number as a rough orientation. It depends on the dataset and model size.
Common errors
- Forgetting
eval()andno_grad. Dropout or gradient tracking changes the features or wastes memory. Extract features with the model in evaluation mode. - Mismatched preprocessing. Use the model's own processor. Resize, crop, and normalization constants differ between models.
- Probing unnormalized features without noticing. Logistic regression is sensitive to feature scale. Normalizing, as above, keeps results consistent with how CLIP uses the embeddings. If you compare normalized and raw features, state which you used.
- Tuning on the test set. This is the most common source of inflated numbers.
- Comparing probes with different settings. Different
Cranges, solvers, or split sizes make model comparisons unreliable. Keep the probe recipe fixed across models. - Probing the projected embedding versus the pre-projection features.
get_image_featuresreturns the projected embedding, the one in the joint space. The vision backbone's pooled output, before the projection, can give different probe accuracy. Pick one and report it.
Reading the results
Interpret probe numbers with some care.
- Compare against a baseline. A probe on random-initialized encoder features, or on an ImageNet-supervised model, tells you whether CLIP's features add anything.
- Look across many datasets. A model that wins on one dataset may lose on another. The CLIP paper evaluated on dozens of datasets and averaged, which reduces this risk.
- Check the gap to zero-shot. If the probe is much better than zero-shot on a dataset, the image features hold class information that the prompts fail to reach. That points to prompt design or to domain words the text encoder handles poorly. If zero-shot is close to the probe, the text side is aligned well for that task.
- Remember distribution shift. The CLIP paper reported that zero-shot CLIP lost less accuracy under natural distribution shift than ImageNet-supervised models. A probe trained on one distribution can inherit that distribution's quirks, so a high in-distribution score does not guarantee robustness.
Connecting back to the loss
The contrastive loss never sees class labels. The probe works anyway because pushing matching image-text pairs together and mismatched pairs apart forces the image encoder to place semantically similar images near each other. Captions mention objects, scenes, and attributes, so those concepts become directions in the embedding space. A linear classifier can then read them out.
Summary of when to use each protocol
- Use zero-shot when you have no labels, or want to test prompt-based use.
- Use a linear probe when you want a cheap, fair comparison of frozen image features, or when you have a modest labeled set and want a fast classifier.
- Use fine-tuning when you need the highest accuracy and can afford to risk drifting from the pretrained features.
Exercise
You train a linear probe on CLIP image features and get 91% accuracy, while zero-shot CLIP on the same dataset gets 70%. You then pick the regularization value C that gave the best accuracy on the test set. Name two problems with how you are interpreting or producing the numbers, and say what the 21-point gap suggests.
Show answer
First, choosing C on the test set leaks test information, so 91% is optimistic. Select C on a validation split or by cross-validation on the training data, then report test accuracy once. Second, the probe uses labeled training data and zero-shot does not, so the two numbers measure different things and should not be compared as if the setups were equal. The gap suggests the image features already separate the classes well, but the text prompts do not reach that information. Improving class names, prompt templates, or prompt ensembling is a likely way to narrow it.
Exercise
Why must the image encoder stay frozen in a linear-probe evaluation, and what would you lose by unfreezing it?
Show answer
The probe is meant to measure the quality of the pretrained features. If the encoder is updated, the result mixes feature quality with the effect of the new training, so you can no longer tell which one produced the accuracy. Unfreezing is fine-tuning, which is a different protocol with a different purpose.