Skip to content

CDiscover · embed.images

Image embeddings, map and neighbors (DINOv2 or ResNet-50)

Which images look alike? Turn each image into a vector with a pretrained network, map them and find each one's nearest neighbors.

Runs a pretrained vision network on this computer over a column of image files — DINOv2-small (self-supervised on 142 million images; 384 values) or ResNet-50 (ImageNet-1k; 2,048 values) — and turns each image into an embedding: images that look alike get nearby vectors. A 2-D map (principal components or UMAP) places similar images together, each image's nearest neighbors by cosine similarity are listed with thumbnails, and when a label is given the share of neighbors that share it shows how well the embedding separates the classes. The embeddings can be saved back to the dataset as columns for clustering, anomaly detection or any learner. Python and R compute the same vectors. The weights download once after you approve (about 90–100 MB).

Experimental Python and R agree to 6 decimals Seeded Also called image embeddings, image vectors, image similarity…

A real result

Example “Dinov2 pca by pattern”, recorded in both engines. In the app, “Try this example” loads it into Analyze.

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

Shortened for the Academy: 2 chart(s) dropped to stay under 100 KB; 2 chart(s) dropped to stay under 100 KB.

Do it in CodeSplash Run it on your own data. It's in the Experimental lane in the app.

Worked examples in the app

  • Dinov2 pca by patternimg1_shapes · image: path · label: pattern
  • Resnet50 neighbors no labelimg1_shapes · image: path
  • Dinov2 umap by sourceimg1_shapes · image: path · label: source
  • Degenerate all naimg1_shapes · image: path · label: pattern
  • Degenerate n1img1_shapes · image: path · label: pattern
  • Degenerate n2img1_shapes · image: path · label: pattern
  • Degenerate n3img1_shapes · image: path · label: pattern
  • Degenerate constantimg1_shapes · image: path · label: pattern

In the guides

Where it sits in the decision guides

  • Multimodal data exploration (text, image, video) · DS & ML Decision Guide · Describe — summarize and visualize
  • Representation learning (autoencoders, contrastive) · DS & ML Decision Guide · Discover — find structure without labels

What you need

Imagescategorical · 1 column
The column of image files (an image folder's path column). Each image is decoded once and resized to the image size below.
Color and check bycategorical / boolean · 0–1 column · 1–60 levels
Optional: a class or folder column that colors the map and checks how often neighbors share it; never used to compute the vectors.

Choices you make

model

Pretrained networkdefault dinov2_small

The network that turns each image into a vector. Both run on this computer after a one-time download you approve.

  • DINOv2-small (~90 MB)(default) — A small vision transformer trained without labels; its 384-value vectors put visually similar images close together.
  • ResNet-50 (~100 MB) — A convolutional network trained to name 1,000 ImageNet classes; 2,048 values that group images by object type.
Image size (pixels)default 224

Each image's shorter side is resized to this and the center cropped to a square. The networks were trained at 224; smaller is faster.

Mapdefault pca

How the vectors are drawn in two dimensions.

  • Principal components(default) — The two directions with the most variation; exact and the same in Python and R.
  • UMAP — Keeps each image's close neighbors close; better clusters, but distances between clusters mean little and the two engines' layouts differ.
Neighbors per imagedefault 5

How many most-similar images each image lists (by cosine similarity of the vectors).

Checks and remedies

CodeSplash checks each testable assumption on every run and shows the result on the card; premises the data can’t test are marked. If a check fails, these are the ways forward.

  • Images resemble photos

    Both networks learned from everyday photos; diagrams, scans or microscopy can embed poorly. Check that neighbors look alike.

  • The center holds the subject

    Images are center-cropped to a square, so content near the long edges of wide or tall images is cut off.

What it reports

n_rows
Rows with an image that could be read and embedded, out of all rows; rows without a path or with a broken file are left out.
n_images
Rows with an image that could be read and embedded, out of all rows; rows without a path or with a broken file are left out.
n_missing
Rows with an image that could be read and embedded, out of all rows; rows without a path or with a broken file are left out.
n_unreadable
Rows with an image that could be read and embedded, out of all rows; rows without a path or with a broken file are left out.
dim
Values in each image's vector (384 for DINOv2-small, 2,048 for ResNet-50) and how many nearest images are listed.
neighbors
Values in each image's vector (384 for DINOv2-small, 2,048 for ResNet-50) and how many nearest images are listed.
map_share_1
The share of the embeddings' total variation along principal components 1 and 2, the axes of the PCA map.
map_share_2
The share of the embeddings' total variation along principal components 1 and 2, the axes of the PCA map.
mean_nn_similarity
The cosine similarity of each image to its closest other image, averaged; near 1 means near-duplicates are common.
trustworthiness
How well the 2-D map keeps each image's close neighbors close (1 = no false neighbors among the 10 nearest).
label_agreement
The share of each image's nearest neighbors with the same label, against the share expected by chance (Σ p²).
label_agreement_chance
The share of each image's nearest neighbors with the same label, against the share expected by chance (Σ p²).

Per group, level or term: emb_check[<dim>]

Python and R

Python and R agree to 6 decimals (relative tolerance 1e-8). Python uses torch, safetensors, codesplash; R uses torch, codesplashr.

Default traps between the two languages

  • Both engines run the same encoder written out on LibTorch in double precision (codesplash.images.backbones ↔ codesplashr images_backbones.R) on the host's media tensors (identical bytes) and the same map and neighbor rules; matrix products use each engine's BLAS, so values agree to rounding (measured 2026-11-22: embeddings within 4e-14).
  • With the UMAP map, umap-learn and uwot start from the same host kNN graph and PCA layout but run their own stochastic gradient descent, so the map's trustworthiness is held to 3% (as discover.umap); the embeddings, neighbors and principal-component shares are compared at the default tolerance.
Python

The exact script CodeSplash ran for example “Dinov2 pca by pattern” · 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"},
    ],
})
R

The exact script CodeSplash ran for example “Dinov2 pca by pattern” · 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")
  )
))

Sources

  • Oquab M, Darcet T, Moutakanni T, et al. (2023). DINOv2: learning robust visual features without supervision. arXiv:2304.07193.
  • He K, Zhang X, Ren S, Sun J (2016). Deep residual learning for image recognition. CVPR 2016, 770–778.
  • Wightman R, Touvron H, Jégou H (2021). ResNet strikes back: an improved training procedure in timm. arXiv:2110.00476.
  • Venna J, Kaski S (2001). Neighborhood preservation in nonlinear projection methods: an experimental study. ICANN 2001, 485–491.
  • McInnes L, Healy J, Melville J (2018). UMAP: uniform manifold approximation and projection for dimension reduction. arXiv:1802.03426.

From the CodeSplash method registry · embed.images v1.0.0.