Skip to content

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.

Applied ~10 min6 steps

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

01

A vector for every picture

Read

A 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.

Image embeddings, map and neighbors (DINOv2 or ResNet-50)Recorded · Python and R agreeRecorded 2026-11-25 · 15 values compared
R

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)

RowImageNeighbor 1Similarity 1Neighbor 2Similarity 2Neighbor 3Similarity 3Neighbor 4Similarity 4Neighbor 5Similarity 5
1eaaf0b653783a80d9368c543de2d3b6d3653e67591914bbf07f3d059e505b9af110.964720.9592120.9551100.944530.8824
21616969906495a3b1e73ed3fd06d130cc7bd0e3869229c661e7c5095c817486e10.959230.9555110.9182100.9075120.9043
3d8dccd3eb1494976deecb62ba4a908a2e51df416dc2adb0c10ac609a6dc2e12620.955510.8824100.8639110.852360.8434
4bc96f5687bf15cdd245ad8df8c765de59787847fb0882b9864f8804c3c060f6d50.968060.8949220.864730.8401230.7735
5bee897f25cb41fbfb6ad00818c58bde4180b58cab4ad348159b9cd0c41bc3d4d40.968060.9539220.864030.8392100.8212
6f74ac9c268e859385d8e9b2f9130f7f091cf8b9a17a5d67be5384d5c8a7c38f150.9539100.902340.8949110.8778120.8720
745ad4af12ce82a0a05bc3a05daa3b889d28351accfbd87ce35083a8f290c693780.987690.9766120.9023100.8958110.8860
85f3599c5f9cbac623f63e69cf9066bec83c510426ac9c869130cbb0a8cff586490.989170.9876120.9227100.9162110.9076
92cf42103f66d4d63582a5df5625d218687bb285288d6c980703790ba9e49a72b80.989170.9766120.9294100.9209110.9189
103cce226bf4f0867bcdccb746b3842c82cc7c0231b3429a3ed034de55bfba914c120.9892110.987110.944590.920980.9162
113270ef987ee35ffc8b442944628367ecf657aece9d3df57a8975a7f0c32eab19120.9914100.987110.964790.918920.9182
12e526022983f99deb3a7710f13f6f42d9f0cfa57fbdea4c18cb8cfb82629e1619110.9914100.989210.955190.929480.9227
13a5b4d35cf856a06f1a8260dfa5ea16eed7faebac1b1bed4098a2eb23afafa2ce140.9789150.9675160.8883170.8565200.8531
14afe329016b29c5e0774f9db39a73b3646fe19554a9d7169142d3594c0bdd722c150.9916130.9789160.9114170.8848180.8708
15311aa9cef09e541ea7ee4f941338147e9ca86001b400950f04371743a901d3f3140.9916130.9675160.9140170.8810200.8716
1693b3aacc37a5a3197f9dab54338ae78997254b9a47fcb782a0945ff7b92a368d170.9835180.9668200.9415150.9140190.9135
174c7c29f5e28b50a5100896a01f05b103006136f1a5dba15557839e51f4ac7d1e180.9861160.9835200.9267190.9122210.8902
182783f8f0767e286ebbddcd1ddd890c8850b7eaf1471cb1708ee7ec450e43fb89170.9861160.9668200.9269190.9266210.8869
19cd7c11335d85e04a83593d5a73dfc735674964cc215737296cc7284b416cb418200.9713180.9266160.9135170.9122210.9096
205e23d8f9c5002195cb21b605ce176a094c0fe5e7bd3e90e97e03ec8293d9b161190.9713210.9558160.9415180.9269170.9267
2181a9721a6f524c9ed85e2686492a542649a745a7617c969eb36d711f0a173916200.9558190.9096160.9084170.8902180.8869
221a1b1b36104cda0082711a0a4594c7f766d02ee20cb959a8d92ecdc6bfb1bbdc230.921840.864750.8640240.819660.7965
234743b825b1e80f2a8580f5f010aae3a26b19e11e64d8ba4da95e575a060162e6240.9656220.9218160.8590200.8415170.8286
247c268eab4ba13c664e8ca27e8c484d1393082db348e60a4350830428fb911776230.9656200.8765190.8700160.8656180.8525
25e3737254bb3a8bce5fe2c0a132802c752aae36058164fde6c2451f5d30e7e960260.9590270.9405300.9074340.9033280.9009
268c189a553b7052eb0c69ad5e655eb776ac86058481919a427a8e37560aac5c7c250.9590270.9246300.9106340.8908320.8797
272b0292d936322add6f739c62dc184ebb5b16ad7a79780ea89a9eec9dbe2d56a6250.9405260.9246340.9194280.9169350.9084
28d655214257593e45321b63942391256a1bc4cb295b2183db9d8c2350efc8497e340.9308330.9287270.9169290.9100300.9076
298150c74699bef1fd8847d821fcf56048d17198cb049df30e2b34cec16c089cc6310.9596330.9283320.9136280.9100340.8650
30bd7b31d3a8d51cfd64a9d2bc53901a56264d6a172fd7adfec6d57b0908b5b421260.9106280.9076250.9074270.8806320.8731
313071561e17a806103735a820928c848308ff0eef0fcd085cfae15b313482f768290.9596330.9440320.9183280.8937360.8597
324f28d467498ba362a0c9490ff305722dbb29f2f8dcdcd51faa129f43be9ec33f330.9634310.9183290.9136270.9081280.9061
3394fa37138390f0c23343c075b06fbb6cfeb5bb360e53e15dcf62f98570348ece320.9634310.9440280.9287290.9283340.8982
34dbb38fe99552de6e9d1aa43e515c45593b15cc142206bd47fba4d47787e1eb09350.9574360.9547280.9308270.9194250.9033
35a2d74e916b6de16197dacdc67ad528dcad7d1f2e2482805d904a4a46affcdb9d340.9574360.9496270.9084280.8886260.8788
369a3571488647fead3c8941992995b4c9d23def741e3ace04bfeaa8da12ec6640340.9547350.9496270.8944320.8911280.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")
  )
))
Python

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)

RowImageNeighbor 1Similarity 1Neighbor 2Similarity 2Neighbor 3Similarity 3Neighbor 4Similarity 4Neighbor 5Similarity 5
1eaaf0b653783a80d9368c543de2d3b6d3653e67591914bbf07f3d059e505b9af110.964720.9592120.9551100.944530.8824
21616969906495a3b1e73ed3fd06d130cc7bd0e3869229c661e7c5095c817486e10.959230.9555110.9182100.9075120.9043
3d8dccd3eb1494976deecb62ba4a908a2e51df416dc2adb0c10ac609a6dc2e12620.955510.8824100.8639110.852360.8434
4bc96f5687bf15cdd245ad8df8c765de59787847fb0882b9864f8804c3c060f6d50.968060.8949220.864730.8401230.7735
5bee897f25cb41fbfb6ad00818c58bde4180b58cab4ad348159b9cd0c41bc3d4d40.968060.9539220.864030.8392100.8212
6f74ac9c268e859385d8e9b2f9130f7f091cf8b9a17a5d67be5384d5c8a7c38f150.9539100.902340.8949110.8778120.8720
745ad4af12ce82a0a05bc3a05daa3b889d28351accfbd87ce35083a8f290c693780.987690.9766120.9023100.8958110.8860
85f3599c5f9cbac623f63e69cf9066bec83c510426ac9c869130cbb0a8cff586490.989170.9876120.9227100.9162110.9076
92cf42103f66d4d63582a5df5625d218687bb285288d6c980703790ba9e49a72b80.989170.9766120.9294100.9209110.9189
103cce226bf4f0867bcdccb746b3842c82cc7c0231b3429a3ed034de55bfba914c120.9892110.987110.944590.920980.9162
113270ef987ee35ffc8b442944628367ecf657aece9d3df57a8975a7f0c32eab19120.9914100.987110.964790.918920.9182
12e526022983f99deb3a7710f13f6f42d9f0cfa57fbdea4c18cb8cfb82629e1619110.9914100.989210.955190.929480.9227
13a5b4d35cf856a06f1a8260dfa5ea16eed7faebac1b1bed4098a2eb23afafa2ce140.9789150.9675160.8883170.8565200.8531
14afe329016b29c5e0774f9db39a73b3646fe19554a9d7169142d3594c0bdd722c150.9916130.9789160.9114170.8848180.8708
15311aa9cef09e541ea7ee4f941338147e9ca86001b400950f04371743a901d3f3140.9916130.9675160.9140170.8810200.8716
1693b3aacc37a5a3197f9dab54338ae78997254b9a47fcb782a0945ff7b92a368d170.9835180.9668200.9415150.9140190.9135
174c7c29f5e28b50a5100896a01f05b103006136f1a5dba15557839e51f4ac7d1e180.9861160.9835200.9267190.9122210.8902
182783f8f0767e286ebbddcd1ddd890c8850b7eaf1471cb1708ee7ec450e43fb89170.9861160.9668200.9269190.9266210.8869
19cd7c11335d85e04a83593d5a73dfc735674964cc215737296cc7284b416cb418200.9713180.9266160.9135170.9122210.9096
205e23d8f9c5002195cb21b605ce176a094c0fe5e7bd3e90e97e03ec8293d9b161190.9713210.9558160.9415180.9269170.9267
2181a9721a6f524c9ed85e2686492a542649a745a7617c969eb36d711f0a173916200.9558190.9096160.9084170.8902180.8869
221a1b1b36104cda0082711a0a4594c7f766d02ee20cb959a8d92ecdc6bfb1bbdc230.921840.864750.8640240.819660.7965
234743b825b1e80f2a8580f5f010aae3a26b19e11e64d8ba4da95e575a060162e6240.9656220.9218160.8590200.8415170.8286
247c268eab4ba13c664e8ca27e8c484d1393082db348e60a4350830428fb911776230.9656200.8765190.8700160.8656180.8525
25e3737254bb3a8bce5fe2c0a132802c752aae36058164fde6c2451f5d30e7e960260.9590270.9405300.9074340.9033280.9009
268c189a553b7052eb0c69ad5e655eb776ac86058481919a427a8e37560aac5c7c250.9590270.9246300.9106340.8908320.8797
272b0292d936322add6f739c62dc184ebb5b16ad7a79780ea89a9eec9dbe2d56a6250.9405260.9246340.9194280.9169350.9084
28d655214257593e45321b63942391256a1bc4cb295b2183db9d8c2350efc8497e340.9308330.9287270.9169290.9100300.9076
298150c74699bef1fd8847d821fcf56048d17198cb049df30e2b34cec16c089cc6310.9596330.9283320.9136280.9100340.8650
30bd7b31d3a8d51cfd64a9d2bc53901a56264d6a172fd7adfec6d57b0908b5b421260.9106280.9076250.9074270.8806320.8731
313071561e17a806103735a820928c848308ff0eef0fcd085cfae15b313482f768290.9596330.9440320.9183280.8937360.8597
324f28d467498ba362a0c9490ff305722dbb29f2f8dcdcd51faa129f43be9ec33f330.9634310.9183290.9136270.9081280.9061
3394fa37138390f0c23343c075b06fbb6cfeb5bb360e53e15dcf62f98570348ece320.9634310.9440280.9287290.9283340.8982
34dbb38fe99552de6e9d1aa43e515c45593b15cc142206bd47fba4d47787e1eb09350.9574360.9547280.9308270.9194250.9033
35a2d74e916b6de16197dacdc67ad528dcad7d1f2e2482805d904a4a46affcdb9d340.9574360.9496270.9084280.8886260.8788
369a3571488647fead3c8941992995b4c9d23def741e3ace04bfeaa8da12ec6640340.9547350.9496270.8944320.8911280.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.

02

The map and the neighbors

Read

The 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.

03

Do the vectors know the classes?

Predict

Predict 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?

About a third, as by chanceAbout two thirdsNearly all
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.

04

Shots of the same source

Read

Colored 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.

Image embeddings, map and neighbors (DINOv2 or ResNet-50)Recorded · Python and R agreeRecorded 2026-11-25 · 15 values compared · largest relative difference 3.0e-3
R

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)

RowImageNeighbor 1Similarity 1Neighbor 2Similarity 2
1eaaf0b653783a80d9368c543de2d3b6d3653e67591914bbf07f3d059e505b9af110.964720.9592
21616969906495a3b1e73ed3fd06d130cc7bd0e3869229c661e7c5095c817486e10.959230.9555
3d8dccd3eb1494976deecb62ba4a908a2e51df416dc2adb0c10ac609a6dc2e12620.955510.8824
4bc96f5687bf15cdd245ad8df8c765de59787847fb0882b9864f8804c3c060f6d50.968060.8949
5bee897f25cb41fbfb6ad00818c58bde4180b58cab4ad348159b9cd0c41bc3d4d40.968060.9539
6f74ac9c268e859385d8e9b2f9130f7f091cf8b9a17a5d67be5384d5c8a7c38f150.9539100.9023
745ad4af12ce82a0a05bc3a05daa3b889d28351accfbd87ce35083a8f290c693780.987690.9766
85f3599c5f9cbac623f63e69cf9066bec83c510426ac9c869130cbb0a8cff586490.989170.9876
92cf42103f66d4d63582a5df5625d218687bb285288d6c980703790ba9e49a72b80.989170.9766
103cce226bf4f0867bcdccb746b3842c82cc7c0231b3429a3ed034de55bfba914c120.9892110.9871
113270ef987ee35ffc8b442944628367ecf657aece9d3df57a8975a7f0c32eab19120.9914100.9871
12e526022983f99deb3a7710f13f6f42d9f0cfa57fbdea4c18cb8cfb82629e1619110.9914100.9892
13a5b4d35cf856a06f1a8260dfa5ea16eed7faebac1b1bed4098a2eb23afafa2ce140.9789150.9675
14afe329016b29c5e0774f9db39a73b3646fe19554a9d7169142d3594c0bdd722c150.9916130.9789
15311aa9cef09e541ea7ee4f941338147e9ca86001b400950f04371743a901d3f3140.9916130.9675
1693b3aacc37a5a3197f9dab54338ae78997254b9a47fcb782a0945ff7b92a368d170.9835180.9668
174c7c29f5e28b50a5100896a01f05b103006136f1a5dba15557839e51f4ac7d1e180.9861160.9835
182783f8f0767e286ebbddcd1ddd890c8850b7eaf1471cb1708ee7ec450e43fb89170.9861160.9668
19cd7c11335d85e04a83593d5a73dfc735674964cc215737296cc7284b416cb418200.9713180.9266
205e23d8f9c5002195cb21b605ce176a094c0fe5e7bd3e90e97e03ec8293d9b161190.9713210.9558
2181a9721a6f524c9ed85e2686492a542649a745a7617c969eb36d711f0a173916200.9558190.9096
221a1b1b36104cda0082711a0a4594c7f766d02ee20cb959a8d92ecdc6bfb1bbdc230.921840.8647
234743b825b1e80f2a8580f5f010aae3a26b19e11e64d8ba4da95e575a060162e6240.9656220.9218
247c268eab4ba13c664e8ca27e8c484d1393082db348e60a4350830428fb911776230.9656200.8765
25e3737254bb3a8bce5fe2c0a132802c752aae36058164fde6c2451f5d30e7e960260.9590270.9405
268c189a553b7052eb0c69ad5e655eb776ac86058481919a427a8e37560aac5c7c250.9590270.9246
272b0292d936322add6f739c62dc184ebb5b16ad7a79780ea89a9eec9dbe2d56a6250.9405260.9246
28d655214257593e45321b63942391256a1bc4cb295b2183db9d8c2350efc8497e340.9308330.9287
298150c74699bef1fd8847d821fcf56048d17198cb049df30e2b34cec16c089cc6310.9596330.9283
30bd7b31d3a8d51cfd64a9d2bc53901a56264d6a172fd7adfec6d57b0908b5b421260.9106280.9076
313071561e17a806103735a820928c848308ff0eef0fcd085cfae15b313482f768290.9596330.9440
324f28d467498ba362a0c9490ff305722dbb29f2f8dcdcd51faa129f43be9ec33f330.9634310.9183
3394fa37138390f0c23343c075b06fbb6cfeb5bb360e53e15dcf62f98570348ece320.9634310.9440
34dbb38fe99552de6e9d1aa43e515c45593b15cc142206bd47fba4d47787e1eb09350.9574360.9547
35a2d74e916b6de16197dacdc67ad528dcad7d1f2e2482805d904a4a46affcdb9d340.9574360.9496
369a3571488647fead3c8941992995b4c9d23def741e3ace04bfeaa8da12ec6640340.9547350.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")
  )
))
Python

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)

RowImageNeighbor 1Similarity 1Neighbor 2Similarity 2
1eaaf0b653783a80d9368c543de2d3b6d3653e67591914bbf07f3d059e505b9af110.964720.9592
21616969906495a3b1e73ed3fd06d130cc7bd0e3869229c661e7c5095c817486e10.959230.9555
3d8dccd3eb1494976deecb62ba4a908a2e51df416dc2adb0c10ac609a6dc2e12620.955510.8824
4bc96f5687bf15cdd245ad8df8c765de59787847fb0882b9864f8804c3c060f6d50.968060.8949
5bee897f25cb41fbfb6ad00818c58bde4180b58cab4ad348159b9cd0c41bc3d4d40.968060.9539
6f74ac9c268e859385d8e9b2f9130f7f091cf8b9a17a5d67be5384d5c8a7c38f150.9539100.9023
745ad4af12ce82a0a05bc3a05daa3b889d28351accfbd87ce35083a8f290c693780.987690.9766
85f3599c5f9cbac623f63e69cf9066bec83c510426ac9c869130cbb0a8cff586490.989170.9876
92cf42103f66d4d63582a5df5625d218687bb285288d6c980703790ba9e49a72b80.989170.9766
103cce226bf4f0867bcdccb746b3842c82cc7c0231b3429a3ed034de55bfba914c120.9892110.9871
113270ef987ee35ffc8b442944628367ecf657aece9d3df57a8975a7f0c32eab19120.9914100.9871
12e526022983f99deb3a7710f13f6f42d9f0cfa57fbdea4c18cb8cfb82629e1619110.9914100.9892
13a5b4d35cf856a06f1a8260dfa5ea16eed7faebac1b1bed4098a2eb23afafa2ce140.9789150.9675
14afe329016b29c5e0774f9db39a73b3646fe19554a9d7169142d3594c0bdd722c150.9916130.9789
15311aa9cef09e541ea7ee4f941338147e9ca86001b400950f04371743a901d3f3140.9916130.9675
1693b3aacc37a5a3197f9dab54338ae78997254b9a47fcb782a0945ff7b92a368d170.9835180.9668
174c7c29f5e28b50a5100896a01f05b103006136f1a5dba15557839e51f4ac7d1e180.9861160.9835
182783f8f0767e286ebbddcd1ddd890c8850b7eaf1471cb1708ee7ec450e43fb89170.9861160.9668
19cd7c11335d85e04a83593d5a73dfc735674964cc215737296cc7284b416cb418200.9713180.9266
205e23d8f9c5002195cb21b605ce176a094c0fe5e7bd3e90e97e03ec8293d9b161190.9713210.9558
2181a9721a6f524c9ed85e2686492a542649a745a7617c969eb36d711f0a173916200.9558190.9096
221a1b1b36104cda0082711a0a4594c7f766d02ee20cb959a8d92ecdc6bfb1bbdc230.921840.8647
234743b825b1e80f2a8580f5f010aae3a26b19e11e64d8ba4da95e575a060162e6240.9656220.9218
247c268eab4ba13c664e8ca27e8c484d1393082db348e60a4350830428fb911776230.9656200.8765
25e3737254bb3a8bce5fe2c0a132802c752aae36058164fde6c2451f5d30e7e960260.9590270.9405
268c189a553b7052eb0c69ad5e655eb776ac86058481919a427a8e37560aac5c7c250.9590270.9246
272b0292d936322add6f739c62dc184ebb5b16ad7a79780ea89a9eec9dbe2d56a6250.9405260.9246
28d655214257593e45321b63942391256a1bc4cb295b2183db9d8c2350efc8497e340.9308330.9287
298150c74699bef1fd8847d821fcf56048d17198cb049df30e2b34cec16c089cc6310.9596330.9283
30bd7b31d3a8d51cfd64a9d2bc53901a56264d6a172fd7adfec6d57b0908b5b421260.9106280.9076
313071561e17a806103735a820928c848308ff0eef0fcd085cfae15b313482f768290.9596330.9440
324f28d467498ba362a0c9490ff305722dbb29f2f8dcdcd51faa129f43be9ec33f330.9634310.9183
3394fa37138390f0c23343c075b06fbb6cfeb5bb360e53e15dcf62f98570348ece320.9634310.9440
34dbb38fe99552de6e9d1aa43e515c45593b15cc142206bd47fba4d47787e1eb09350.9574360.9547
35a2d74e916b6de16197dacdc67ad528dcad7d1f2e2482805d904a4a46affcdb9d340.9574360.9496
369a3571488647fead3c8941992995b4c9d23def741e3ace04bfeaa8da12ec6640340.9547350.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.

05

Check your understanding

Checkpoint

Check 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.

06

Save the vectors

In the app

In 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