CDiscover · discover.image_text
Image–text search and zero-shot labels (CLIP, SigLIP)
Which of my words fit each image, which images match a text, and which images look alike?
Puts images and texts in one space with a pretrained image–text model (CLIP ViT-B/32 or SigLIP base/16, written out in Python and R from the published weights). Label images with your own words (zero-shot, with editable prompt templates averaged together), rank the images for a text, or find each image's most similar images. Shows scores, the top results per image or query, how much the labels depend on the wording, and agreement with known labels; the image embeddings can be saved as columns. Runs on this computer after a one-time download you approve (about 607 MB or 815 MB).
A real result
Example “Colors zero shot”, recorded in both engines. In the app, “Try this example” loads it into Analyze.
17 images into 4 labels; most common red (29%); accuracy 100% against color.
- Images
- 17
- Labels
- 4
- Mean score of the chosen label
- 0.9999
- Accuracy
- 100.0%
- Macro F1
- 1
Plots
View data
| File | Label | Image | Rank | Score |
|---|---|---|---|---|
| red_square_2.png | red | 434e2ec8acd8699a94f5db3be0f41ab8101c8157f523a05e1db05a7ea975a55f | 1 | 1.0000 |
| red_square_1.png | red | c2da9720dabe35c5e764c0a9e57df8638d67b65ccc85bc35c96446af38526376 | 2 | 1.0000 |
| red_circle_1.png | red | 9a3e76d2849e45190bae64fd1b648905c4eab576a5511c82985daa44ff7a25eb | 3 | 1.0000 |
| red_circle_1_copy.png | red | 9a3e76d2849e45190bae64fd1b648905c4eab576a5511c82985daa44ff7a25eb | 4 | 1.0000 |
| red_circle_2.png | red | 5fa652ab46822e575326d94ba482a845383141f4a34132c22d95b069024f6321 | 5 | 0.9999 |
| green_square_1.png | green | 8ca99c38a1f6c433614960aff2a8d7432eeeebd3654348c9988b0f9ba30e32c7 | 1 | 1.0000 |
| green_circle_1.png | green | 33a634b9fb3326da6edf75bc17755bbf236a4cf0e7b2349a6dbbd4790ad909e1 | 2 | 0.9999 |
| green_square_2.png | green | f0eb0253e1fbd26b61ce7c9415da8fc11b7af80d1ba096256ce92f1afb3a2a21 | 3 | 0.9999 |
| green_circle_2.png | green | c125e99541f94beca9d2d051595926fe9131dcab8e707e6fa273c7785cc88f13 | 4 | 0.9995 |
| blue_circle_2.png | green | 727f2dc4b0383e83cb77fb364b8a04e06695160ddfaf71a979346cb38448a808 | 5 | 3.616e-5 |
| blue_square_1.png | blue | bcf2583948f23afadb9eedbe7ed773103107e11d79522ae2bd5a1b8062fa7380 | 1 | 1.0000 |
| blue_circle_1.png | blue | ac9b3dde099f3243d0b992fc9bac26d3384e28638afc7a82efa35c622ce9c12f | 2 | 1.0000 |
| blue_square_2.png | blue | 77c412ebdfceb00bc8213a6cd85286eb2bc53778a6822bc3ef09293ffec249d9 | 3 | 0.9999 |
| blue_circle_2.png | blue | 727f2dc4b0383e83cb77fb364b8a04e06695160ddfaf71a979346cb38448a808 | 4 | 0.9992 |
| green_circle_2.png | blue | c125e99541f94beca9d2d051595926fe9131dcab8e707e6fa273c7785cc88f13 | 5 | 0.0001 |
| yellow_square_1.png | yellow | c37818ace5a34c68b5903a7aee70236022e599dc89a78dea4f5cbfa8cf53d3d3 | 1 | 1.0000 |
| yellow_square_2.png | yellow | fa76bf14a0ba2ef56e8166402e88d235460ce6ea91d115ad87bbc8ec9a500ed0 | 2 | 1.0000 |
| yellow_circle_1.png | yellow | d7650e4851900cbbd716ef730decc1f99ed2da6e97b937bf8ce0a7bf5a6a64e4 | 3 | 1.0000 |
| yellow_circle_2.png | yellow | 604a35801ef2627525250e1f7dd474fa9f79e7f5e8ca8452de2cceb6ee67040f | 4 | 0.9999 |
| green_circle_2.png | yellow | c125e99541f94beca9d2d051595926fe9131dcab8e707e6fa273c7785cc88f13 | 5 | 8.919e-5 |
View data
| Images | Label |
|---|---|
| 5 | red |
| 4 | green |
| 4 | blue |
| 4 | yellow |
View data
| Score |
|---|
| 1.0000 |
| 1.0000 |
| 0.9999 |
| 1.0000 |
| 1.0000 |
| 1.0000 |
| 1.0000 |
| 1.0000 |
| 0.9999 |
| 1.0000 |
| 0.9995 |
| 0.9999 |
| 0.9992 |
| 0.9999 |
| 0.9999 |
| 1.0000 |
| 1.0000 |
View data
| color | Zero-shot label |
|---|---|
| red | red |
| red | red |
| green | green |
| green | green |
| blue | blue |
| blue | blue |
| yellow | yellow |
| yellow | yellow |
| red | red |
| red | red |
| green | green |
| green | green |
| blue | blue |
| blue | blue |
| yellow | yellow |
| yellow | yellow |
| red | red |
View data
| Zero-shot label | PC 1 | PC 2 |
|---|---|---|
| red | 0.3347 | 0.2984 |
| red | −0.2839 | 0.2952 |
| green | 0.1721 | 0.1685 |
| green | −0.3015 | 0.1529 |
| blue | 0.2475 | 0.0618 |
| blue | −0.2808 | 0.0773 |
| yellow | 0.1769 | 0.1547 |
| yellow | −0.3399 | 0.1976 |
| red | 0.3175 | −0.1227 |
| red | −0.2224 | −0.0265 |
| green | 0.2007 | −0.2935 |
| green | −0.2048 | −0.2399 |
| blue | 0.2314 | −0.3410 |
| blue | −0.2016 | −0.2745 |
| yellow | 0.1155 | −0.2591 |
| yellow | −0.2960 | −0.1475 |
| red | 0.3347 | 0.2984 |
Assumptions
- Scores are not probabilities — The scores rank images and labels well but aren't calibrated; check them against known labels before acting on a cutoff.
- Labels depend on wording — Labels and search results change with the words used; try a few wordings or templates.
- Learned from web images — The model learned from web images and alt text; it can repeat their stereotypes and miss specialized images such as scans, documents or satellite views.
Labels
| Label | Images | Share of images | Mean score (labeled images) | Known | Precision | Recall | F1 |
|---|---|---|---|---|---|---|---|
| red | 5 | 0.2941 | 1.0000 | 5 | 1 | 1 | 1 |
| green | 4 | 0.2353 | 0.9998 | 4 | 1 | 1 | 1 |
| blue | 4 | 0.2353 | 0.9997 | 4 | 1 | 1 | 1 |
| yellow | 4 | 0.2353 | 1.0000 | 4 | 1 | 1 | 1 |
Each label is embedded as a photo of a {label}. with the label filled in. Scores are softmax probabilities across the labels (they sum to 1).
Top labels per image
| Row | File | Label 1 | Score 1 | Label 2 | Score 2 | Label 3 | Score 3 | Label 4 | Score 4 | Known label |
|---|---|---|---|---|---|---|---|---|---|---|
| 1 | red_circle_1.png | red | 1.0000 | blue | 2.575e-5 | yellow | 4.918e-6 | green | 1.101e-6 | red |
| 2 | red_square_1.png | red | 1.0000 | blue | 7.675e-7 | yellow | 4.752e-7 | green | 4.568e-7 | red |
| 3 | green_circle_1.png | green | 0.9999 | red | 3.881e-5 | blue | 3.725e-5 | yellow | 7.679e-6 | green |
| 4 | green_square_1.png | green | 1.0000 | red | 1.266e-5 | blue | 1.134e-5 | yellow | 2.463e-6 | green |
| 5 | blue_circle_1.png | blue | 1.0000 | red | 4.510e-5 | yellow | 2.744e-6 | green | 2.041e-6 | blue |
| 6 | blue_square_1.png | blue | 1.0000 | red | 1.483e-5 | green | 1.156e-6 | yellow | 9.401e-7 | blue |
| 7 | yellow_circle_1.png | yellow | 1.0000 | red | 1.210e-5 | blue | 7.562e-6 | green | 3.706e-6 | yellow |
| 8 | yellow_square_1.png | yellow | 1.0000 | green | 1.652e-6 | red | 1.530e-6 | blue | 5.983e-7 | yellow |
| 9 | red_circle_2.png | red | 0.9999 | yellow | 5.776e-5 | blue | 3.343e-5 | green | 7.213e-6 | red |
| 10 | red_square_2.png | red | 1.0000 | yellow | 7.082e-7 | blue | 6.591e-7 | green | 3.169e-7 | red |
| 11 | green_circle_2.png | green | 0.9995 | red | 0.0003 | blue | 0.0001 | yellow | 8.919e-5 | green |
| 12 | green_square_2.png | green | 0.9999 | red | 8.516e-5 | blue | 3.818e-5 | yellow | 2.244e-5 | green |
| 13 | blue_circle_2.png | blue | 0.9992 | red | 0.0007 | yellow | 7.249e-5 | green | 3.616e-5 | blue |
| 14 | blue_square_2.png | blue | 0.9999 | red | 0.0001 | yellow | 2.006e-5 | green | 5.698e-6 | blue |
| 15 | yellow_circle_2.png | yellow | 0.9999 | red | 4.148e-5 | green | 1.243e-5 | blue | 7.390e-6 | yellow |
| 16 | yellow_square_2.png | yellow | 1.0000 | red | 2.760e-6 | green | 1.148e-6 | blue | 8.616e-7 | yellow |
| 17 | red_circle_1_copy.png | red | 1.0000 | blue | 2.575e-5 | yellow | 4.918e-6 | green | 1.101e-6 | red |
- 1 image file(s) couldn't be read and are left out (first: clip_images/not_there.png).
- Model: CLIP ViT-B/32 (DataComp-1B). Each image and text is embedded on its own in double precision, so results never depend on what else is in the run.
17 images into 4 labels; most common red (29%); accuracy 100% against color.
- Images
- 17
- Labels
- 4
- Mean score of the chosen label
- 0.9999
- Accuracy
- 100.0%
- Macro F1
- 1
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Scores are not probabilities — The scores rank images and labels well but aren't calibrated; check them against known labels before acting on a cutoff.
- Labels depend on wording — Labels and search results change with the words used; try a few wordings or templates.
- Learned from web images — The model learned from web images and alt text; it can repeat their stereotypes and miss specialized images such as scans, documents or satellite views.
Labels
| Label | Images | Share of images | Mean score (labeled images) | Known | Precision | Recall | F1 |
|---|---|---|---|---|---|---|---|
| red | 5 | 0.2941 | 1.0000 | 5 | 1 | 1 | 1 |
| green | 4 | 0.2353 | 0.9998 | 4 | 1 | 1 | 1 |
| blue | 4 | 0.2353 | 0.9997 | 4 | 1 | 1 | 1 |
| yellow | 4 | 0.2353 | 1.0000 | 4 | 1 | 1 | 1 |
Each label is embedded as a photo of a {label}. with the label filled in. Scores are softmax probabilities across the labels (they sum to 1).
Top labels per image
| Row | File | Label 1 | Score 1 | Label 2 | Score 2 | Label 3 | Score 3 | Label 4 | Score 4 | Known label |
|---|---|---|---|---|---|---|---|---|---|---|
| 1 | red_circle_1.png | red | 1.0000 | blue | 2.575e-5 | yellow | 4.918e-6 | green | 1.101e-6 | red |
| 2 | red_square_1.png | red | 1.0000 | blue | 7.675e-7 | yellow | 4.752e-7 | green | 4.568e-7 | red |
| 3 | green_circle_1.png | green | 0.9999 | red | 3.881e-5 | blue | 3.725e-5 | yellow | 7.679e-6 | green |
| 4 | green_square_1.png | green | 1.0000 | red | 1.266e-5 | blue | 1.134e-5 | yellow | 2.463e-6 | green |
| 5 | blue_circle_1.png | blue | 1.0000 | red | 4.510e-5 | yellow | 2.744e-6 | green | 2.041e-6 | blue |
| 6 | blue_square_1.png | blue | 1.0000 | red | 1.483e-5 | green | 1.156e-6 | yellow | 9.401e-7 | blue |
| 7 | yellow_circle_1.png | yellow | 1.0000 | red | 1.210e-5 | blue | 7.562e-6 | green | 3.706e-6 | yellow |
| 8 | yellow_square_1.png | yellow | 1.0000 | green | 1.652e-6 | red | 1.530e-6 | blue | 5.983e-7 | yellow |
| 9 | red_circle_2.png | red | 0.9999 | yellow | 5.776e-5 | blue | 3.343e-5 | green | 7.213e-6 | red |
| 10 | red_square_2.png | red | 1.0000 | yellow | 7.082e-7 | blue | 6.591e-7 | green | 3.169e-7 | red |
| 11 | green_circle_2.png | green | 0.9995 | red | 0.0003 | blue | 0.0001 | yellow | 8.919e-5 | green |
| 12 | green_square_2.png | green | 0.9999 | red | 8.516e-5 | blue | 3.818e-5 | yellow | 2.244e-5 | green |
| 13 | blue_circle_2.png | blue | 0.9992 | red | 0.0007 | yellow | 7.249e-5 | green | 3.616e-5 | blue |
| 14 | blue_square_2.png | blue | 0.9999 | red | 0.0001 | yellow | 2.006e-5 | green | 5.698e-6 | blue |
| 15 | yellow_circle_2.png | yellow | 0.9999 | red | 4.148e-5 | green | 1.243e-5 | blue | 7.390e-6 | yellow |
| 16 | yellow_square_2.png | yellow | 1.0000 | red | 2.760e-6 | green | 1.148e-6 | blue | 8.616e-7 | yellow |
| 17 | red_circle_1_copy.png | red | 1.0000 | blue | 2.575e-5 | yellow | 4.918e-6 | green | 1.101e-6 | red |
- 1 image file(s) couldn't be read and are left out (first: clip_images/not_there.png).
- Model: CLIP ViT-B/32 (DataComp-1B). Each image and text is embedded on its own in double precision, so results never depend on what else is in the run.
Do it in CodeSplash Run it on your own data. It's in the Experimental lane in the app.
Worked examples in the app
- Colors zero shotclip_images · image: path · truth: color
- Shapes two templates siglipclip_images · image: path · truth: shape
- Labels from known levelsclip_images · caption: caption · image: path · truth: shape
- Text search queriesclip_images · image: path
- Caption recall siglipclip_images · caption: caption · image: path
- Image neighborsclip_images · image: path
- Image query rowsclip_images · image: path · truth: color
- Invalid one labelclip_images · image: path
In the guides
Where it sits in the decision guides
- Multimodal data exploration (text, image, video) · DS & ML Decision Guide · Describe — summarize and visualize
- Representation learning (autoencoders, contrastive) · DS & ML Decision Guide · Discover — find structure without labels
What you need
- Image pathcategorical · 1 column
- A column of image files, such as the path column of an image folder added in Data. Files stay where they are.
- Known labelscategorical · 0–1 column · 2–50 levels
- Optional: the right label of each image. Zero-shot labels are then scored against it; empty labels use its levels.
- Captionscategorical · 0–1 column
- Optional: a text written for each image. Search then ranks each caption's own image, and CLIPScore measures the fit.
Choices you make
statistics
- Modeldefault clip
The pretrained image–text model. Both run on this computer after a one-time download that asks first.
- CLIP ViT-B/32 (DataComp-1B, about 607 MB)(default) — Scores across labels sum to 1 (softmax). MIT license; trained by LAION on DataComp-1B web image–text pairs.
- SigLIP base/16 (about 815 MB) — Scores each image–label pair on its own (sigmoid), so several labels can fit. Apache-2.0; trained on Google's WebLI.
- Taskdefault zero_shot
Label images with your words, find the images that match a text, or find images that look alike.
- Label images from your words(default) — Each image gets the label whose sentence fits it best; no training data needed.
- Find images from a text — Ranks every image by how well it matches each search text (or each image's own caption).
- Find similar images — Ranks the other images by how similar they look to each query image.
options
- Labelsdefault —
Labels separated by commas or semicolons, e.g. cat, dog, car. Empty uses the levels of the known-label column.
- Prompt templatesdefault a photo of a {label}.
Sentences with {label}, separated by semicolons. Each label's sentences are embedded and averaged.
- Search textsdefault —
Texts to search for, separated by semicolons. Empty uses each image's caption (needs a caption column).
- Query rowsdefault —
Row numbers of the query images, separated by commas. Empty finds the nearest images of every image.
- Results per querydefault 5
How many top images (or labels) to list for each query, label or image.
Checks and remedies
CodeSplash checks each testable assumption on every run and shows the result on the card; premises the data can’t test are marked. If a check fails, these are the ways forward.
Scores are not probabilities
CLIP's softmax and SigLIP's sigmoid scores rank well but aren't calibrated; check them against known labels before acting on a cutoff.
Labels depend on wording
Zero-shot labels change with the label words and templates; compare several templates and watch the agreement.
Learned from web images
The models learned from web images and alt text: they can repeat its stereotypes and miss specialized images (scans, documents, satellite views).
What it reports
- n_rows
- Rows read, images embedded, files that couldn't be decoded, the task and how many numbers each embedding has.
- n_images
- Rows read, images embedded, files that couldn't be decoded, the task and how many numbers each embedding has.
- n_unreadable
- Rows read, images embedded, files that couldn't be decoded, the task and how many numbers each embedding has.
- encoder
- A pair of networks trained on web image–caption pairs so that an image and a text about it land close together in one vector space.
- mode
- Rows read, images embedded, files that couldn't be decoded, the task and how many numbers each embedding has.
- dim
- Rows read, images embedded, files that couldn't be decoded, the task and how many numbers each embedding has.
- logit_scale
- A pair of networks trained on web image–caption pairs so that an image and a text about it land close together in one vector space.
- logit_bias
- A CLIP-like image–text model trained with a sigmoid loss: it scores each image–text pair on its own instead of across a batch.
- n_labels
- Each image gets the label whose sentence, like 'a photo of a {label}.', fits it best; no labeled training images are needed.
- n_templates
- Each label is written into several sentences; their unit embeddings are averaged into one label vector, which steadies the labels.
- labels_text
- Each image gets the label whose sentence, like 'a photo of a {label}.', fits it best; no labeled training images are needed.
- mean_top_score
- CLIP: a softmax over the labels of 100 × cosine. SigLIP: a sigmoid of scale × cosine + bias per pair. Neither is calibrated.
- mean_margin
- CLIP: a softmax over the labels of 100 × cosine. SigLIP: a sigmoid of scale × cosine + bias per pair. Neither is calibrated.
- template_agreement
- Each label is written into several sentences; their unit embeddings are averaged into one label vector, which steadies the labels.
- n_evaluated
- Accuracy, macro F1 and balanced accuracy of the zero-shot labels on images whose known label is one of the labels.
- accuracy
- Accuracy, macro F1 and balanced accuracy of the zero-shot labels on images whose known label is one of the labels.
- macro_f1
- Accuracy, macro F1 and balanced accuracy of the zero-shot labels on images whose known label is one of the labels.
- balanced_accuracy
- Accuracy, macro F1 and balanced accuracy of the zero-shot labels on images whose known label is one of the labels.
- n_queries
- Every image is ranked by the cosine similarity of its embedding to a search text's embedding, best match first.
- recall_at_1
- Share of captions whose own image ranks in the top k when every image is ranked for that caption; the median rank sums it up.
- recall_at_5
- Share of captions whose own image ranks in the top k when every image is ranked for that caption; the median rank sums it up.
- recall_at_10
- Share of captions whose own image ranks in the top k when every image is ranked for that caption; the median rank sums it up.
- median_rank
- Share of captions whose own image ranks in the top k when every image is ranked for that caption; the median rank sums it up.
- clipscore_mean
- 2.5 × max(cosine of an image and its caption, 0): how well a caption fits its image, without reference captions.
- mean_nn_similarity
- The other images ranked by the cosine similarity of their embeddings to a query image's; identical files score 1.
Per group, level or term: emb_check[<dim>], n[<label>], share[<label>], mean_score[<label>], f1[<label>], accuracy_template[<template>], match_row[<query>.<rank>], match_score[<query>.<rank>], neighbor_row[<query>.<rank>], neighbor_similarity[<query>.<rank>]
Python and R
Python and R agree to 6 decimals (relative tolerance 1e-9). Python uses torch, numpy, pandas, codesplash; R uses torch, stringi, nanoparquet, codesplashr.
Default traps between the two languages
- Both engines run the same written-out towers (codesplash.imagetext ↔ codesplashr imagetext_*.R) on LibTorch in double precision on one thread, from the same float32 weights and the same decoded image tensors; the packages ship different LibTorch builds, so embeddings agree to about 1e-15 and scores to about 1e-13 rather than exactly.
- Rankings treat scores within 1e-10 as ties broken by row order, so rounding never reorders results between engines. Identical files (the same content hash) always tie.
- Without the downloaded weights the run stops with CS_WEIGHTS_MISSING in both engines; nothing is downloaded automatically.
The exact script CodeSplash ran for example “Colors zero shot” · Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Image–text search and zero-shot labels (CLIP, SigLIP)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.image_text 1.0.0 · spec 85dbfef898a61423
# Dataset: clip_images (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import os
import numpy as np
import pandas as pd
import codesplash as cs
from codesplash import ml as csml
from codesplash.imagetext import discover as it # prompts, scores, rankings (twin: codesplashr cs_imagetext_*)
from codesplash.ml import embed as csembed # order-sensitive checksums (twin: cs_ml_checksum)
from codesplash.text import search as zs # label lists and agreement figures (twin: cs_search_* / cs_zero_shot_classification)
from codesplash.imagetext import clip as tower # CLIP ViT-B/32 written out on torch (twin: cs_clip_*)
# %% Data (rows with an image path; known labels and captions may be missing)
IMAGE = "path"
TRUTH = "color"
CAPTION = None
df = pd.read_parquet("tests/parity/fixtures/clip_images.parquet", columns=["path", "color"])
n_input = len(df)
df = df[df[IMAGE].notna()]
warnings = []
if n_input - len(df):
warnings.append(cs.cs_warning("CS_W_ROWS_DROPPED", dropped=n_input - len(df), total=n_input))
if not len(df):
cs.cs_error("CS_E_NO_ROWS")
# %% Media files (image column path)
# In the app the files were decoded once into float32 arrays (media.json in the run folder). Elsewhere they are
# decoded here the same way: PNG and WAV give the app's values; JPEG, MP3 and other lossy files can differ slightly.
import json as _media_json
from codesplash import media as cs_media
media = cs_media.setup(_media_json.loads("{\"ids_column\":\"media_id\",\"kind\":\"image\",\"path_column\":\"path\",\"role\":\"image\",\"transform\":{\"filter\":\"catmull_rom\",\"fit\":\"shorter_center_crop\",\"mode\":\"rgb\",\"normalize\":{\"mean\":[0.48145466,0.4578275,0.40821073],\"std\":[0.26862954,0.26130258,0.27577711]},\"size\":[224,224]}}"), "target/academy-parity/run-8142/discover.image_text/colors_zero_shot/out-python", df, "tests/parity/fixtures/clip_images.parquet")
media_ids = cs_media.ids_of(media, df)
# %% Images the host could decode (unreadable files are left out)
status = cs_media.status(media, media_ids)
ok = [k for k, s in enumerate(status) if s is None]
bad = [k for k, s in enumerate(status) if s is not None]
n_unreadable = len(bad)
if not ok:
cs.cs_error("CS_E_MEDIA_DECODE", file=str(df[IMAGE].iloc[bad[0]]), reason=str(status[bad[0]]))
if bad:
warnings.append(f"{len(bad)} image file(s) couldn't be read and are left out (first: {df[IMAGE].iloc[bad[0]]}).")
df = df.iloc[ok]
ids = [media_ids[k] for k in ok]
rows = df.index.to_numpy().astype(np.int64) # 0-based positions in the analysis input
n = len(rows)
files = [os.path.basename(str(p)) for p in df[IMAGE].tolist()]
truth = None if TRUTH is None else [None if pd.isna(v) else str(v) for v in df[TRUTH].tolist()]
captions = None if CAPTION is None else [None if pd.isna(v) else str(v) for v in df[CAPTION].tolist()]
truth_levels = [] if truth is None else sorted(set(t for t in truth if t is not None))
# %% Task settings (checked before the model loads)
MODE = "zero_shot"
KIND = "clip"
TOP_K = int(5)
LABELS, TEMPLATES, QUERIES, QPOS = [], [], [], []
if MODE == "zero_shot":
LABELS = zs.split_labels("red, green, blue, yellow")
if not LABELS and truth_levels:
LABELS = list(truth_levels)
if len(LABELS) < 2:
cs.cs_error("CS_E_INVALID_OPTION", option="Labels", allowed="at least two labels separated by commas", value=", ".join(LABELS) or "(empty)")
if len(set(LABELS)) < len(LABELS):
cs.cs_error("CS_E_INVALID_OPTION", option="Labels", allowed="distinct labels", value=", ".join(LABELS))
TEMPLATES = zs.split_list("a photo of a {label}.")
if not TEMPLATES or any(zs.LABEL_SLOT not in t for t in TEMPLATES):
cs.cs_error("CS_E_INVALID_OPTION", option="Prompt templates", allowed="sentences that each contain {label}", value="; ".join(TEMPLATES) or "(empty)")
elif MODE == "text_search":
QUERIES = zs.split_list("")
if not QUERIES and (captions is None or not any(c is not None for c in captions)):
cs.cs_error("CS_E_INVALID_OPTION", option="Search texts", allowed="at least one text, or a caption column", value="(empty)")
else:
if n < 2:
cs.cs_error("CS_E_TOO_FEW_ROWS", what="Finding similar images", min=2, n=n)
QROWS = it.parse_rows("")
if QROWS is None:
cs.cs_error("CS_E_INVALID_OPTION", option="Query rows", allowed="row numbers separated by commas", value="")
for q in QROWS:
hit = np.nonzero(rows + 1 == q)[0]
if not len(hit):
cs.cs_error("CS_E_INVALID_OPTION", option="Query rows", allowed="row numbers of readable images", value=str(q))
QPOS.append(int(hit[0]))
if not QPOS:
QPOS = list(range(n))
# %% Image embeddings (CLIP ViT-B/32, double precision, one image at a time)
if not tower.available():
cs.cs_error("CS_WEIGHTS_MISSING", model=tower.NAME)
model = tower.Model()
LOGIT_BIAS = float(getattr(model, "logit_bias", 0.0))
d = model.dim
E = np.zeros((n, d)) # unit rows, one image at a time; files read 32 at a time from the host's decoded tensors
for i in range(0, n, 32):
E[i:i + 32] = model.image_embed(cs_media.load(media, ids[i:i + 32])) # float32 (b, 3, 224, 224)
values = {
"n_rows": n_input, "n_images": n, "n_unreadable": n_unreadable, "encoder": tower.NAME, "mode": MODE, "dim": d,
"logit_scale": model.logit_scale, "logit_bias": LOGIT_BIAS if KIND == "siglip" else None,
"n_labels": None, "n_templates": None, "labels_text": None, "mean_top_score": None, "mean_margin": None,
"template_agreement": None, "n_evaluated": None, "accuracy": None, "macro_f1": None, "balanced_accuracy": None,
"n_queries": None, "recall_at_1": None, "recall_at_5": None, "recall_at_10": None, "median_rank": None,
"clipscore_mean": None, "mean_nn_similarity": None,
}
for j in range(min(5, d)):
values[f"emb_check[{j + 1}]"] = csembed.checksum(E[:, j], rows)
# %% Captions: CLIPScore = 2.5 · max(cos(image, caption), 0) (Hessel et al. 2021), on this model's embeddings
cap_pos = [] if captions is None else [k for k, c in enumerate(captions) if c is not None]
C = model.text_embed([captions[k] for k in cap_pos]) if cap_pos else None
if cap_pos:
values["clipscore_mean"] = float(np.mean(2.5 * np.maximum(np.sum(C * E[cap_pos], axis=1), 0.0)))
out = csml.out_dir("target/academy-parity/run-8142/discover.image_text/colors_zero_shot/out-python")
tables, charts, statistics, artifacts = [], [], [], []
gallery = {"media": [], "file": [], "group": [], "rank": [], "score": []}
def add_gallery(group, positions, scores):
for r, (k, s) in enumerate(zip(positions, scores), start=1):
gallery["media"].append(ids[k])
gallery["file"].append(files[k])
gallery["group"].append(group)
gallery["rank"].append(r)
gallery["score"].append(float(s))
# %% Zero-shot labels: each label's template sentences averaged (prompt ensemble)
L, T = len(LABELS), len(TEMPLATES)
P = model.text_embed(it.prompts(LABELS, TEMPLATES)) # (T·L, d), template-major
V = it.label_vectors(P, L, T)
S = it.scores(E @ V.T, KIND, model.logit_scale, LOGIT_BIAS) # images × labels
pred_idx = it.best(S)
pred = [LABELS[j] for j in pred_idx]
top = S[np.arange(n), pred_idx]
margin = it.margins(S)
per_template = [it.best(it.scores(E @ it.unit_rows(P[t * L:(t + 1) * L]).T, KIND, model.logit_scale, LOGIT_BIAS)) for t in range(T)]
values.update({"n_labels": L, "n_templates": T, "labels_text": ", ".join(LABELS), "mean_top_score": float(np.mean(top)),
"mean_margin": float(np.mean(margin)), "template_agreement": it.agreement(per_template)})
counts = {lab: sum(1 for p in pred if p == lab) for lab in LABELS}
for j, lab in enumerate(LABELS):
m = pred_idx == j
values[f"n[{lab}]"] = counts[lab]
values[f"share[{lab}]"] = counts[lab] / n
values[f"mean_score[{lab}]"] = float(np.mean(S[m, j])) if m.any() else None
ev = None
if truth is not None:
keep = [k for k, t in enumerate(truth) if t is not None and t in LABELS]
n_not_in = sum(1 for t in truth if t is not None and t not in LABELS)
if n_not_in:
warnings.append(f"{n_not_in} known label(s) are not among the labels and are left out of the agreement figures.")
if keep:
ev = zs.classification([truth[k] for k in keep], [pred[k] for k in keep], LABELS)
values.update({"n_evaluated": ev["n"], "accuracy": ev["accuracy"], "macro_f1": ev["macro_f1"], "balanced_accuracy": ev["balanced_accuracy"]})
for r in ev["rows"]:
values[f"f1[{r['label']}]"] = r["f1"]
if T > 1:
for t in range(T):
values[f"accuracy_template[{t + 1}]"] = float(np.mean([LABELS[per_template[t][k]] == truth[k] for k in keep]))
else:
warnings.append("No image has a known label that is one of the labels, so agreement can't be computed.")
never = [lab for lab in LABELS if counts[lab] == 0]
if never:
warnings.append(f"No image was given {', '.join(never)}.")
label_cols = [{"key": "label", "label": "Label", "type": "string"}, {"key": "images", "label": "Images", "type": "integer"},
{"key": "share", "label": "Share of images", "type": "number"}, {"key": "score", "label": "Mean score (labeled images)", "type": "number"}]
label_rows = [{"label": lab, "images": counts[lab], "share": counts[lab] / n, "score": values[f"mean_score[{lab}]"]} for lab in LABELS]
if ev:
label_cols += [{"key": "support", "label": "Known", "type": "integer"}, {"key": "precision", "label": "Precision", "type": "number"},
{"key": "recall", "label": "Recall", "type": "number"}, {"key": "f1", "label": "F1", "type": "number"}]
for row, r in zip(label_rows, ev["rows"]):
row.update({"support": r["support"], "precision": r["precision"], "recall": r["recall"], "f1": r["f1"]})
K = min(TOP_K, L)
img_cols = [{"key": "row", "label": "Row", "type": "integer"}, {"key": "file", "label": "File", "type": "string"}]
for r in range(K):
img_cols += [{"key": f"label_{r + 1}", "label": f"Label {r + 1}", "type": "string"}, {"key": f"score_{r + 1}", "label": f"Score {r + 1}", "type": "number"}]
if truth is not None:
img_cols.append({"key": "known", "label": "Known label", "type": "string"})
SHOW = min(n, 100)
img_rows = []
for k in range(SHOW):
rec = {"row": int(rows[k]) + 1, "file": files[k]}
for r, j in enumerate(it.top_k(S[k], K)):
rec[f"label_{r + 1}"] = LABELS[int(j)]
rec[f"score_{r + 1}"] = float(S[k, j])
if truth is not None:
rec["known"] = truth[k]
img_rows.append(rec)
note = "Scores are softmax probabilities across the labels (they sum to 1)." if KIND == "clip" else "Scores are SigLIP's pair scores (sigmoid); each label is scored on its own."
tables += [
{"key": "labels", "title": "Labels", "columns": label_cols, "rows": label_rows,
"note": f"Each label is embedded as {'; '.join(TEMPLATES)} with the label filled in" + (" and the sentences averaged. " if T > 1 else ". ") + note},
{"key": "images", "title": "Top labels per image", "columns": img_cols, "rows": img_rows,
"note": None if SHOW == n else f"The first {SHOW} of {n} images."},
]
for j, lab in enumerate(LABELS):
best_k = it.top_k(S[:, j], min(TOP_K, n))
add_gallery(lab, best_k, S[best_k, j])
charts.append(cs.chart("labels", "ngram-bars", "Images per label", {
"term": cs.col("Label", LABELS, kind="categorical"), "count": cs.col("Images", [counts[lab] for lab in LABELS])}, controls={"top": min(L, 50)}))
charts.append(cs.chart("top_scores", "histogram", "Score of the chosen label", {"x": cs.col("Score", top)}))
if ev:
keep = [k for k, t in enumerate(truth) if t is not None and t in LABELS]
charts.append(cs.chart("confusion", "confusion-matrix", f"Zero-shot labels against {TRUTH}", {
"actual": cs.col(TRUTH, [truth[k] for k in keep], kind="categorical", levels=LABELS),
"predicted": cs.col("Zero-shot label", [pred[k] for k in keep], kind="categorical", levels=LABELS)}))
statistics += [{"key": "n_labels", "label": "Labels", "value": L}, {"key": "mean_top_score", "label": "Mean score of the chosen label", "value": values["mean_top_score"]}]
if values["template_agreement"] is not None:
statistics.append({"key": "template_agreement", "label": "Same label under every template", "value": values["template_agreement"], "format": "percent"})
if ev:
statistics += [{"key": "accuracy", "label": "Accuracy", "value": values["accuracy"], "format": "percent"},
{"key": "macro_f1", "label": "Macro F1", "value": values["macro_f1"]}]
lab_frame = pd.DataFrame({"row": rows, "cluster": pred_idx.astype(np.int64), "label": pred, "score": top, "margin": margin})
lab_frame.to_parquet(os.path.join(out, "labels.parquet"), index=False)
score_frame = pd.DataFrame({"row": rows, **{lab: S[:, j] for j, lab in enumerate(LABELS)}})
score_frame.to_parquet(os.path.join(out, "scores.parquet"), index=False)
artifacts += [{"key": "labels", "path": os.path.join(out, "labels.parquet"), "format": "parquet"},
{"key": "scores", "path": os.path.join(out, "scores.parquet"), "format": "parquet"}]
top_label = max(LABELS, key=lambda lab: (counts[lab], -LABELS.index(lab)))
summary = f"{n} images into {L} labels; most common {top_label} ({counts[top_label] / n:.0%})" + (f"; accuracy {values['accuracy']:.0%} against {TRUTH}." if ev else ".")
# %% Ranked thumbnails, the embedding map and the saved embeddings
if gallery["media"]:
charts.insert(0, cs.chart("gallery", "image-ranking", "Top images" if MODE != "image_search" else "Query images and their nearest images", {
"media": cs.col("Image", gallery["media"], kind="categorical"),
"file": cs.col("File", gallery["file"], kind="categorical"),
"group": cs.col("Label" if MODE == "zero_shot" else ("Search text" if MODE == "text_search" else "Query"), gallery["group"], kind="categorical"),
"rank": cs.col("Rank", gallery["rank"]),
"score": cs.col("Score" if MODE != "image_search" else "Cosine similarity", gallery["score"]),
}, controls={"per_group": min(TOP_K + (1 if MODE == "image_search" else 0), 12)}))
if n >= 3:
Z = it.pca2(E)
color = pred if MODE == "zero_shot" else (truth if truth is not None else ["Images"] * n)
charts.append(cs.chart("map", "cluster-scatter", "Image map (first two principal components of the embeddings)", {
"x": cs.col("PC 1", Z[:, 0], "numeric"), "y": cs.col("PC 2", Z[:, 1], "numeric"),
"cluster": cs.col("Zero-shot label" if MODE == "zero_shot" else (TRUTH or "Group"), ["(missing)" if c is None else c for c in color], "categorical"),
}))
emb = pd.DataFrame({"row": rows, **{f"dim_{j + 1}": E[:, j] for j in range(d)}})
emb.to_parquet(os.path.join(out, "embedding.parquet"), index=False)
artifacts.insert(0, {"key": "embedding", "path": os.path.join(out, "embedding.parquet"), "format": "parquet"})
statistics.insert(0, {"key": "n_images", "label": "Images", "value": n, "format": "integer"})
if values["clipscore_mean"] is not None:
statistics.append({"key": "clipscore_mean", "label": "Mean CLIPScore (captions)", "value": values["clipscore_mean"]})
assumptions = [
{"key": "uncalibrated", "label": "Scores are not probabilities", "status": "info",
"detail": "The scores rank images and labels well but aren't calibrated; check them against known labels before acting on a cutoff."},
{"key": "prompt_wording", "label": "Labels depend on wording", "status": ("warn" if values["template_agreement"] is not None and values["template_agreement"] < 0.9 else "info"),
"detail": (f"{values['template_agreement']:.0%} of images get the same label under every template." if values["template_agreement"] is not None
else "Labels and search results change with the words used; try a few wordings or templates.")},
{"key": "web_training", "label": "Learned from web images", "status": "info",
"detail": "The model learned from web images and alt text; it can repeat their stereotypes and miss specialized images such as scans, documents or satellite views."},
]
cs.publish({
"title": "Image–text search and zero-shot labels (CLIP, SigLIP)",
"engine": cs.engine_info("torch", "numpy", "pandas"),
"n": n,
"summary": summary,
"statistics": statistics,
"tables": tables,
"assumptions": assumptions,
"charts": charts,
"values": values,
"warnings": warnings,
"notes": [f"Model: {tower.NAME}. Each image and text is embedded on its own in double precision, so results never depend on what else is in the run."],
"artifacts": artifacts,
})
The exact script CodeSplash ran for example “Colors zero shot” · R version 4.5.1 (2025-06-13)
# Image–text search and zero-shot labels (CLIP, SigLIP)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.image_text 1.0.0 · spec 85dbfef898a61423
# Dataset: clip_images (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr) # cs_clip_* / cs_siglip_* (towers on R torch), cs_imagetext_* (twins of codesplash.imagetext.discover)
# %% Data (rows with an image path; known labels and captions may be missing)
IMAGE <- "path"
TRUTH <- "color"
CAPTION <- NULL
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/clip_images.parquet", col_select = c("path", "color")))
n_input <- nrow(df)
df <- df[!is.na(df[[IMAGE]]), , drop = FALSE]
warnings <- list()
if (n_input - nrow(df) > 0) warnings <- c(warnings, cs_warning("CS_W_ROWS_DROPPED", dropped = n_input - nrow(df), total = n_input))
if (nrow(df) == 0) cs_error("CS_E_NO_ROWS")
# %% Media files (image column path)
# In the app the files were decoded once into float32 arrays (media.json in the run folder). Elsewhere they are
# decoded here the same way: PNG and WAV give the app's values; JPEG, MP3 and other lossy files can differ slightly.
media <- cs_media_setup(jsonlite::fromJSON("{\"ids_column\":\"media_id\",\"kind\":\"image\",\"path_column\":\"path\",\"role\":\"image\",\"transform\":{\"filter\":\"catmull_rom\",\"fit\":\"shorter_center_crop\",\"mode\":\"rgb\",\"normalize\":{\"mean\":[0.48145466,0.4578275,0.40821073],\"std\":[0.26862954,0.26130258,0.27577711]},\"size\":[224,224]}}", simplifyVector = FALSE), "target/academy-parity/run-8142/discover.image_text/colors_zero_shot/out-r", df,
"tests/parity/fixtures/clip_images.parquet")
media_ids <- cs_media_ids(media, df)
# %% Images the host could decode (unreadable files are left out)
status <- cs_media_status(media, media_ids)
ok <- which(is.na(status))
bad <- which(!is.na(status))
n_unreadable <- length(bad)
if (!length(ok)) cs_error("CS_E_MEDIA_DECODE", file = as.character(df[[IMAGE]][bad[1]]), reason = as.character(status[bad[1]]))
if (length(bad)) {
warnings <- c(warnings, sprintf("%d image file(s) couldn't be read and are left out (first: %s).", length(bad), as.character(df[[IMAGE]][bad[1]])))
}
input_pos <- as.integer(rownames(df)) - 1L
df <- df[ok, , drop = FALSE]
ids <- media_ids[ok]
rows <- input_pos[ok] # 0-based positions in the analysis input
n <- length(rows)
files <- basename(as.character(df[[IMAGE]]))
truth <- if (is.null(TRUTH)) NULL else as.character(df[[TRUTH]])
captions <- if (is.null(CAPTION)) NULL else as.character(df[[CAPTION]])
truth_levels <- if (is.null(truth)) character(0) else sort(unique(truth[!is.na(truth)]), method = "radix")
# %% Task settings (checked before the model loads)
MODE <- "zero_shot"
KIND <- "clip"
TOP_K <- as.integer(5)
LABELS <- character(0); TEMPLATES <- character(0); QUERIES <- character(0); QPOS <- integer(0)
if (MODE == "zero_shot") {
LABELS <- cs_search_split_labels("red, green, blue, yellow")
if (!length(LABELS) && length(truth_levels)) LABELS <- truth_levels
if (length(LABELS) < 2) {
cs_error("CS_E_INVALID_OPTION", option = "Labels", allowed = "at least two labels separated by commas",
value = if (length(LABELS)) paste(LABELS, collapse = ", ") else "(empty)")
}
if (anyDuplicated(LABELS)) cs_error("CS_E_INVALID_OPTION", option = "Labels", allowed = "distinct labels", value = paste(LABELS, collapse = ", "))
TEMPLATES <- cs_search_split_list("a photo of a {label}.")
if (!length(TEMPLATES) || !all(grepl("{label}", TEMPLATES, fixed = TRUE))) {
cs_error("CS_E_INVALID_OPTION", option = "Prompt templates", allowed = "sentences that each contain {label}",
value = if (length(TEMPLATES)) paste(TEMPLATES, collapse = "; ") else "(empty)")
}
} else if (MODE == "text_search") {
QUERIES <- cs_search_split_list("")
if (!length(QUERIES) && (is.null(captions) || all(is.na(captions)))) {
cs_error("CS_E_INVALID_OPTION", option = "Search texts", allowed = "at least one text, or a caption column", value = "(empty)")
}
} else {
if (n < 2) cs_error("CS_E_TOO_FEW_ROWS", what = "Finding similar images", min = 2, n = n)
QROWS <- cs_imagetext_parse_rows("")
if (is.null(QROWS)) cs_error("CS_E_INVALID_OPTION", option = "Query rows", allowed = "row numbers separated by commas", value = "")
for (q in QROWS) {
hit <- which(rows + 1L == q)
if (!length(hit)) cs_error("CS_E_INVALID_OPTION", option = "Query rows", allowed = "row numbers of readable images", value = as.character(q))
QPOS <- c(QPOS, hit[1])
}
if (!length(QPOS)) QPOS <- seq_len(n)
}
# %% Image embeddings (CLIP ViT-B/32, double precision, one image at a time)
if (!cs_clip_available()) cs_error("CS_WEIGHTS_MISSING", model = "CLIP ViT-B/32 (DataComp-1B)")
model <- cs_clip_load()
NAME <- "CLIP ViT-B/32 (DataComp-1B)"
embed_images <- function(x) cs_clip_image_embed(model, x)
embed_texts <- function(t) cs_clip_text_embed(model, t)
LOGIT_BIAS <- 0
d <- model$dim
E <- matrix(0, n, d) # unit rows, one image at a time; files read 32 at a time from the host's decoded tensors
for (i in seq(1L, n, by = 32L)) {
idx <- i:min(n, i + 31L)
E[idx, ] <- embed_images(cs_media_load(media, ids[idx])) # (b, 3, 224, 224), the host's float32 values
}
values <- list(
n_rows = n_input, n_images = n, n_unreadable = n_unreadable, encoder = NAME, mode = MODE, dim = d,
logit_scale = model$logit_scale, logit_bias = if (KIND == "siglip") LOGIT_BIAS else NA,
n_labels = NA, n_templates = NA, labels_text = NA, mean_top_score = NA, mean_margin = NA,
template_agreement = NA, n_evaluated = NA, accuracy = NA, macro_f1 = NA, balanced_accuracy = NA,
n_queries = NA, recall_at_1 = NA, recall_at_5 = NA, recall_at_10 = NA, median_rank = NA,
clipscore_mean = NA, mean_nn_similarity = NA
)
for (j in seq_len(min(5L, d))) values[[sprintf("emb_check[%d]", j)]] <- cs_ml_checksum(E[, j], rows)
# %% Captions: CLIPScore = 2.5 * max(cos(image, caption), 0) (Hessel et al. 2021), on this model's embeddings
cap_pos <- if (is.null(captions)) integer(0) else which(!is.na(captions))
C <- if (length(cap_pos)) embed_texts(captions[cap_pos]) else NULL
if (length(cap_pos)) values$clipscore_mean <- mean(2.5 * pmax(rowSums(C * E[cap_pos, , drop = FALSE]), 0))
out <- cs_ml_out_dir("target/academy-parity/run-8142/discover.image_text/colors_zero_shot/out-r")
tables <- list(); charts <- list(); statistics <- list(); artifacts <- list()
gallery <- list(media = character(0), file = character(0), group = character(0), rank = integer(0), score = numeric(0))
add_gallery <- function(group, positions, scores) {
gallery$media <<- c(gallery$media, ids[positions])
gallery$file <<- c(gallery$file, files[positions])
gallery$group <<- c(gallery$group, rep(group, length(positions)))
gallery$rank <<- c(gallery$rank, seq_along(positions))
gallery$score <<- c(gallery$score, as.numeric(scores))
}
# %% Zero-shot labels: each label's template sentences averaged (prompt ensemble)
L <- length(LABELS); NT <- length(TEMPLATES)
P <- embed_texts(cs_imagetext_prompts(LABELS, TEMPLATES)) # (T*L x d), template-major
V <- cs_imagetext_label_vectors(P, L, NT)
S <- cs_imagetext_scores(E %*% t(V), KIND, model$logit_scale, LOGIT_BIAS) # images x labels
pred_idx <- cs_imagetext_best(S)
pred <- LABELS[pred_idx]
top <- S[cbind(seq_len(n), pred_idx)]
margin <- cs_imagetext_margins(S)
per_template <- lapply(seq_len(NT), function(tt) {
Vt <- cs_imagetext_unit_rows(P[(tt - 1) * L + seq_len(L), , drop = FALSE])
cs_imagetext_best(cs_imagetext_scores(E %*% t(Vt), KIND, model$logit_scale, LOGIT_BIAS))
})
agree <- cs_imagetext_agreement(per_template)
values$n_labels <- L; values$n_templates <- NT; values$labels_text <- paste(LABELS, collapse = ", ")
values$mean_top_score <- mean(top); values$mean_margin <- mean(margin)
values$template_agreement <- if (is.null(agree)) NA else agree
counts <- vapply(LABELS, function(l) sum(pred == l), numeric(1), USE.NAMES = FALSE)
names(counts) <- LABELS
for (j in seq_len(L)) {
m <- pred_idx == j
values[[sprintf("n[%s]", LABELS[j])]] <- counts[[j]]
values[[sprintf("share[%s]", LABELS[j])]] <- counts[[j]] / n
values[[sprintf("mean_score[%s]", LABELS[j])]] <- if (any(m)) mean(S[m, j]) else NA
}
ev <- NULL
if (!is.null(truth)) {
keep <- which(!is.na(truth) & truth %in% LABELS)
n_not_in <- sum(!is.na(truth) & !(truth %in% LABELS))
if (n_not_in > 0) warnings <- c(warnings, sprintf("%d known label(s) are not among the labels and are left out of the agreement figures.", n_not_in))
if (length(keep)) {
ev <- cs_zero_shot_classification(truth[keep], pred[keep], LABELS)
values$n_evaluated <- ev$n; values$accuracy <- ev$accuracy; values$macro_f1 <- ev$macro_f1; values$balanced_accuracy <- ev$balanced_accuracy
for (r in ev$rows) values[[sprintf("f1[%s]", r$label)]] <- r$f1
if (NT > 1) for (tt in seq_len(NT)) values[[sprintf("accuracy_template[%d]", tt)]] <- mean(LABELS[per_template[[tt]][keep]] == truth[keep])
} else {
warnings <- c(warnings, "No image has a known label that is one of the labels, so agreement can't be computed.")
}
}
never <- LABELS[counts == 0]
if (length(never)) warnings <- c(warnings, sprintf("No image was given %s.", paste(never, collapse = ", ")))
label_cols <- list(list(key = "label", label = "Label", type = "string"), list(key = "images", label = "Images", type = "integer"),
list(key = "share", label = "Share of images", type = "number"), list(key = "score", label = "Mean score (labeled images)", type = "number"))
label_rows <- lapply(seq_len(L), function(j) list(label = LABELS[j], images = counts[[j]], share = counts[[j]] / n,
score = values[[sprintf("mean_score[%s]", LABELS[j])]]))
if (!is.null(ev)) {
label_cols <- c(label_cols, list(list(key = "support", label = "Known", type = "integer"), list(key = "precision", label = "Precision", type = "number"),
list(key = "recall", label = "Recall", type = "number"), list(key = "f1", label = "F1", type = "number")))
for (j in seq_along(label_rows)) {
r <- ev$rows[[j]]
label_rows[[j]] <- c(label_rows[[j]], list(support = r$support, precision = r$precision, recall = r$recall, f1 = r$f1))
}
}
K <- min(TOP_K, L)
img_cols <- list(list(key = "row", label = "Row", type = "integer"), list(key = "file", label = "File", type = "string"))
for (r in seq_len(K)) img_cols <- c(img_cols, list(list(key = sprintf("label_%d", r), label = sprintf("Label %d", r), type = "string"),
list(key = sprintf("score_%d", r), label = sprintf("Score %d", r), type = "number")))
if (!is.null(truth)) img_cols <- c(img_cols, list(list(key = "known", label = "Known label", type = "string")))
SHOW <- min(n, 100L)
img_rows <- lapply(seq_len(SHOW), function(k) {
rec <- list(row = rows[k] + 1L, file = files[k])
tk <- cs_imagetext_top_k(S[k, ], K)
for (r in seq_along(tk)) {
rec[[sprintf("label_%d", r)]] <- LABELS[tk[r]]
rec[[sprintf("score_%d", r)]] <- S[k, tk[r]]
}
if (!is.null(truth)) rec$known <- truth[k]
rec
})
note <- if (KIND == "clip") "Scores are softmax probabilities across the labels (they sum to 1)." else "Scores are SigLIP's pair scores (sigmoid); each label is scored on its own."
tables <- c(tables, list(
list(key = "labels", title = "Labels", columns = label_cols, rows = label_rows,
note = paste0("Each label is embedded as ", paste(TEMPLATES, collapse = "; "), " with the label filled in",
if (NT > 1) " and the sentences averaged. " else ". ", note)),
list(key = "images", title = "Top labels per image", columns = img_cols, rows = img_rows,
note = if (SHOW == n) NULL else sprintf("The first %d of %d images.", SHOW, n))
))
for (j in seq_len(L)) {
best_k <- cs_imagetext_top_k(S[, j], min(TOP_K, n))
add_gallery(LABELS[j], best_k, S[best_k, j])
}
charts <- c(charts, list(
cs_chart("labels", "ngram-bars", "Images per label",
list(term = cs_col("Label", LABELS, kind = "categorical"), count = cs_col("Images", unname(counts))), controls = list(top = min(L, 50L))),
cs_chart("top_scores", "histogram", "Score of the chosen label", list(x = cs_col("Score", top)))
))
if (!is.null(ev)) {
keep <- which(!is.na(truth) & truth %in% LABELS)
charts[[length(charts) + 1]] <- cs_chart("confusion", "confusion-matrix", sprintf("Zero-shot labels against %s", TRUTH),
list(actual = cs_col(TRUTH, truth[keep], kind = "categorical", levels = LABELS),
predicted = cs_col("Zero-shot label", pred[keep], kind = "categorical", levels = LABELS)))
}
statistics <- c(statistics, list(list(key = "n_labels", label = "Labels", value = L),
list(key = "mean_top_score", label = "Mean score of the chosen label", value = values$mean_top_score)))
if (!is.na(values$template_agreement)) {
statistics[[length(statistics) + 1]] <- list(key = "template_agreement", label = "Same label under every template", value = values$template_agreement, format = "percent")
}
if (!is.null(ev)) statistics <- c(statistics, list(list(key = "accuracy", label = "Accuracy", value = values$accuracy, format = "percent"),
list(key = "macro_f1", label = "Macro F1", value = values$macro_f1)))
nanoparquet::write_parquet(data.frame(row = as.integer(rows), cluster = as.integer(pred_idx - 1L), label = pred, score = top, margin = margin),
file.path(out, "labels.parquet"))
score_frame <- data.frame(row = as.integer(rows))
for (j in seq_len(L)) score_frame[[LABELS[j]]] <- S[, j]
nanoparquet::write_parquet(score_frame, file.path(out, "scores.parquet"))
artifacts <- c(artifacts, list(list(key = "labels", path = file.path(out, "labels.parquet"), format = "parquet"),
list(key = "scores", path = file.path(out, "scores.parquet"), format = "parquet")))
top_label <- LABELS[which.max(counts)]
summary <- paste0(sprintf("%d images into %d labels; most common %s (%s)", n, L, top_label, sprintf("%.0f%%", 100 * counts[[top_label]] / n)),
if (!is.null(ev)) sprintf("; accuracy %.0f%% against %s.", 100 * values$accuracy, TRUTH) else ".")
# %% Ranked thumbnails, the embedding map and the saved embeddings
if (length(gallery$media)) {
charts <- c(list(cs_chart("gallery", "image-ranking", if (MODE != "image_search") "Top images" else "Query images and their nearest images", list(
media = cs_col("Image", gallery$media, kind = "categorical"),
file = cs_col("File", gallery$file, kind = "categorical"),
group = cs_col(if (MODE == "zero_shot") "Label" else if (MODE == "text_search") "Search text" else "Query", gallery$group, kind = "categorical"),
rank = cs_col("Rank", as.numeric(gallery$rank)),
score = cs_col(if (MODE != "image_search") "Score" else "Cosine similarity", gallery$score)
), controls = list(per_group = min(TOP_K + (if (MODE == "image_search") 1L else 0L), 12L)))), charts)
}
if (n >= 3) {
Z <- cs_imagetext_pca2(E)
color <- if (MODE == "zero_shot") pred else if (!is.null(truth)) truth else rep("Images", n)
charts[[length(charts) + 1]] <- cs_chart("map", "cluster-scatter", "Image map (first two principal components of the embeddings)", list(
x = cs_col("PC 1", Z[, 1], "numeric"), y = cs_col("PC 2", Z[, 2], "numeric"),
cluster = cs_col(if (MODE == "zero_shot") "Zero-shot label" else if (!is.null(TRUTH)) TRUTH else "Group", ifelse(is.na(color), "(missing)", color), "categorical")
))
}
emb <- data.frame(row = as.integer(rows))
for (j in seq_len(d)) emb[[sprintf("dim_%d", j)]] <- E[, j]
nanoparquet::write_parquet(emb, file.path(out, "embedding.parquet"))
artifacts <- c(list(list(key = "embedding", path = file.path(out, "embedding.parquet"), format = "parquet")), artifacts)
statistics <- c(list(list(key = "n_images", label = "Images", value = n, format = "integer")), statistics)
if (!is.na(values$clipscore_mean)) statistics[[length(statistics) + 1]] <- list(key = "clipscore_mean", label = "Mean CLIPScore (captions)", value = values$clipscore_mean)
ta <- values$template_agreement
assumptions <- list(
list(key = "uncalibrated", label = "Scores are not probabilities", status = "info",
detail = "The scores rank images and labels well but aren't calibrated; check them against known labels before acting on a cutoff."),
list(key = "prompt_wording", label = "Labels depend on wording", status = if (!is.na(ta) && ta < 0.9) "warn" else "info",
detail = if (!is.na(ta)) sprintf("%.0f%% of images get the same label under every template.", 100 * ta)
else "Labels and search results change with the words used; try a few wordings or templates."),
list(key = "web_training", label = "Learned from web images", status = "info",
detail = "The model learned from web images and alt text; it can repeat their stereotypes and miss specialized images such as scans, documents or satellite views.")
)
cs_publish(list(
title = "Image–text search and zero-shot labels (CLIP, SigLIP)",
engine = cs_engine_info("torch", "stringi", "nanoparquet"),
n = n,
summary = summary,
statistics = statistics,
tables = tables,
assumptions = assumptions,
charts = charts,
values = values,
warnings = warnings,
notes = list(sprintf("Model: %s. Each image and text is embedded on its own in double precision, so results never depend on what else is in the run.", NAME)),
artifacts = artifacts
))
Sources
- Radford A, Kim JW, Hallacy C, et al. (2021). Learning transferable visual models from natural language supervision. ICML 2021, PMLR 139:8748–8763.
- Zhai X, Mustafa B, Kolesnikov A, Beyer L (2023). Sigmoid loss for language image pre-training. ICCV 2023, 11975–11986.
- Cherti M, Beaumont R, Wightman R, et al. (2023). Reproducible scaling laws for contrastive language-image learning. CVPR 2023, 2818–2829.
- Gadre SY, Ilharco G, Fang A, et al. (2023). DataComp: In search of the next generation of multimodal datasets. NeurIPS 2023 Datasets and Benchmarks.
- Dosovitskiy A, Beyer L, Kolesnikov A, et al. (2021). An image is worth 16x16 words: Transformers for image recognition at scale. ICLR 2021.
- Sennrich R, Haddow B, Birch A (2016). Neural machine translation of rare words with subword units. ACL 2016, 1715–1725.
- Hessel J, Holtzman A, Forbes M, Le Bras R, Choi Y (2021). CLIPScore: A reference-free evaluation metric for image captioning. EMNLP 2021, 7514–7528.
From the CodeSplash method registry · discover.image_text v1.0.0.