Labeling and searching images with words
Use a pretrained image–text model (CLIP or SigLIP) to label images with words you choose, rank images for a search text and find look-alike images, then check how much the result depends on the wording.
What runs in CodeSplash
You will be able to
- Explain how one shared space lets an image be compared with any text
- Label images zero-shot and judge the labels against known ones and across prompt templates
- Search images by text or by image and read recall at k
One space for pictures and words
ReadAn image–text model has two networks. One turns an image into a vector, the other turns a sentence into a vector, and training on web pictures with their captions pulls each picture close to its own caption. CLIPCLIPA 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. and SigLIPSigLIPA CLIP-like image–text model trained with a sigmoid loss: it scores each image–text pair on its own instead of across a batch. both work this way.
Because pictures and sentences now live in one space, you can compare an image with any words you type. Nothing is trained on your data, and the model runs on this computer after a download you approve.
The folder here holds 17 simple drawings: colored circles and squares.
Labels from your words
PredictPredict first
Each label is written into the sentence "a photo of a {label}." for red, green, blue and yellow, and each drawing takes the label that fits it best. How many get the right color?
Reveal
The answer: Most images get the right color
The labels agree with the known colors for 100.0% of the drawings. Colors and simple shapes are easy; real photos of near-identical classes are much harder.
Run it
In the app17 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.
The exact R script · R 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
))
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.
The exact Python script · Python 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 ranked thumbnails show, for each label, the images it fits best. Type your own labels, separated by commas, and watch which images move.
View data
| image | file | label | rank | score |
|---|---|---|---|---|
| demo:square:red | red_square_1.png | red | 1 | 0.9340 |
| demo:triangle:red | red_triangle_2.png | red | 2 | 0.8660 |
| demo:circle:red | red_circle_3.png | red | 3 | 0.8320 |
| demo:square:red | red_square_4.png | red | 4 | 0.7410 |
| demo:triangle:green | green_triangle_1.png | green | 1 | 0.9530 |
| demo:circle:green | green_circle_2.png | green | 2 | 0.8600 |
| demo:square:green | green_square_3.png | green | 3 | 0.8100 |
| demo:triangle:green | green_triangle_4.png | green | 4 | 0.7560 |
| demo:circle:blue | blue_circle_1.png | blue | 1 | 0.9200 |
| demo:square:blue | blue_square_2.png | blue | 2 | 0.9020 |
| demo:triangle:blue | blue_triangle_3.png | blue | 3 | 0.8030 |
| demo:circle:blue | blue_circle_4.png | blue | 4 | 0.7300 |
| demo:square:orange | orange_square_1.png | orange | 1 | 0.9370 |
| demo:triangle:orange | orange_triangle_2.png | orange | 2 | 0.8950 |
| demo:circle:orange | orange_circle_3.png | orange | 3 | 0.7910 |
| demo:square:orange | orange_square_4.png | orange | 4 | 0.7780 |
Wording matters
ReflectA prompt ensemblePrompt ensembleEach label is written into several sentences; their unit embeddings are averaged into one label vector, which steadies the labels. writes each label into several sentences and averages their vectors. It steadies the labels, and it also lets you measure how much the wording matters.
With two templates for the shapes, SigLIP gives 100.0% of the images the same label under each template on its own. When that share drops, the words you chose are driving the result, not the pictures.
View data
| churned | churn_probability |
|---|---|
| no | 0.1130 |
| no | 0.1960 |
| no | 0.0150 |
| no | 0.4510 |
| no | 0.0820 |
| no | 0.0180 |
| yes | 0.9500 |
| no | 0.5490 |
| no | 0.1550 |
| no | 0.5380 |
| no | 0.2070 |
| no | 0.1630 |
| no | 0.0720 |
| no | 0.4190 |
| yes | 0.8590 |
| no | 0.0530 |
| no | 0.2970 |
| no | 0.0430 |
| no | 0.0910 |
| no | 0.0760 |
| no | 0.0610 |
| no | 0.4490 |
| no | 0.0870 |
| no | 0.1210 |
| no | 0.0970 |
| no | 0.7310 |
| no | 0.3160 |
| no | 0.1260 |
| no | 0.1460 |
| no | 0.1380 |
| no | 0.0600 |
| no | 0.0700 |
| no | 0.0640 |
| no | 0.5060 |
| no | 0.7570 |
| no | 0.0910 |
| no | 0.0910 |
| no | 0.1450 |
| no | 0.0850 |
| yes | 0.9210 |
| yes | 0.9000 |
| no | 0.3470 |
| no | 0.1580 |
| no | 0.0060 |
| no | 0.0520 |
| no | 0.2120 |
| no | 0.2060 |
| no | 0.1880 |
| yes | 0.8940 |
| no | 0.5160 |
| no | 0.0660 |
| no | 0.0320 |
| yes | 0.8820 |
| no | 0.1710 |
| no | 0.6350 |
| no | 0.1400 |
| no | 0.1350 |
| no | 0.0600 |
| no | 0.4720 |
| no | 0.1760 |
First 60 of 1000 rows.
CLIP or SigLIP
ReadCLIP turns similarities into a softmax across your labels, so the scores of one image sum to one: it always picks a winner. SigLIP scores each image–label pair on its own, so an image can fit several labels, or none.
Search by text, or by image
ReadText → image searchText → image searchEvery image is ranked by the cosine similarity of its embedding to a search text's embedding, best match first. ranks every image for a sentence. For "a red circle", the first image is row 9.
With a caption for each image, the app ranks every image for each caption and asks where the caption's own image lands. SigLIP puts it first for 47.1% of captions. Identical captions on look-alike drawings explain most of the misses: recall at kRecall at k (captions)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. punishes ties the model can't break.
Image → image search ranks the look-alikesSimilar images (image → image)The other images ranked by the cosine similarity of their embeddings to a query image's; identical files score 1. of a query image. An exact copy of a file always comes first.
The 4 most similar images of 2 query images among 17; mean similarity to the nearest other image 0.908.
- Images
- 17
- Query images
- 2
- Mean similarity to the nearest other image
- 0.9077
Plots
View data
| File | Query | Image | Rank | Cosine similarity |
|---|---|---|---|---|
| red_circle_1.png | Row 1: red_circle_1.png | 9a3e76d2849e45190bae64fd1b648905c4eab576a5511c82985daa44ff7a25eb | 1 | 1 |
| red_circle_1_copy.png | Row 1: red_circle_1.png | 9a3e76d2849e45190bae64fd1b648905c4eab576a5511c82985daa44ff7a25eb | 2 | 1 |
| red_circle_2.png | Row 1: red_circle_1.png | 5fa652ab46822e575326d94ba482a845383141f4a34132c22d95b069024f6321 | 3 | 0.8794 |
| blue_circle_1.png | Row 1: red_circle_1.png | ac9b3dde099f3243d0b992fc9bac26d3384e28638afc7a82efa35c622ce9c12f | 4 | 0.8703 |
| yellow_circle_1.png | Row 1: red_circle_1.png | d7650e4851900cbbd716ef730decc1f99ed2da6e97b937bf8ce0a7bf5a6a64e4 | 5 | 0.8576 |
| blue_square_1.png | Row 6: blue_square_1.png | bcf2583948f23afadb9eedbe7ed773103107e11d79522ae2bd5a1b8062fa7380 | 1 | 1 |
| blue_square_2.png | Row 6: blue_square_1.png | 77c412ebdfceb00bc8213a6cd85286eb2bc53778a6822bc3ef09293ffec249d9 | 2 | 0.9014 |
| green_square_1.png | Row 6: blue_square_1.png | 8ca99c38a1f6c433614960aff2a8d7432eeeebd3654348c9988b0f9ba30e32c7 | 3 | 0.8785 |
| red_square_1.png | Row 6: blue_square_1.png | c2da9720dabe35c5e764c0a9e57df8638d67b65ccc85bc35c96446af38526376 | 4 | 0.8717 |
| yellow_square_1.png | Row 6: blue_square_1.png | c37818ace5a34c68b5903a7aee70236022e599dc89a78dea4f5cbfa8cf53d3d3 | 5 | 0.8590 |
View data
| Cosine similarity |
|---|
| 1 |
| 0.9034 |
| 0.8878 |
| 0.8827 |
| 0.8878 |
| 0.9014 |
| 0.8636 |
| 0.8937 |
| 0.8794 |
| 0.9034 |
| 0.9262 |
| 0.9069 |
| 0.9262 |
| 0.9069 |
| 0.8679 |
| 0.8937 |
| 1 |
View data
| color | 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.
Most similar images
| Query row | Query file | Rank | Row | File | Cosine similarity |
|---|---|---|---|---|---|
| 1 | red_circle_1.png | 1 | 17 | red_circle_1_copy.png | 1 |
| 1 | red_circle_1.png | 2 | 9 | red_circle_2.png | 0.8794 |
| 1 | red_circle_1.png | 3 | 5 | blue_circle_1.png | 0.8703 |
| 1 | red_circle_1.png | 4 | 7 | yellow_circle_1.png | 0.8576 |
| 6 | blue_square_1.png | 1 | 14 | blue_square_2.png | 0.9014 |
| 6 | blue_square_1.png | 2 | 4 | green_square_1.png | 0.8785 |
| 6 | blue_square_1.png | 3 | 2 | red_square_1.png | 0.8717 |
| 6 | blue_square_1.png | 4 | 8 | yellow_square_1.png | 0.8590 |
- 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.
The exact R script · R 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 3438fe2dbda1d0f0
# 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/image_query_rows/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 <- "image_search"
KIND <- "clip"
TOP_K <- as.integer(4)
LABELS <- character(0); TEMPLATES <- character(0); QUERIES <- character(0); QPOS <- integer(0)
if (MODE == "zero_shot") {
LABELS <- cs_search_split_labels("")
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("1, 6")
if (is.null(QROWS)) cs_error("CS_E_INVALID_OPTION", option = "Query rows", allowed = "row numbers separated by commas", value = "1, 6")
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/image_query_rows/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))
}
# %% Image -> image similarity: the other images ranked by cosine similarity to each query image
sim <- E %*% t(E)
nn <- vapply(seq_len(n), function(i) sim[i, cs_imagetext_top_k(sim[i, ], 1, exclude = i)[1]], 0)
values$n_queries <- length(QPOS); values$mean_nn_similarity <- mean(nn)
K <- min(TOP_K, n - 1L)
b_qrow <- integer(0); b_qfile <- character(0); b_rank <- integer(0); b_row <- integer(0); b_file <- character(0); b_sim <- numeric(0)
for (qi in seq_along(QPOS)) {
i <- QPOS[qi]
best_k <- cs_imagetext_top_k(sim[i, ], K, exclude = i)
b_qrow <- c(b_qrow, rep(rows[i] + 1L, length(best_k))); b_qfile <- c(b_qfile, rep(files[i], length(best_k)))
b_rank <- c(b_rank, seq_along(best_k)); b_row <- c(b_row, rows[best_k] + 1L); b_file <- c(b_file, files[best_k]); b_sim <- c(b_sim, sim[i, best_k])
if (qi <= 10) for (r in seq_along(best_k)) {
values[[sprintf("neighbor_row[%d.%d]", qi, r)]] <- rows[best_k[r]] + 1L
values[[sprintf("neighbor_similarity[%d.%d]", qi, r)]] <- sim[i, best_k[r]]
}
if (qi <= 20) add_gallery(sprintf("Row %d: %s", rows[i] + 1L, files[i]), c(i, best_k), c(1, sim[i, best_k]))
}
nb_cols <- list(list(key = "query_row", label = "Query row", type = "integer"), list(key = "query_file", label = "Query file", type = "string"),
list(key = "rank", label = "Rank", type = "integer"), list(key = "row", label = "Row", type = "integer"),
list(key = "file", label = "File", type = "string"), list(key = "similarity", label = "Cosine similarity", type = "number"))
n_nb <- length(b_rank)
shown <- seq_len(min(n_nb, 500L))
nb_rows <- lapply(shown, function(i) list(query_row = b_qrow[i], query_file = b_qfile[i], rank = b_rank[i], row = b_row[i], file = b_file[i], similarity = b_sim[i]))
tables[[length(tables) + 1]] <- list(key = "neighbors", title = "Most similar images", columns = nb_cols, rows = nb_rows,
note = if (length(shown) == n_nb) NULL else sprintf("The first %d of %d neighbors.", length(shown), n_nb))
statistics <- c(statistics, list(list(key = "n_queries", label = "Query images", value = length(QPOS)),
list(key = "mean_nn_similarity", label = "Mean similarity to the nearest other image", value = values$mean_nn_similarity)))
charts[[length(charts) + 1]] <- cs_chart("nearest", "histogram", "Similarity of each image to its nearest other image", list(x = cs_col("Cosine similarity", nn)))
nanoparquet::write_parquet(data.frame(query_row = b_qrow, query_file = b_qfile, rank = b_rank, row = b_row, file = b_file, similarity = b_sim),
file.path(out, "neighbors.parquet"))
artifacts[[length(artifacts) + 1]] <- list(key = "neighbors", path = file.path(out, "neighbors.parquet"), format = "parquet")
summary <- sprintf("The %d most similar images of %d query image%s among %d; mean similarity to the nearest other image %.3f.",
K, length(QPOS), if (length(QPOS) != 1) "s" else "", n, values$mean_nn_similarity)
# %% 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
))
The 4 most similar images of 2 query images among 17; mean similarity to the nearest other image 0.908.
- Images
- 17
- Query images
- 2
- Mean similarity to the nearest other image
- 0.9077
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.
Most similar images
| Query row | Query file | Rank | Row | File | Cosine similarity |
|---|---|---|---|---|---|
| 1 | red_circle_1.png | 1 | 17 | red_circle_1_copy.png | 1.000 |
| 1 | red_circle_1.png | 2 | 9 | red_circle_2.png | 0.8794 |
| 1 | red_circle_1.png | 3 | 5 | blue_circle_1.png | 0.8703 |
| 1 | red_circle_1.png | 4 | 7 | yellow_circle_1.png | 0.8576 |
| 6 | blue_square_1.png | 1 | 14 | blue_square_2.png | 0.9014 |
| 6 | blue_square_1.png | 2 | 4 | green_square_1.png | 0.8785 |
| 6 | blue_square_1.png | 3 | 2 | red_square_1.png | 0.8717 |
| 6 | blue_square_1.png | 4 | 8 | yellow_square_1.png | 0.8590 |
- 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.
The exact Python script · Python 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 3438fe2dbda1d0f0
# 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/image_query_rows/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 = "image_search"
KIND = "clip"
TOP_K = int(4)
LABELS, TEMPLATES, QUERIES, QPOS = [], [], [], []
if MODE == "zero_shot":
LABELS = zs.split_labels("")
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("1, 6")
if QROWS is None:
cs.cs_error("CS_E_INVALID_OPTION", option="Query rows", allowed="row numbers separated by commas", value="1, 6")
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/image_query_rows/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))
# %% Image → image similarity: the other images ranked by cosine similarity to each query image
sim = E @ E.T
nn = np.array([float(sim[i, it.top_k(sim[i], 1, exclude=i)[0]]) for i in range(n)])
values.update({"n_queries": len(QPOS), "mean_nn_similarity": float(np.mean(nn))})
K = min(TOP_K, n - 1)
nb_rows = []
for qi, i in enumerate(QPOS):
best_k = it.top_k(sim[i], K, exclude=i)
for r, k in enumerate(best_k, start=1):
nb_rows.append({"query_row": int(rows[i]) + 1, "query_file": files[i], "rank": r, "row": int(rows[k]) + 1, "file": files[k],
"similarity": float(sim[i, k])})
if qi < 10:
values[f"neighbor_row[{qi + 1}.{r}]"] = int(rows[k]) + 1
values[f"neighbor_similarity[{qi + 1}.{r}]"] = float(sim[i, k])
if qi < 20:
add_gallery(f"Row {int(rows[i]) + 1}: {files[i]}", [i] + [int(k) for k in best_k], [1.0] + [float(sim[i, k]) for k in best_k])
nb_cols = [{"key": "query_row", "label": "Query row", "type": "integer"}, {"key": "query_file", "label": "Query file", "type": "string"},
{"key": "rank", "label": "Rank", "type": "integer"}, {"key": "row", "label": "Row", "type": "integer"},
{"key": "file", "label": "File", "type": "string"}, {"key": "similarity", "label": "Cosine similarity", "type": "number"}]
SHOWN = nb_rows[:500]
tables.append({"key": "neighbors", "title": "Most similar images", "columns": nb_cols, "rows": SHOWN,
"note": None if len(SHOWN) == len(nb_rows) else f"The first {len(SHOWN)} of {len(nb_rows)} neighbors."})
statistics += [{"key": "n_queries", "label": "Query images", "value": len(QPOS)},
{"key": "mean_nn_similarity", "label": "Mean similarity to the nearest other image", "value": values["mean_nn_similarity"]}]
charts.append(cs.chart("nearest", "histogram", "Similarity of each image to its nearest other image", {"x": cs.col("Cosine similarity", nn)}))
pd.DataFrame(nb_rows).to_parquet(os.path.join(out, "neighbors.parquet"), index=False)
artifacts.append({"key": "neighbors", "path": os.path.join(out, "neighbors.parquet"), "format": "parquet"})
summary = f"The {K} most similar images of {len(QPOS)} query image{'s' if len(QPOS) != 1 else ''} among {n}; mean similarity to the nearest other image {values['mean_nn_similarity']:.3f}."
# %% 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,
})
Check your understanding
CheckpointCheck yourself
A photo shows a dog and a cat. With CLIP and the labels "dog" and "cat", the scores are close to one half each. What would SigLIP be able to say that CLIP can't?
Show the answer
Answer: a
CLIP's softmax shares one unit of score across the labels, so two good labels split it. SigLIP's sigmoid scores each image–label pair separately, so both can be high.
Check yourself
Many of your images change label from one template to another. What's the best next step?
Show the answer
Answer: a
Low agreement means the wording, not the picture, decides many labels. Averaging hides the disagreement but doesn't remove it; looking at the images that flip shows which label or template is unclear.
Check yourself
Recall at 1 for your captions is low, but recall at 5 is high. What's the most likely reading?
Show the answer
Answer: a
When the own image is in the top five but rarely first, near-duplicates or generic captions are crowding the first place. Read the matches before blaming the model.
Recap
Recap- CLIP and SigLIP put images and texts in one space, so any words can label or search images without training.
- The wording of labels and templates changes the result: compare templates and read the images that flip.
- CLIP's scores split across labels; SigLIP's don't. Neither is calibrated.
- Text search, caption recall and look-alike search all rank by cosine similarity, and ties keep row order.
Concepts in this lesson