Which images look alike? Image embeddings, maps and neighbors
Turn every image into a vector with a pretrained network, map the vectors in two dimensions, list each image's nearest neighbors, and check how well the vectors separate known classes before saving them for other methods.
What runs in CodeSplash
You will be able to
- Explain what an image embedding is and why look-alike images get nearby vectors
- Read an image map, a nearest-neighbor gallery and the share of neighbors that share a label
- Choose between DINOv2 and ResNet-50 and between a PCA and a UMAP map
Read first
A vector for every picture
ReadA pretrained network turns an image into a list of numbers, an image embeddingImage embeddingThe vector a pretrained network gives an image; images that look alike get nearby vectors.. Networks trained on millions of photos learn to give look-alike images nearby vectors, so distances between vectors stand in for "these look alike".
Image embeddings runs one of two networks on this computer: DINOv2DINOv2A vision transformer trained without labels to give look-alike images similar vectors; the small model has 384 values.-small, trained without labels, gives 384 values per image; ResNet-50ResNet-50A 50-layer convolutional network whose blocks add their input back to their output, which lets very deep networks train., trained to name ImageNet's classes, gives 2,048. The folder here holds 36 drawings in three patterns.
36 of 36 images embedded with DINOv2-small (384 values each); the first two principal components hold 67% of the variation, and an image's nearest neighbor has a mean cosine similarity of 0.966. 97% of the 5 nearest neighbors share the image's pattern (33% by chance).
- Images embedded
- 36
- Mean nearest-neighbor similarity
- 0.9664
- Map trustworthiness (k = 10)
- 0.9879
- Neighbors sharing pattern
- 96.7%
Nearest neighbors (first 50 images)
| Row | Image | Neighbor 1 | Similarity 1 | Neighbor 2 | Similarity 2 | Neighbor 3 | Similarity 3 | Neighbor 4 | Similarity 4 | Neighbor 5 | Similarity 5 |
|---|---|---|---|---|---|---|---|---|---|---|---|
| 1 | eaaf0b653783a80d9368c543de2d3b6d3653e67591914bbf07f3d059e505b9af | 11 | 0.9647 | 2 | 0.9592 | 12 | 0.9551 | 10 | 0.9445 | 3 | 0.8824 |
| 2 | 1616969906495a3b1e73ed3fd06d130cc7bd0e3869229c661e7c5095c817486e | 1 | 0.9592 | 3 | 0.9555 | 11 | 0.9182 | 10 | 0.9075 | 12 | 0.9043 |
| 3 | d8dccd3eb1494976deecb62ba4a908a2e51df416dc2adb0c10ac609a6dc2e126 | 2 | 0.9555 | 1 | 0.8824 | 10 | 0.8639 | 11 | 0.8523 | 6 | 0.8434 |
| 4 | bc96f5687bf15cdd245ad8df8c765de59787847fb0882b9864f8804c3c060f6d | 5 | 0.9680 | 6 | 0.8949 | 22 | 0.8647 | 3 | 0.8401 | 23 | 0.7735 |
| 5 | bee897f25cb41fbfb6ad00818c58bde4180b58cab4ad348159b9cd0c41bc3d4d | 4 | 0.9680 | 6 | 0.9539 | 22 | 0.8640 | 3 | 0.8392 | 10 | 0.8212 |
| 6 | f74ac9c268e859385d8e9b2f9130f7f091cf8b9a17a5d67be5384d5c8a7c38f1 | 5 | 0.9539 | 10 | 0.9023 | 4 | 0.8949 | 11 | 0.8778 | 12 | 0.8720 |
| 7 | 45ad4af12ce82a0a05bc3a05daa3b889d28351accfbd87ce35083a8f290c6937 | 8 | 0.9876 | 9 | 0.9766 | 12 | 0.9023 | 10 | 0.8958 | 11 | 0.8860 |
| 8 | 5f3599c5f9cbac623f63e69cf9066bec83c510426ac9c869130cbb0a8cff5864 | 9 | 0.9891 | 7 | 0.9876 | 12 | 0.9227 | 10 | 0.9162 | 11 | 0.9076 |
| 9 | 2cf42103f66d4d63582a5df5625d218687bb285288d6c980703790ba9e49a72b | 8 | 0.9891 | 7 | 0.9766 | 12 | 0.9294 | 10 | 0.9209 | 11 | 0.9189 |
| 10 | 3cce226bf4f0867bcdccb746b3842c82cc7c0231b3429a3ed034de55bfba914c | 12 | 0.9892 | 11 | 0.9871 | 1 | 0.9445 | 9 | 0.9209 | 8 | 0.9162 |
| 11 | 3270ef987ee35ffc8b442944628367ecf657aece9d3df57a8975a7f0c32eab19 | 12 | 0.9914 | 10 | 0.9871 | 1 | 0.9647 | 9 | 0.9189 | 2 | 0.9182 |
| 12 | e526022983f99deb3a7710f13f6f42d9f0cfa57fbdea4c18cb8cfb82629e1619 | 11 | 0.9914 | 10 | 0.9892 | 1 | 0.9551 | 9 | 0.9294 | 8 | 0.9227 |
| 13 | a5b4d35cf856a06f1a8260dfa5ea16eed7faebac1b1bed4098a2eb23afafa2ce | 14 | 0.9789 | 15 | 0.9675 | 16 | 0.8883 | 17 | 0.8565 | 20 | 0.8531 |
| 14 | afe329016b29c5e0774f9db39a73b3646fe19554a9d7169142d3594c0bdd722c | 15 | 0.9916 | 13 | 0.9789 | 16 | 0.9114 | 17 | 0.8848 | 18 | 0.8708 |
| 15 | 311aa9cef09e541ea7ee4f941338147e9ca86001b400950f04371743a901d3f3 | 14 | 0.9916 | 13 | 0.9675 | 16 | 0.9140 | 17 | 0.8810 | 20 | 0.8716 |
| 16 | 93b3aacc37a5a3197f9dab54338ae78997254b9a47fcb782a0945ff7b92a368d | 17 | 0.9835 | 18 | 0.9668 | 20 | 0.9415 | 15 | 0.9140 | 19 | 0.9135 |
| 17 | 4c7c29f5e28b50a5100896a01f05b103006136f1a5dba15557839e51f4ac7d1e | 18 | 0.9861 | 16 | 0.9835 | 20 | 0.9267 | 19 | 0.9122 | 21 | 0.8902 |
| 18 | 2783f8f0767e286ebbddcd1ddd890c8850b7eaf1471cb1708ee7ec450e43fb89 | 17 | 0.9861 | 16 | 0.9668 | 20 | 0.9269 | 19 | 0.9266 | 21 | 0.8869 |
| 19 | cd7c11335d85e04a83593d5a73dfc735674964cc215737296cc7284b416cb418 | 20 | 0.9713 | 18 | 0.9266 | 16 | 0.9135 | 17 | 0.9122 | 21 | 0.9096 |
| 20 | 5e23d8f9c5002195cb21b605ce176a094c0fe5e7bd3e90e97e03ec8293d9b161 | 19 | 0.9713 | 21 | 0.9558 | 16 | 0.9415 | 18 | 0.9269 | 17 | 0.9267 |
| 21 | 81a9721a6f524c9ed85e2686492a542649a745a7617c969eb36d711f0a173916 | 20 | 0.9558 | 19 | 0.9096 | 16 | 0.9084 | 17 | 0.8902 | 18 | 0.8869 |
| 22 | 1a1b1b36104cda0082711a0a4594c7f766d02ee20cb959a8d92ecdc6bfb1bbdc | 23 | 0.9218 | 4 | 0.8647 | 5 | 0.8640 | 24 | 0.8196 | 6 | 0.7965 |
| 23 | 4743b825b1e80f2a8580f5f010aae3a26b19e11e64d8ba4da95e575a060162e6 | 24 | 0.9656 | 22 | 0.9218 | 16 | 0.8590 | 20 | 0.8415 | 17 | 0.8286 |
| 24 | 7c268eab4ba13c664e8ca27e8c484d1393082db348e60a4350830428fb911776 | 23 | 0.9656 | 20 | 0.8765 | 19 | 0.8700 | 16 | 0.8656 | 18 | 0.8525 |
| 25 | e3737254bb3a8bce5fe2c0a132802c752aae36058164fde6c2451f5d30e7e960 | 26 | 0.9590 | 27 | 0.9405 | 30 | 0.9074 | 34 | 0.9033 | 28 | 0.9009 |
| 26 | 8c189a553b7052eb0c69ad5e655eb776ac86058481919a427a8e37560aac5c7c | 25 | 0.9590 | 27 | 0.9246 | 30 | 0.9106 | 34 | 0.8908 | 32 | 0.8797 |
| 27 | 2b0292d936322add6f739c62dc184ebb5b16ad7a79780ea89a9eec9dbe2d56a6 | 25 | 0.9405 | 26 | 0.9246 | 34 | 0.9194 | 28 | 0.9169 | 35 | 0.9084 |
| 28 | d655214257593e45321b63942391256a1bc4cb295b2183db9d8c2350efc8497e | 34 | 0.9308 | 33 | 0.9287 | 27 | 0.9169 | 29 | 0.9100 | 30 | 0.9076 |
| 29 | 8150c74699bef1fd8847d821fcf56048d17198cb049df30e2b34cec16c089cc6 | 31 | 0.9596 | 33 | 0.9283 | 32 | 0.9136 | 28 | 0.9100 | 34 | 0.8650 |
| 30 | bd7b31d3a8d51cfd64a9d2bc53901a56264d6a172fd7adfec6d57b0908b5b421 | 26 | 0.9106 | 28 | 0.9076 | 25 | 0.9074 | 27 | 0.8806 | 32 | 0.8731 |
| 31 | 3071561e17a806103735a820928c848308ff0eef0fcd085cfae15b313482f768 | 29 | 0.9596 | 33 | 0.9440 | 32 | 0.9183 | 28 | 0.8937 | 36 | 0.8597 |
| 32 | 4f28d467498ba362a0c9490ff305722dbb29f2f8dcdcd51faa129f43be9ec33f | 33 | 0.9634 | 31 | 0.9183 | 29 | 0.9136 | 27 | 0.9081 | 28 | 0.9061 |
| 33 | 94fa37138390f0c23343c075b06fbb6cfeb5bb360e53e15dcf62f98570348ece | 32 | 0.9634 | 31 | 0.9440 | 28 | 0.9287 | 29 | 0.9283 | 34 | 0.8982 |
| 34 | dbb38fe99552de6e9d1aa43e515c45593b15cc142206bd47fba4d47787e1eb09 | 35 | 0.9574 | 36 | 0.9547 | 28 | 0.9308 | 27 | 0.9194 | 25 | 0.9033 |
| 35 | a2d74e916b6de16197dacdc67ad528dcad7d1f2e2482805d904a4a46affcdb9d | 34 | 0.9574 | 36 | 0.9496 | 27 | 0.9084 | 28 | 0.8886 | 26 | 0.8788 |
| 36 | 9a3571488647fead3c8941992995b4c9d23def741e3ace04bfeaa8da12ec6640 | 34 | 0.9547 | 35 | 0.9496 | 27 | 0.8944 | 32 | 0.8911 | 28 | 0.8876 |
The exact R script · R R version 4.5.1 (2025-06-13)
# Image embeddings, map and neighbors (DINOv2 or ResNet-50)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method embed.images 1.0.0 · spec d55ed26adc4d2b2f
# Dataset: img1_shapes (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr)
# %% Data: the image column (and the label to color by)
IMAGE <- "path"
LABEL <- "pattern"
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/img1_shapes.parquet", col_select = c(IMAGE, LABEL)))
df <- cs_imgcls_attach_columns(df, "tests/parity/fixtures/img1_shapes.parquet", IMAGE) # media_id, for a media collection
warnings <- list()
# %% 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\":\"triangle\",\"fit\":\"shorter_center_crop\",\"mode\":\"rgb\",\"normalize\":\"none\",\"size\":[56,56]}}", simplifyVector = FALSE), "target/academy-parity/run-97231/embed.images/dinov2_pca_by_pattern/out-r", df,
"tests/parity/fixtures/img1_shapes.parquet")
media_ids <- cs_media_ids(media, df)
ok <- cs_imgemb_usable(media, media_ids, IMAGE)
rows <- ok$rows
if (ok$n_missing + ok$n_unreadable > 0) {
warnings <- c(warnings, sprintf("%d of %d rows have no readable image (%d without a path); they are left out of the map and their embedding stays empty.",
ok$n_missing + ok$n_unreadable, nrow(df), ok$n_missing))
}
# %% Embeddings: DINOv2-small on 56 x 56 images (float64 under Parity)
ENCODER <- "dinov2_small"
E <- cs_encoder_embed(ENCODER, media, batch_size = 16L, ids = ok$ids)
D <- ncol(E)
# %% 2-D map and nearest neighbors (cosine)
pm <- cs_imgemb_pca_map(E)
Y <- pm$Y
shares <- pm$shares
MAP_LABEL <- "Component"
K <- as.integer(min(5, length(rows) - 1L))
nn <- cs_imgemb_cosine_knn(E, K)
labels <- if (!is.null(LABEL)) df[[LABEL]][rows + 1L] else NULL
la <- if (!is.null(LABEL)) cs_imgemb_label_agreement(nn$idx, labels) else list(agreement = NULL, chance = NULL)
sample <- cs_ml_sample_rows(length(rows))
k_eval <- min(10L, length(sample) - 2L)
trust <- if (k_eval >= 1L) cs_ml_trustworthiness(E[sample, , drop = FALSE], Y[sample, , drop = FALSE], k_eval) else NULL
# %% Artifacts: embeddings (saved like any Discover embedding) and neighbors
out <- cs_ml_out_dir("target/academy-parity/run-97231/embed.images/dinov2_pca_by_pattern/out-r")
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"))
nb <- data.frame(row = rep(as.integer(rows), each = K), rank = rep(seq_len(K), times = length(rows)),
neighbor = as.integer(rows[as.vector(t(nn$idx)) + 1L]), similarity = as.vector(t(nn$sim)))
nanoparquet::write_parquet(nb, file.path(out, "neighbors.parquet"))
# %% Result
values <- list(
n_rows = nrow(df), n_images = length(rows), n_missing = ok$n_missing, n_unreadable = ok$n_unreadable, dim = D,
neighbors = K, map_share_1 = shares[1], map_share_2 = shares[2], mean_nn_similarity = mean(nn$sim[, 1]),
trustworthiness = trust, label_agreement = la$agreement, label_agreement_chance = la$chance
)
for (j in seq_len(min(3L, D))) values[[sprintf("emb_check[%d]", j)]] <- cs_ml_checksum(E[, j], rows)
pick <- cs_ml_sample_rows(length(rows), 5000)
grp <- if (is.null(LABEL)) rep("All images", length(pick)) else {
v <- as.character(df[[LABEL]][rows[pick] + 1L]); ifelse(is.na(v), "(missing)", v)
}
charts <- list(cs_chart("map", "cluster-scatter",
sprintf("Image map (%s)", if (MAP_LABEL == "UMAP") "umap" else "principal components 1 and 2"),
list(x = cs_col(paste(MAP_LABEL, 1), Y[pick, 1], "numeric"), y = cs_col(paste(MAP_LABEL, 2), Y[pick, 2], "numeric"),
cluster = cs_col(if (is.null(LABEL)) "Group" else LABEL, grp, "categorical")),
note = if (length(pick) == length(rows)) NULL else sprintf("%s of %s images shown.", format(length(pick), big.mark = ","), format(length(rows), big.mark = ","))))
picks <- cs_ml_sample_rows(length(rows), 4) - 1L
charts[[2]] <- cs_imgcls_image_chart("neighbors", "image-gallery", sprintf("Nearest neighbors of %d images", length(picks)),
cs_imgemb_gallery_rows(media, ok$ids, rows, nn$idx, nn$sim, picks),
"Each line starts with an image and shows its closest images by cosine similarity (the number under each).")
trows <- lapply(seq_len(min(50L, length(rows))), function(i) {
r <- list(row = rows[i] + 1L, media_id = ok$ids[i])
for (k in seq_len(K)) {
r[[sprintf("n%d", k)]] <- rows[nn$idx[i, k] + 1L] + 1L
r[[sprintf("s%d", k)]] <- nn$sim[i, k]
}
r
})
cols <- c(list(list(key = "row", label = "Row", type = "integer"), list(key = "media_id", label = "Image")),
unlist(lapply(seq_len(K), function(k) list(list(key = sprintf("n%d", k), label = sprintf("Neighbor %d", k), type = "integer"),
list(key = sprintf("s%d", k), label = sprintf("Similarity %d", k), type = "number"))), recursive = FALSE))
tables <- list(list(key = "neighbors", title = "Nearest neighbors (first 50 images)", columns = cols, rows = trows))
summary <- sprintf("%d of %d images embedded with %s (%d values each); the first two principal components hold %s of the variation, and an image's nearest neighbor has a mean cosine similarity of %.3f.",
length(rows), nrow(df), cs_encoder_get(ENCODER)$label, D, sprintf("%.0f%%", 100 * (shares[1] + shares[2])), values$mean_nn_similarity)
if (!is.null(la$agreement)) summary <- paste0(summary, sprintf(" %s of the %d nearest neighbors share the image's %s (%s by chance).",
sprintf("%.0f%%", 100 * (la$agreement)), K, LABEL, sprintf("%.0f%%", 100 * (la$chance))))
stats <- list(list(key = "n_images", label = "Images embedded", value = length(rows)),
list(key = "mean_nn_similarity", label = "Mean nearest-neighbor similarity", value = values$mean_nn_similarity))
if (!is.null(trust)) stats[[length(stats) + 1L]] <- list(key = "trustworthiness", label = sprintf("Map trustworthiness (k = %d)", k_eval), value = trust)
if (!is.null(la$agreement)) stats[[length(stats) + 1L]] <- list(key = "label_agreement", label = sprintf("Neighbors sharing %s", LABEL), value = la$agreement, format = "percent")
cs_publish(list(
title = "Image embeddings, map and neighbors (DINOv2 or ResNet-50)",
engine = cs_engine_info("torch", "nanoparquet"),
n = length(rows),
summary = summary,
statistics = stats,
charts = charts,
tables = tables,
values = values,
warnings = warnings,
artifacts = list(
list(key = "embedding", path = file.path(out, "embedding.parquet"), format = "parquet"),
list(key = "neighbors", path = file.path(out, "neighbors.parquet"), format = "parquet")
)
))
36 of 36 images embedded with DINOv2-small (384 values each); the first two principal components hold 67% of the variation, and an image's nearest neighbor has a mean cosine similarity of 0.966. 97% of the 5 nearest neighbors share the image's pattern (33% by chance).
- Images embedded
- 36
- Mean nearest-neighbor similarity
- 0.9664
- Map trustworthiness (k = 10)
- 0.9879
- Neighbors sharing pattern
- 96.7%
Nearest neighbors (first 50 images)
| Row | Image | Neighbor 1 | Similarity 1 | Neighbor 2 | Similarity 2 | Neighbor 3 | Similarity 3 | Neighbor 4 | Similarity 4 | Neighbor 5 | Similarity 5 |
|---|---|---|---|---|---|---|---|---|---|---|---|
| 1 | eaaf0b653783a80d9368c543de2d3b6d3653e67591914bbf07f3d059e505b9af | 11 | 0.9647 | 2 | 0.9592 | 12 | 0.9551 | 10 | 0.9445 | 3 | 0.8824 |
| 2 | 1616969906495a3b1e73ed3fd06d130cc7bd0e3869229c661e7c5095c817486e | 1 | 0.9592 | 3 | 0.9555 | 11 | 0.9182 | 10 | 0.9075 | 12 | 0.9043 |
| 3 | d8dccd3eb1494976deecb62ba4a908a2e51df416dc2adb0c10ac609a6dc2e126 | 2 | 0.9555 | 1 | 0.8824 | 10 | 0.8639 | 11 | 0.8523 | 6 | 0.8434 |
| 4 | bc96f5687bf15cdd245ad8df8c765de59787847fb0882b9864f8804c3c060f6d | 5 | 0.9680 | 6 | 0.8949 | 22 | 0.8647 | 3 | 0.8401 | 23 | 0.7735 |
| 5 | bee897f25cb41fbfb6ad00818c58bde4180b58cab4ad348159b9cd0c41bc3d4d | 4 | 0.9680 | 6 | 0.9539 | 22 | 0.8640 | 3 | 0.8392 | 10 | 0.8212 |
| 6 | f74ac9c268e859385d8e9b2f9130f7f091cf8b9a17a5d67be5384d5c8a7c38f1 | 5 | 0.9539 | 10 | 0.9023 | 4 | 0.8949 | 11 | 0.8778 | 12 | 0.8720 |
| 7 | 45ad4af12ce82a0a05bc3a05daa3b889d28351accfbd87ce35083a8f290c6937 | 8 | 0.9876 | 9 | 0.9766 | 12 | 0.9023 | 10 | 0.8958 | 11 | 0.8860 |
| 8 | 5f3599c5f9cbac623f63e69cf9066bec83c510426ac9c869130cbb0a8cff5864 | 9 | 0.9891 | 7 | 0.9876 | 12 | 0.9227 | 10 | 0.9162 | 11 | 0.9076 |
| 9 | 2cf42103f66d4d63582a5df5625d218687bb285288d6c980703790ba9e49a72b | 8 | 0.9891 | 7 | 0.9766 | 12 | 0.9294 | 10 | 0.9209 | 11 | 0.9189 |
| 10 | 3cce226bf4f0867bcdccb746b3842c82cc7c0231b3429a3ed034de55bfba914c | 12 | 0.9892 | 11 | 0.9871 | 1 | 0.9445 | 9 | 0.9209 | 8 | 0.9162 |
| 11 | 3270ef987ee35ffc8b442944628367ecf657aece9d3df57a8975a7f0c32eab19 | 12 | 0.9914 | 10 | 0.9871 | 1 | 0.9647 | 9 | 0.9189 | 2 | 0.9182 |
| 12 | e526022983f99deb3a7710f13f6f42d9f0cfa57fbdea4c18cb8cfb82629e1619 | 11 | 0.9914 | 10 | 0.9892 | 1 | 0.9551 | 9 | 0.9294 | 8 | 0.9227 |
| 13 | a5b4d35cf856a06f1a8260dfa5ea16eed7faebac1b1bed4098a2eb23afafa2ce | 14 | 0.9789 | 15 | 0.9675 | 16 | 0.8883 | 17 | 0.8565 | 20 | 0.8531 |
| 14 | afe329016b29c5e0774f9db39a73b3646fe19554a9d7169142d3594c0bdd722c | 15 | 0.9916 | 13 | 0.9789 | 16 | 0.9114 | 17 | 0.8848 | 18 | 0.8708 |
| 15 | 311aa9cef09e541ea7ee4f941338147e9ca86001b400950f04371743a901d3f3 | 14 | 0.9916 | 13 | 0.9675 | 16 | 0.9140 | 17 | 0.8810 | 20 | 0.8716 |
| 16 | 93b3aacc37a5a3197f9dab54338ae78997254b9a47fcb782a0945ff7b92a368d | 17 | 0.9835 | 18 | 0.9668 | 20 | 0.9415 | 15 | 0.9140 | 19 | 0.9135 |
| 17 | 4c7c29f5e28b50a5100896a01f05b103006136f1a5dba15557839e51f4ac7d1e | 18 | 0.9861 | 16 | 0.9835 | 20 | 0.9267 | 19 | 0.9122 | 21 | 0.8902 |
| 18 | 2783f8f0767e286ebbddcd1ddd890c8850b7eaf1471cb1708ee7ec450e43fb89 | 17 | 0.9861 | 16 | 0.9668 | 20 | 0.9269 | 19 | 0.9266 | 21 | 0.8869 |
| 19 | cd7c11335d85e04a83593d5a73dfc735674964cc215737296cc7284b416cb418 | 20 | 0.9713 | 18 | 0.9266 | 16 | 0.9135 | 17 | 0.9122 | 21 | 0.9096 |
| 20 | 5e23d8f9c5002195cb21b605ce176a094c0fe5e7bd3e90e97e03ec8293d9b161 | 19 | 0.9713 | 21 | 0.9558 | 16 | 0.9415 | 18 | 0.9269 | 17 | 0.9267 |
| 21 | 81a9721a6f524c9ed85e2686492a542649a745a7617c969eb36d711f0a173916 | 20 | 0.9558 | 19 | 0.9096 | 16 | 0.9084 | 17 | 0.8902 | 18 | 0.8869 |
| 22 | 1a1b1b36104cda0082711a0a4594c7f766d02ee20cb959a8d92ecdc6bfb1bbdc | 23 | 0.9218 | 4 | 0.8647 | 5 | 0.8640 | 24 | 0.8196 | 6 | 0.7965 |
| 23 | 4743b825b1e80f2a8580f5f010aae3a26b19e11e64d8ba4da95e575a060162e6 | 24 | 0.9656 | 22 | 0.9218 | 16 | 0.8590 | 20 | 0.8415 | 17 | 0.8286 |
| 24 | 7c268eab4ba13c664e8ca27e8c484d1393082db348e60a4350830428fb911776 | 23 | 0.9656 | 20 | 0.8765 | 19 | 0.8700 | 16 | 0.8656 | 18 | 0.8525 |
| 25 | e3737254bb3a8bce5fe2c0a132802c752aae36058164fde6c2451f5d30e7e960 | 26 | 0.9590 | 27 | 0.9405 | 30 | 0.9074 | 34 | 0.9033 | 28 | 0.9009 |
| 26 | 8c189a553b7052eb0c69ad5e655eb776ac86058481919a427a8e37560aac5c7c | 25 | 0.9590 | 27 | 0.9246 | 30 | 0.9106 | 34 | 0.8908 | 32 | 0.8797 |
| 27 | 2b0292d936322add6f739c62dc184ebb5b16ad7a79780ea89a9eec9dbe2d56a6 | 25 | 0.9405 | 26 | 0.9246 | 34 | 0.9194 | 28 | 0.9169 | 35 | 0.9084 |
| 28 | d655214257593e45321b63942391256a1bc4cb295b2183db9d8c2350efc8497e | 34 | 0.9308 | 33 | 0.9287 | 27 | 0.9169 | 29 | 0.9100 | 30 | 0.9076 |
| 29 | 8150c74699bef1fd8847d821fcf56048d17198cb049df30e2b34cec16c089cc6 | 31 | 0.9596 | 33 | 0.9283 | 32 | 0.9136 | 28 | 0.9100 | 34 | 0.8650 |
| 30 | bd7b31d3a8d51cfd64a9d2bc53901a56264d6a172fd7adfec6d57b0908b5b421 | 26 | 0.9106 | 28 | 0.9076 | 25 | 0.9074 | 27 | 0.8806 | 32 | 0.8731 |
| 31 | 3071561e17a806103735a820928c848308ff0eef0fcd085cfae15b313482f768 | 29 | 0.9596 | 33 | 0.9440 | 32 | 0.9183 | 28 | 0.8937 | 36 | 0.8597 |
| 32 | 4f28d467498ba362a0c9490ff305722dbb29f2f8dcdcd51faa129f43be9ec33f | 33 | 0.9634 | 31 | 0.9183 | 29 | 0.9136 | 27 | 0.9081 | 28 | 0.9061 |
| 33 | 94fa37138390f0c23343c075b06fbb6cfeb5bb360e53e15dcf62f98570348ece | 32 | 0.9634 | 31 | 0.9440 | 28 | 0.9287 | 29 | 0.9283 | 34 | 0.8982 |
| 34 | dbb38fe99552de6e9d1aa43e515c45593b15cc142206bd47fba4d47787e1eb09 | 35 | 0.9574 | 36 | 0.9547 | 28 | 0.9308 | 27 | 0.9194 | 25 | 0.9033 |
| 35 | a2d74e916b6de16197dacdc67ad528dcad7d1f2e2482805d904a4a46affcdb9d | 34 | 0.9574 | 36 | 0.9496 | 27 | 0.9084 | 28 | 0.8886 | 26 | 0.8788 |
| 36 | 9a3571488647fead3c8941992995b4c9d23def741e3ace04bfeaa8da12ec6640 | 34 | 0.9547 | 35 | 0.9496 | 27 | 0.8944 | 32 | 0.8911 | 28 | 0.8876 |
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Image embeddings, map and neighbors (DINOv2 or ResNet-50)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method embed.images 1.0.0 · spec d55ed26adc4d2b2f
# Dataset: img1_shapes (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 encoders
from codesplash import ml as csml
from codesplash.images import embed_images as eimg # twin of codesplashr cs_imgemb_* (same encoder, map and neighbors)
from codesplash.images.classifier import attach_columns, image_chart
from codesplash.ml import embed as csembed
# %% Data: the image column (and the label to color by)
IMAGE = "path"
LABEL = "pattern"
df = pd.read_parquet("tests/parity/fixtures/img1_shapes.parquet", columns=[IMAGE] + ([LABEL] if LABEL else []))
df = attach_columns(df, "tests/parity/fixtures/img1_shapes.parquet", IMAGE) # media_id, for a media collection
warnings = []
# %% 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\":\"triangle\",\"fit\":\"shorter_center_crop\",\"mode\":\"rgb\",\"normalize\":\"none\",\"size\":[56,56]}}"), "target/academy-parity/run-97231/embed.images/dinov2_pca_by_pattern/out-python", df, "tests/parity/fixtures/img1_shapes.parquet")
media_ids = cs_media.ids_of(media, df)
ok = eimg.usable(media, media_ids, IMAGE)
rows = ok["rows"]
if ok["n_missing"] or ok["n_unreadable"]:
warnings.append(f"{ok['n_missing'] + ok['n_unreadable']} of {len(df)} rows have no readable image ({ok['n_missing']} without a path); they are left out of the map and their embedding stays empty.")
# %% Embeddings: DINOv2-small on 56 × 56 images (float64 under Parity)
ENCODER = "dinov2_small"
E = encoders.embed(ENCODER, media, ids=ok["ids"], batch_size=16)
D = E.shape[1]
# %% 2-D map and nearest neighbors (cosine)
Y, shares = eimg.pca_map(E)
MAP_LABEL = "Component"
K = min(5, len(rows) - 1)
nn_idx, nn_sim = eimg.cosine_knn(E, K)
labels = df[LABEL].iloc[rows].tolist() if LABEL else None
agree, chance = eimg.label_agreement(nn_idx, labels) if LABEL else (None, None)
sample = csembed.sample_rows(len(rows))
k_eval = min(10, len(sample) - 2)
trust = csembed.trustworthiness(E[sample], Y[sample], k_eval) if k_eval >= 1 else None
# %% Artifacts: embeddings (saved like any Discover embedding) and neighbors
out = csml.out_dir("target/academy-parity/run-97231/embed.images/dinov2_pca_by_pattern/out-python")
emb = pd.DataFrame({"row": rows.astype(np.int64), **{f"dim_{j + 1}": E[:, j] for j in range(D)}})
emb.to_parquet(os.path.join(out, "embedding.parquet"), index=False)
nb = pd.DataFrame({
"row": np.repeat(rows, K).astype(np.int64),
"rank": np.tile(np.arange(1, K + 1), len(rows)).astype(np.int64),
"neighbor": rows[nn_idx.reshape(-1)].astype(np.int64),
"similarity": nn_sim.reshape(-1),
})
nb.to_parquet(os.path.join(out, "neighbors.parquet"), index=False)
# %% Result
values = {
"n_rows": len(df),
"n_images": len(rows),
"n_missing": ok["n_missing"],
"n_unreadable": ok["n_unreadable"],
"dim": D,
"neighbors": K,
"map_share_1": float(shares[0]),
"map_share_2": float(shares[1]),
"mean_nn_similarity": float(np.mean(nn_sim[:, 0])),
"trustworthiness": trust,
"label_agreement": agree,
"label_agreement_chance": chance,
}
for j in range(min(3, D)):
values[f"emb_check[{j + 1}]"] = csembed.checksum(E[:, j], rows)
pick = csembed.sample_rows(len(rows), 5000)
grp = [("All images" if LABEL is None else ("(missing)" if pd.isna(v) else str(v))) for v in (df[LABEL].iloc[rows[pick]] if LABEL else [None] * len(pick))]
charts = [cs.chart("map", "cluster-scatter", f"Image map ({MAP_LABEL.lower() if MAP_LABEL == 'UMAP' else 'principal components 1 and 2'})", {
"x": cs.col(f"{MAP_LABEL} 1", Y[pick, 0], "numeric"),
"y": cs.col(f"{MAP_LABEL} 2", Y[pick, 1], "numeric"),
"cluster": cs.col(LABEL or "Group", grp, "categorical"),
}, note=None if len(pick) == len(rows) else f"{len(pick):,} of {len(rows):,} images shown.")]
picks = csembed.sample_rows(len(rows), 4)
charts.append(image_chart("neighbors", "image-gallery", f"Nearest neighbors of {len(picks)} images", eimg.gallery_rows(media, ok["ids"], rows, nn_idx, nn_sim, picks),
"Each line starts with an image and shows its closest images by cosine similarity (the number under each)."))
table_rows = [{"row": int(rows[i]) + 1, "media_id": ok["ids"][i], **{f"n{r + 1}": int(rows[nn_idx[i, r]]) + 1 for r in range(K)},
**{f"s{r + 1}": float(nn_sim[i, r]) for r in range(K)}} for i in range(min(50, len(rows)))]
tables = [{
"key": "neighbors",
"title": "Nearest neighbors (first 50 images)",
"columns": [{"key": "row", "label": "Row", "type": "integer"}, {"key": "media_id", "label": "Image"}]
+ [c for r in range(K) for c in ({"key": f"n{r + 1}", "label": f"Neighbor {r + 1}", "type": "integer"}, {"key": f"s{r + 1}", "label": f"Similarity {r + 1}", "type": "number"})],
"rows": table_rows,
}]
summary = (
f"{len(rows)} of {len(df)} images embedded with {encoders.get(ENCODER).label} ({D} values each); the first two principal components hold "
f"{shares[0] + shares[1]:.0%} of the variation, and an image's nearest neighbor has a mean cosine similarity of {values['mean_nn_similarity']:.3f}."
)
if agree is not None:
summary += f" {agree:.0%} of the {K} nearest neighbors share the image's {LABEL} ({chance:.0%} by chance)."
cs.publish({
"title": "Image embeddings, map and neighbors (DINOv2 or ResNet-50)",
"engine": cs.engine_info("torch", "numpy", "pandas"),
"n": len(rows),
"summary": summary,
"statistics": [
{"key": "n_images", "label": "Images embedded", "value": len(rows)},
{"key": "mean_nn_similarity", "label": "Mean nearest-neighbor similarity", "value": values["mean_nn_similarity"]},
] + ([{"key": "trustworthiness", "label": f"Map trustworthiness (k = {k_eval})", "value": trust}] if trust is not None else [])
+ ([{"key": "label_agreement", "label": f"Neighbors sharing {LABEL}", "value": agree, "format": "percent"}] if agree is not None else []),
"charts": charts,
"tables": tables,
"values": values,
"warnings": warnings,
"artifacts": [
{"key": "embedding", "path": os.path.join(out, "embedding.parquet"), "format": "parquet"},
{"key": "neighbors", "path": os.path.join(out, "neighbors.parquet"), "format": "parquet"},
],
})
Shortened for the Academy: 2 chart(s) dropped to stay under 100 KB; 2 chart(s) dropped to stay under 100 KB.
The map and the neighbors
ReadThe map draws principal components 1 and 2 of the vectors. They hold 50.0% and 16.7% of the variation: a map shows the broadest differences and hides the rest, so read neighbors from the vectors, not from the picture.
Each image's nearest neighbors come from cosine similarityCosine similarityThe cosine of the angle between two vectors: 1 for the same direction, 0 for unrelated, −1 for opposite. of the full vectors. The gallery starts each line with an image and shows its closest images with their similarity; the mean similarity of an image to its closest neighbor is 0.966.
Do the vectors know the classes?
PredictPredict first
The pattern was never shown to the network. Each image lists its 5 nearest neighbors. What share of those neighbors do you expect to have the same pattern?
Reveal
Nearly all: 96.7%, against 33.3% by chance. The vectors separate the patterns on their own, so a classifier trained on them should do well: try the Image classifier with head-only training.
Shots of the same source
ReadColored by source, each source's three shots sit together and the UMAP map clusters them: 84.7% of each image's 2 nearest neighbors come from its own source. Near-duplicates like these are why an image classifier's folds should be grouped by source.
36 of 36 images embedded with DINOv2-small (384 values each); the first two principal components hold 67% of the variation, and an image's nearest neighbor has a mean cosine similarity of 0.966. 85% of the 2 nearest neighbors share the image's source (8% by chance).
- Images embedded
- 36
- Mean nearest-neighbor similarity
- 0.9664
- Map trustworthiness (k = 10)
- 0.9869
- Neighbors sharing source
- 84.7%
Nearest neighbors (first 50 images)
| Row | Image | Neighbor 1 | Similarity 1 | Neighbor 2 | Similarity 2 |
|---|---|---|---|---|---|
| 1 | eaaf0b653783a80d9368c543de2d3b6d3653e67591914bbf07f3d059e505b9af | 11 | 0.9647 | 2 | 0.9592 |
| 2 | 1616969906495a3b1e73ed3fd06d130cc7bd0e3869229c661e7c5095c817486e | 1 | 0.9592 | 3 | 0.9555 |
| 3 | d8dccd3eb1494976deecb62ba4a908a2e51df416dc2adb0c10ac609a6dc2e126 | 2 | 0.9555 | 1 | 0.8824 |
| 4 | bc96f5687bf15cdd245ad8df8c765de59787847fb0882b9864f8804c3c060f6d | 5 | 0.9680 | 6 | 0.8949 |
| 5 | bee897f25cb41fbfb6ad00818c58bde4180b58cab4ad348159b9cd0c41bc3d4d | 4 | 0.9680 | 6 | 0.9539 |
| 6 | f74ac9c268e859385d8e9b2f9130f7f091cf8b9a17a5d67be5384d5c8a7c38f1 | 5 | 0.9539 | 10 | 0.9023 |
| 7 | 45ad4af12ce82a0a05bc3a05daa3b889d28351accfbd87ce35083a8f290c6937 | 8 | 0.9876 | 9 | 0.9766 |
| 8 | 5f3599c5f9cbac623f63e69cf9066bec83c510426ac9c869130cbb0a8cff5864 | 9 | 0.9891 | 7 | 0.9876 |
| 9 | 2cf42103f66d4d63582a5df5625d218687bb285288d6c980703790ba9e49a72b | 8 | 0.9891 | 7 | 0.9766 |
| 10 | 3cce226bf4f0867bcdccb746b3842c82cc7c0231b3429a3ed034de55bfba914c | 12 | 0.9892 | 11 | 0.9871 |
| 11 | 3270ef987ee35ffc8b442944628367ecf657aece9d3df57a8975a7f0c32eab19 | 12 | 0.9914 | 10 | 0.9871 |
| 12 | e526022983f99deb3a7710f13f6f42d9f0cfa57fbdea4c18cb8cfb82629e1619 | 11 | 0.9914 | 10 | 0.9892 |
| 13 | a5b4d35cf856a06f1a8260dfa5ea16eed7faebac1b1bed4098a2eb23afafa2ce | 14 | 0.9789 | 15 | 0.9675 |
| 14 | afe329016b29c5e0774f9db39a73b3646fe19554a9d7169142d3594c0bdd722c | 15 | 0.9916 | 13 | 0.9789 |
| 15 | 311aa9cef09e541ea7ee4f941338147e9ca86001b400950f04371743a901d3f3 | 14 | 0.9916 | 13 | 0.9675 |
| 16 | 93b3aacc37a5a3197f9dab54338ae78997254b9a47fcb782a0945ff7b92a368d | 17 | 0.9835 | 18 | 0.9668 |
| 17 | 4c7c29f5e28b50a5100896a01f05b103006136f1a5dba15557839e51f4ac7d1e | 18 | 0.9861 | 16 | 0.9835 |
| 18 | 2783f8f0767e286ebbddcd1ddd890c8850b7eaf1471cb1708ee7ec450e43fb89 | 17 | 0.9861 | 16 | 0.9668 |
| 19 | cd7c11335d85e04a83593d5a73dfc735674964cc215737296cc7284b416cb418 | 20 | 0.9713 | 18 | 0.9266 |
| 20 | 5e23d8f9c5002195cb21b605ce176a094c0fe5e7bd3e90e97e03ec8293d9b161 | 19 | 0.9713 | 21 | 0.9558 |
| 21 | 81a9721a6f524c9ed85e2686492a542649a745a7617c969eb36d711f0a173916 | 20 | 0.9558 | 19 | 0.9096 |
| 22 | 1a1b1b36104cda0082711a0a4594c7f766d02ee20cb959a8d92ecdc6bfb1bbdc | 23 | 0.9218 | 4 | 0.8647 |
| 23 | 4743b825b1e80f2a8580f5f010aae3a26b19e11e64d8ba4da95e575a060162e6 | 24 | 0.9656 | 22 | 0.9218 |
| 24 | 7c268eab4ba13c664e8ca27e8c484d1393082db348e60a4350830428fb911776 | 23 | 0.9656 | 20 | 0.8765 |
| 25 | e3737254bb3a8bce5fe2c0a132802c752aae36058164fde6c2451f5d30e7e960 | 26 | 0.9590 | 27 | 0.9405 |
| 26 | 8c189a553b7052eb0c69ad5e655eb776ac86058481919a427a8e37560aac5c7c | 25 | 0.9590 | 27 | 0.9246 |
| 27 | 2b0292d936322add6f739c62dc184ebb5b16ad7a79780ea89a9eec9dbe2d56a6 | 25 | 0.9405 | 26 | 0.9246 |
| 28 | d655214257593e45321b63942391256a1bc4cb295b2183db9d8c2350efc8497e | 34 | 0.9308 | 33 | 0.9287 |
| 29 | 8150c74699bef1fd8847d821fcf56048d17198cb049df30e2b34cec16c089cc6 | 31 | 0.9596 | 33 | 0.9283 |
| 30 | bd7b31d3a8d51cfd64a9d2bc53901a56264d6a172fd7adfec6d57b0908b5b421 | 26 | 0.9106 | 28 | 0.9076 |
| 31 | 3071561e17a806103735a820928c848308ff0eef0fcd085cfae15b313482f768 | 29 | 0.9596 | 33 | 0.9440 |
| 32 | 4f28d467498ba362a0c9490ff305722dbb29f2f8dcdcd51faa129f43be9ec33f | 33 | 0.9634 | 31 | 0.9183 |
| 33 | 94fa37138390f0c23343c075b06fbb6cfeb5bb360e53e15dcf62f98570348ece | 32 | 0.9634 | 31 | 0.9440 |
| 34 | dbb38fe99552de6e9d1aa43e515c45593b15cc142206bd47fba4d47787e1eb09 | 35 | 0.9574 | 36 | 0.9547 |
| 35 | a2d74e916b6de16197dacdc67ad528dcad7d1f2e2482805d904a4a46affcdb9d | 34 | 0.9574 | 36 | 0.9496 |
| 36 | 9a3571488647fead3c8941992995b4c9d23def741e3ace04bfeaa8da12ec6640 | 34 | 0.9547 | 35 | 0.9496 |
The exact R script · R R version 4.5.1 (2025-06-13)
# Image embeddings, map and neighbors (DINOv2 or ResNet-50)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method embed.images 1.0.0 · spec 6a5fc2dd4d52b27a
# Dataset: img1_shapes (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr)
suppressPackageStartupMessages(library(uwot))
# %% Data: the image column (and the label to color by)
IMAGE <- "path"
LABEL <- "source"
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/img1_shapes.parquet", col_select = c(IMAGE, LABEL)))
df <- cs_imgcls_attach_columns(df, "tests/parity/fixtures/img1_shapes.parquet", IMAGE) # media_id, for a media collection
warnings <- list()
# %% 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\":\"triangle\",\"fit\":\"shorter_center_crop\",\"mode\":\"rgb\",\"normalize\":\"none\",\"size\":[56,56]}}", simplifyVector = FALSE), "target/academy-parity/run-97231/embed.images/dinov2_umap_by_source/out-r", df,
"tests/parity/fixtures/img1_shapes.parquet")
media_ids <- cs_media_ids(media, df)
ok <- cs_imgemb_usable(media, media_ids, IMAGE)
rows <- ok$rows
if (ok$n_missing + ok$n_unreadable > 0) {
warnings <- c(warnings, sprintf("%d of %d rows have no readable image (%d without a path); they are left out of the map and their embedding stays empty.",
ok$n_missing + ok$n_unreadable, nrow(df), ok$n_missing))
}
# %% Embeddings: DINOv2-small on 56 x 56 images (float64 under Parity)
ENCODER <- "dinov2_small"
E <- cs_encoder_embed(ENCODER, media, batch_size = 16L, ids = ok$ids)
D <- ncol(E)
# %% 2-D map and nearest neighbors (cosine)
kk <- min(15L, length(rows) - 1L)
Y <- uwot::umap(E, n_neighbors = kk, min_dist = 0.1, n_components = 2, metric = "euclidean", n_epochs = 500,
nn_method = cs_ml_exact_knn(E, kk), init = cs_ml_pca_init(E, 10), n_threads = 1, n_sgd_threads = 0,
seed = 42) # host graph and start shared with Python (as discover.umap)
shares <- cs_imgemb_pca_map(E)$shares
MAP_LABEL <- "UMAP"
K <- as.integer(min(2, length(rows) - 1L))
nn <- cs_imgemb_cosine_knn(E, K)
labels <- if (!is.null(LABEL)) df[[LABEL]][rows + 1L] else NULL
la <- if (!is.null(LABEL)) cs_imgemb_label_agreement(nn$idx, labels) else list(agreement = NULL, chance = NULL)
sample <- cs_ml_sample_rows(length(rows))
k_eval <- min(10L, length(sample) - 2L)
trust <- if (k_eval >= 1L) cs_ml_trustworthiness(E[sample, , drop = FALSE], Y[sample, , drop = FALSE], k_eval) else NULL
# %% Artifacts: embeddings (saved like any Discover embedding) and neighbors
out <- cs_ml_out_dir("target/academy-parity/run-97231/embed.images/dinov2_umap_by_source/out-r")
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"))
nb <- data.frame(row = rep(as.integer(rows), each = K), rank = rep(seq_len(K), times = length(rows)),
neighbor = as.integer(rows[as.vector(t(nn$idx)) + 1L]), similarity = as.vector(t(nn$sim)))
nanoparquet::write_parquet(nb, file.path(out, "neighbors.parquet"))
# %% Result
values <- list(
n_rows = nrow(df), n_images = length(rows), n_missing = ok$n_missing, n_unreadable = ok$n_unreadable, dim = D,
neighbors = K, map_share_1 = shares[1], map_share_2 = shares[2], mean_nn_similarity = mean(nn$sim[, 1]),
trustworthiness = trust, label_agreement = la$agreement, label_agreement_chance = la$chance
)
for (j in seq_len(min(3L, D))) values[[sprintf("emb_check[%d]", j)]] <- cs_ml_checksum(E[, j], rows)
pick <- cs_ml_sample_rows(length(rows), 5000)
grp <- if (is.null(LABEL)) rep("All images", length(pick)) else {
v <- as.character(df[[LABEL]][rows[pick] + 1L]); ifelse(is.na(v), "(missing)", v)
}
charts <- list(cs_chart("map", "cluster-scatter",
sprintf("Image map (%s)", if (MAP_LABEL == "UMAP") "umap" else "principal components 1 and 2"),
list(x = cs_col(paste(MAP_LABEL, 1), Y[pick, 1], "numeric"), y = cs_col(paste(MAP_LABEL, 2), Y[pick, 2], "numeric"),
cluster = cs_col(if (is.null(LABEL)) "Group" else LABEL, grp, "categorical")),
note = if (length(pick) == length(rows)) NULL else sprintf("%s of %s images shown.", format(length(pick), big.mark = ","), format(length(rows), big.mark = ","))))
picks <- cs_ml_sample_rows(length(rows), 4) - 1L
charts[[2]] <- cs_imgcls_image_chart("neighbors", "image-gallery", sprintf("Nearest neighbors of %d images", length(picks)),
cs_imgemb_gallery_rows(media, ok$ids, rows, nn$idx, nn$sim, picks),
"Each line starts with an image and shows its closest images by cosine similarity (the number under each).")
trows <- lapply(seq_len(min(50L, length(rows))), function(i) {
r <- list(row = rows[i] + 1L, media_id = ok$ids[i])
for (k in seq_len(K)) {
r[[sprintf("n%d", k)]] <- rows[nn$idx[i, k] + 1L] + 1L
r[[sprintf("s%d", k)]] <- nn$sim[i, k]
}
r
})
cols <- c(list(list(key = "row", label = "Row", type = "integer"), list(key = "media_id", label = "Image")),
unlist(lapply(seq_len(K), function(k) list(list(key = sprintf("n%d", k), label = sprintf("Neighbor %d", k), type = "integer"),
list(key = sprintf("s%d", k), label = sprintf("Similarity %d", k), type = "number"))), recursive = FALSE))
tables <- list(list(key = "neighbors", title = "Nearest neighbors (first 50 images)", columns = cols, rows = trows))
summary <- sprintf("%d of %d images embedded with %s (%d values each); the first two principal components hold %s of the variation, and an image's nearest neighbor has a mean cosine similarity of %.3f.",
length(rows), nrow(df), cs_encoder_get(ENCODER)$label, D, sprintf("%.0f%%", 100 * (shares[1] + shares[2])), values$mean_nn_similarity)
if (!is.null(la$agreement)) summary <- paste0(summary, sprintf(" %s of the %d nearest neighbors share the image's %s (%s by chance).",
sprintf("%.0f%%", 100 * (la$agreement)), K, LABEL, sprintf("%.0f%%", 100 * (la$chance))))
stats <- list(list(key = "n_images", label = "Images embedded", value = length(rows)),
list(key = "mean_nn_similarity", label = "Mean nearest-neighbor similarity", value = values$mean_nn_similarity))
if (!is.null(trust)) stats[[length(stats) + 1L]] <- list(key = "trustworthiness", label = sprintf("Map trustworthiness (k = %d)", k_eval), value = trust)
if (!is.null(la$agreement)) stats[[length(stats) + 1L]] <- list(key = "label_agreement", label = sprintf("Neighbors sharing %s", LABEL), value = la$agreement, format = "percent")
cs_publish(list(
title = "Image embeddings, map and neighbors (DINOv2 or ResNet-50)",
engine = cs_engine_info("torch", "nanoparquet", "uwot"),
n = length(rows),
summary = summary,
statistics = stats,
charts = charts,
tables = tables,
values = values,
warnings = warnings,
artifacts = list(
list(key = "embedding", path = file.path(out, "embedding.parquet"), format = "parquet"),
list(key = "neighbors", path = file.path(out, "neighbors.parquet"), format = "parquet")
)
))
36 of 36 images embedded with DINOv2-small (384 values each); the first two principal components hold 67% of the variation, and an image's nearest neighbor has a mean cosine similarity of 0.966. 85% of the 2 nearest neighbors share the image's source (8% by chance).
- Images embedded
- 36
- Mean nearest-neighbor similarity
- 0.9664
- Map trustworthiness (k = 10)
- 0.9839
- Neighbors sharing source
- 84.7%
Nearest neighbors (first 50 images)
| Row | Image | Neighbor 1 | Similarity 1 | Neighbor 2 | Similarity 2 |
|---|---|---|---|---|---|
| 1 | eaaf0b653783a80d9368c543de2d3b6d3653e67591914bbf07f3d059e505b9af | 11 | 0.9647 | 2 | 0.9592 |
| 2 | 1616969906495a3b1e73ed3fd06d130cc7bd0e3869229c661e7c5095c817486e | 1 | 0.9592 | 3 | 0.9555 |
| 3 | d8dccd3eb1494976deecb62ba4a908a2e51df416dc2adb0c10ac609a6dc2e126 | 2 | 0.9555 | 1 | 0.8824 |
| 4 | bc96f5687bf15cdd245ad8df8c765de59787847fb0882b9864f8804c3c060f6d | 5 | 0.9680 | 6 | 0.8949 |
| 5 | bee897f25cb41fbfb6ad00818c58bde4180b58cab4ad348159b9cd0c41bc3d4d | 4 | 0.9680 | 6 | 0.9539 |
| 6 | f74ac9c268e859385d8e9b2f9130f7f091cf8b9a17a5d67be5384d5c8a7c38f1 | 5 | 0.9539 | 10 | 0.9023 |
| 7 | 45ad4af12ce82a0a05bc3a05daa3b889d28351accfbd87ce35083a8f290c6937 | 8 | 0.9876 | 9 | 0.9766 |
| 8 | 5f3599c5f9cbac623f63e69cf9066bec83c510426ac9c869130cbb0a8cff5864 | 9 | 0.9891 | 7 | 0.9876 |
| 9 | 2cf42103f66d4d63582a5df5625d218687bb285288d6c980703790ba9e49a72b | 8 | 0.9891 | 7 | 0.9766 |
| 10 | 3cce226bf4f0867bcdccb746b3842c82cc7c0231b3429a3ed034de55bfba914c | 12 | 0.9892 | 11 | 0.9871 |
| 11 | 3270ef987ee35ffc8b442944628367ecf657aece9d3df57a8975a7f0c32eab19 | 12 | 0.9914 | 10 | 0.9871 |
| 12 | e526022983f99deb3a7710f13f6f42d9f0cfa57fbdea4c18cb8cfb82629e1619 | 11 | 0.9914 | 10 | 0.9892 |
| 13 | a5b4d35cf856a06f1a8260dfa5ea16eed7faebac1b1bed4098a2eb23afafa2ce | 14 | 0.9789 | 15 | 0.9675 |
| 14 | afe329016b29c5e0774f9db39a73b3646fe19554a9d7169142d3594c0bdd722c | 15 | 0.9916 | 13 | 0.9789 |
| 15 | 311aa9cef09e541ea7ee4f941338147e9ca86001b400950f04371743a901d3f3 | 14 | 0.9916 | 13 | 0.9675 |
| 16 | 93b3aacc37a5a3197f9dab54338ae78997254b9a47fcb782a0945ff7b92a368d | 17 | 0.9835 | 18 | 0.9668 |
| 17 | 4c7c29f5e28b50a5100896a01f05b103006136f1a5dba15557839e51f4ac7d1e | 18 | 0.9861 | 16 | 0.9835 |
| 18 | 2783f8f0767e286ebbddcd1ddd890c8850b7eaf1471cb1708ee7ec450e43fb89 | 17 | 0.9861 | 16 | 0.9668 |
| 19 | cd7c11335d85e04a83593d5a73dfc735674964cc215737296cc7284b416cb418 | 20 | 0.9713 | 18 | 0.9266 |
| 20 | 5e23d8f9c5002195cb21b605ce176a094c0fe5e7bd3e90e97e03ec8293d9b161 | 19 | 0.9713 | 21 | 0.9558 |
| 21 | 81a9721a6f524c9ed85e2686492a542649a745a7617c969eb36d711f0a173916 | 20 | 0.9558 | 19 | 0.9096 |
| 22 | 1a1b1b36104cda0082711a0a4594c7f766d02ee20cb959a8d92ecdc6bfb1bbdc | 23 | 0.9218 | 4 | 0.8647 |
| 23 | 4743b825b1e80f2a8580f5f010aae3a26b19e11e64d8ba4da95e575a060162e6 | 24 | 0.9656 | 22 | 0.9218 |
| 24 | 7c268eab4ba13c664e8ca27e8c484d1393082db348e60a4350830428fb911776 | 23 | 0.9656 | 20 | 0.8765 |
| 25 | e3737254bb3a8bce5fe2c0a132802c752aae36058164fde6c2451f5d30e7e960 | 26 | 0.9590 | 27 | 0.9405 |
| 26 | 8c189a553b7052eb0c69ad5e655eb776ac86058481919a427a8e37560aac5c7c | 25 | 0.9590 | 27 | 0.9246 |
| 27 | 2b0292d936322add6f739c62dc184ebb5b16ad7a79780ea89a9eec9dbe2d56a6 | 25 | 0.9405 | 26 | 0.9246 |
| 28 | d655214257593e45321b63942391256a1bc4cb295b2183db9d8c2350efc8497e | 34 | 0.9308 | 33 | 0.9287 |
| 29 | 8150c74699bef1fd8847d821fcf56048d17198cb049df30e2b34cec16c089cc6 | 31 | 0.9596 | 33 | 0.9283 |
| 30 | bd7b31d3a8d51cfd64a9d2bc53901a56264d6a172fd7adfec6d57b0908b5b421 | 26 | 0.9106 | 28 | 0.9076 |
| 31 | 3071561e17a806103735a820928c848308ff0eef0fcd085cfae15b313482f768 | 29 | 0.9596 | 33 | 0.9440 |
| 32 | 4f28d467498ba362a0c9490ff305722dbb29f2f8dcdcd51faa129f43be9ec33f | 33 | 0.9634 | 31 | 0.9183 |
| 33 | 94fa37138390f0c23343c075b06fbb6cfeb5bb360e53e15dcf62f98570348ece | 32 | 0.9634 | 31 | 0.9440 |
| 34 | dbb38fe99552de6e9d1aa43e515c45593b15cc142206bd47fba4d47787e1eb09 | 35 | 0.9574 | 36 | 0.9547 |
| 35 | a2d74e916b6de16197dacdc67ad528dcad7d1f2e2482805d904a4a46affcdb9d | 34 | 0.9574 | 36 | 0.9496 |
| 36 | 9a3571488647fead3c8941992995b4c9d23def741e3ace04bfeaa8da12ec6640 | 34 | 0.9547 | 35 | 0.9496 |
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Image embeddings, map and neighbors (DINOv2 or ResNet-50)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method embed.images 1.0.0 · spec 6a5fc2dd4d52b27a
# Dataset: img1_shapes (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 encoders
from codesplash import ml as csml
from codesplash.images import embed_images as eimg # twin of codesplashr cs_imgemb_* (same encoder, map and neighbors)
from codesplash.images.classifier import attach_columns, image_chart
from codesplash.ml import embed as csembed
# %% Data: the image column (and the label to color by)
IMAGE = "path"
LABEL = "source"
df = pd.read_parquet("tests/parity/fixtures/img1_shapes.parquet", columns=[IMAGE] + ([LABEL] if LABEL else []))
df = attach_columns(df, "tests/parity/fixtures/img1_shapes.parquet", IMAGE) # media_id, for a media collection
warnings = []
# %% 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\":\"triangle\",\"fit\":\"shorter_center_crop\",\"mode\":\"rgb\",\"normalize\":\"none\",\"size\":[56,56]}}"), "target/academy-parity/run-97231/embed.images/dinov2_umap_by_source/out-python", df, "tests/parity/fixtures/img1_shapes.parquet")
media_ids = cs_media.ids_of(media, df)
ok = eimg.usable(media, media_ids, IMAGE)
rows = ok["rows"]
if ok["n_missing"] or ok["n_unreadable"]:
warnings.append(f"{ok['n_missing'] + ok['n_unreadable']} of {len(df)} rows have no readable image ({ok['n_missing']} without a path); they are left out of the map and their embedding stays empty.")
# %% Embeddings: DINOv2-small on 56 × 56 images (float64 under Parity)
ENCODER = "dinov2_small"
E = encoders.embed(ENCODER, media, ids=ok["ids"], batch_size=16)
D = E.shape[1]
# %% 2-D map and nearest neighbors (cosine)
import warnings as _warnings
import umap
kk = min(15, len(rows) - 1)
knn_idx, knn_dist = csembed.exact_knn(E, kk) # host graph and start shared with R (as discover.umap)
with _warnings.catch_warnings():
_warnings.simplefilter("ignore")
Y = umap.UMAP(n_neighbors=kk, min_dist=0.1, n_components=2, metric="euclidean", n_epochs=500, init=csembed.pca_init(E, 10.0),
random_state=42, n_jobs=1, precomputed_knn=(knn_idx, knn_dist, None)).fit_transform(E)
_, shares = eimg.pca_map(E)
MAP_LABEL = "UMAP"
K = min(2, len(rows) - 1)
nn_idx, nn_sim = eimg.cosine_knn(E, K)
labels = df[LABEL].iloc[rows].tolist() if LABEL else None
agree, chance = eimg.label_agreement(nn_idx, labels) if LABEL else (None, None)
sample = csembed.sample_rows(len(rows))
k_eval = min(10, len(sample) - 2)
trust = csembed.trustworthiness(E[sample], Y[sample], k_eval) if k_eval >= 1 else None
# %% Artifacts: embeddings (saved like any Discover embedding) and neighbors
out = csml.out_dir("target/academy-parity/run-97231/embed.images/dinov2_umap_by_source/out-python")
emb = pd.DataFrame({"row": rows.astype(np.int64), **{f"dim_{j + 1}": E[:, j] for j in range(D)}})
emb.to_parquet(os.path.join(out, "embedding.parquet"), index=False)
nb = pd.DataFrame({
"row": np.repeat(rows, K).astype(np.int64),
"rank": np.tile(np.arange(1, K + 1), len(rows)).astype(np.int64),
"neighbor": rows[nn_idx.reshape(-1)].astype(np.int64),
"similarity": nn_sim.reshape(-1),
})
nb.to_parquet(os.path.join(out, "neighbors.parquet"), index=False)
# %% Result
values = {
"n_rows": len(df),
"n_images": len(rows),
"n_missing": ok["n_missing"],
"n_unreadable": ok["n_unreadable"],
"dim": D,
"neighbors": K,
"map_share_1": float(shares[0]),
"map_share_2": float(shares[1]),
"mean_nn_similarity": float(np.mean(nn_sim[:, 0])),
"trustworthiness": trust,
"label_agreement": agree,
"label_agreement_chance": chance,
}
for j in range(min(3, D)):
values[f"emb_check[{j + 1}]"] = csembed.checksum(E[:, j], rows)
pick = csembed.sample_rows(len(rows), 5000)
grp = [("All images" if LABEL is None else ("(missing)" if pd.isna(v) else str(v))) for v in (df[LABEL].iloc[rows[pick]] if LABEL else [None] * len(pick))]
charts = [cs.chart("map", "cluster-scatter", f"Image map ({MAP_LABEL.lower() if MAP_LABEL == 'UMAP' else 'principal components 1 and 2'})", {
"x": cs.col(f"{MAP_LABEL} 1", Y[pick, 0], "numeric"),
"y": cs.col(f"{MAP_LABEL} 2", Y[pick, 1], "numeric"),
"cluster": cs.col(LABEL or "Group", grp, "categorical"),
}, note=None if len(pick) == len(rows) else f"{len(pick):,} of {len(rows):,} images shown.")]
picks = csembed.sample_rows(len(rows), 4)
charts.append(image_chart("neighbors", "image-gallery", f"Nearest neighbors of {len(picks)} images", eimg.gallery_rows(media, ok["ids"], rows, nn_idx, nn_sim, picks),
"Each line starts with an image and shows its closest images by cosine similarity (the number under each)."))
table_rows = [{"row": int(rows[i]) + 1, "media_id": ok["ids"][i], **{f"n{r + 1}": int(rows[nn_idx[i, r]]) + 1 for r in range(K)},
**{f"s{r + 1}": float(nn_sim[i, r]) for r in range(K)}} for i in range(min(50, len(rows)))]
tables = [{
"key": "neighbors",
"title": "Nearest neighbors (first 50 images)",
"columns": [{"key": "row", "label": "Row", "type": "integer"}, {"key": "media_id", "label": "Image"}]
+ [c for r in range(K) for c in ({"key": f"n{r + 1}", "label": f"Neighbor {r + 1}", "type": "integer"}, {"key": f"s{r + 1}", "label": f"Similarity {r + 1}", "type": "number"})],
"rows": table_rows,
}]
summary = (
f"{len(rows)} of {len(df)} images embedded with {encoders.get(ENCODER).label} ({D} values each); the first two principal components hold "
f"{shares[0] + shares[1]:.0%} of the variation, and an image's nearest neighbor has a mean cosine similarity of {values['mean_nn_similarity']:.3f}."
)
if agree is not None:
summary += f" {agree:.0%} of the {K} nearest neighbors share the image's {LABEL} ({chance:.0%} by chance)."
cs.publish({
"title": "Image embeddings, map and neighbors (DINOv2 or ResNet-50)",
"engine": cs.engine_info("torch", "numpy", "pandas", "umap-learn"),
"n": len(rows),
"summary": summary,
"statistics": [
{"key": "n_images", "label": "Images embedded", "value": len(rows)},
{"key": "mean_nn_similarity", "label": "Mean nearest-neighbor similarity", "value": values["mean_nn_similarity"]},
] + ([{"key": "trustworthiness", "label": f"Map trustworthiness (k = {k_eval})", "value": trust}] if trust is not None else [])
+ ([{"key": "label_agreement", "label": f"Neighbors sharing {LABEL}", "value": agree, "format": "percent"}] if agree is not None else []),
"charts": charts,
"tables": tables,
"values": values,
"warnings": warnings,
"artifacts": [
{"key": "embedding", "path": os.path.join(out, "embedding.parquet"), "format": "parquet"},
{"key": "neighbors", "path": os.path.join(out, "neighbors.parquet"), "format": "parquet"},
],
})
Shortened for the Academy: 2 chart(s) dropped to stay under 100 KB; 2 chart(s) dropped to stay under 100 KB.
UMAP keeps close neighbors close and separates clusters well, but distances between clusters mean little, and Python and R lay it out differently. The principal-component map is exact and the same in both engines.
Check your understanding
CheckpointCheck yourself
Two images have a cosine similarity of 0.98 in DINOv2's space. What does that suggest?
Show the answer
Answer: a
Cosine similarity compares the directions of the two vectors. Near 1 means the network describes the images almost the same way; it is not a pixel overlap or a class probability.
Check yourself
Two images sit far apart on the PCA map but are listed as nearest neighbors. Which do you trust?
Show the answer
Answer: b
The first two principal components hold only part of the variation. Images that differ along those two directions can still be close in the full space the neighbors come from.
Save the vectors
In the appIn Discover → Images, choose Image embeddings with the path column of an image folder. Save to dataset adds the vectors as columns, ready for clustering, anomaly detection or any learner; a run without a label still lists neighbors, here with a mean nearest-neighbor similarity of 0.964 for ResNet-50.
Concepts in this lesson