Lab 5: Retrieval in a Toy CLIP Space
Rank images and texts in 2-D, then a gender–occupation probe.
Work in a Jupyter notebook. This lab uses a constructed CLIP-like space, not OpenAI weights, so it runs offline. Download toy_clip.csv.
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from pathlib import Path
df = pd.read_csv(Path("toy_clip.csv"))
# columns: name, kind (image|text), x, y
Each concept (cat, dog, nurse, ceo, …) has an image row and a text row in 2-D.
def vecs(kind):
sub = df[df.kind == kind]
return {row["name"]: np.array([row.x, row.y], float) for _, row in sub.iterrows()}
img, txt = vecs("image"), vecs("text")
def cosine(a, b):
return float(np.dot(a, b) / (np.linalg.norm(a) * np.linalg.norm(b)))
1. Retrieval
-
For query text
"cat", rank all images by cosine. Iscatfirst? -
For query image
"ceo", rank all texts. Print the top three. -
Build the full image-to-text cosine matrix. Heatmap it. Comment on the diagonal.
2. Zero-shot
Treat texts cat, dog, nurse, ceo as class prompts.
-
Classify image
dogby nearest prompt. -
Classify image
nursetwice: prompts as above, then replacenursewith the prompt namewomanif present, or add a fake prompt vector by copyingnurse’s text shifted towardsheif you added one in the CSV. The CSV already includesmanandwomantext rows. Comparenurseandceoimages against promptsmanvswoman. Which occupation sits closer toman?
3. Robustness
-
Add noise:
img["cat"] + np.array([0.8, -0.8]). Does retrieval still return cat? -
Write five lines: what CLIP would do that this CSV fakes, what BLIP adds (generation), one bias number you measured, and one limitation of 2-D toys.
Scatter-plot all points, color by kind, annotate name.