CDiscover · discover.image_anomaly
Image inspection anomalies (PaDiM, kNN)
Which images look unlike the known-good ones — scratches, spots, missing pieces — and how often would a good image raise a false alarm?
Learns what normal images look like from reference images (marked in a column, for example the train split or a "good" label) and scores every image by how far it strays. PaDiM-style patch Gaussian: each image is cut into a grid of patches described by color, contrast, gradients and sharpness, a Gaussian is fitted to every patch position over the reference images, and an image's score is its most unusual patch (the patch scores form its anomaly map). kNN distance: the mean distance to the nearest reference images. Part of the reference images is held back to calibrate the alarms: conformal p-values keep the false-alarm rate on good images at the level you choose. The scores, in order with the held-back reference images first, open in a control chart (phase I = reference). Runs on the decoded copies the app makes once per collection, identically in Python and R.
A real result
Example “Parts padim reference”, recorded in both engines. In the app, “Try this example” loads it into Analyze.
8 of 18 tested images are flagged as anomalies (false-alarm rate 0.05, 28 calibration images).
- Anomalies
- 8
- Images tested
- 18
- Calibration images
- 28
- Highest score
- 123.56
Plots
View data
| Flagged | Largest patch distance |
|---|---|
| false | 2.165 |
| false | 2.134 |
| false | 2.134 |
| false | 2.077 |
| false | 2.125 |
| false | 3.118 |
| false | 1.885 |
| false | 2.409 |
| false | 1.980 |
| false | 2.024 |
| false | 2.057 |
| false | 2.043 |
| false | 1.856 |
| false | 1.987 |
| false | 2.320 |
| false | 1.954 |
| false | 2.304 |
| false | 1.833 |
| false | 1.879 |
| false | 2.117 |
| false | 1.771 |
| false | 2.008 |
| false | 2.190 |
| false | 2.202 |
| false | 2.042 |
| false | 2.155 |
| false | 2.246 |
| false | 1.769 |
| false | 2.056 |
| false | 2.746 |
| false | 2.021 |
| false | 2.023 |
| false | 2.023 |
| false | 2.026 |
| false | 2.015 |
| false | 2.469 |
| false | 1.818 |
| false | 1.875 |
| false | 2.109 |
| false | 1.673 |
| false | 2.149 |
| false | 2.207 |
| false | 2.230 |
| false | 2.015 |
| false | 1.921 |
| false | 1.863 |
| false | 2.295 |
| false | 2.261 |
| false | 2.012 |
| false | 2.063 |
| false | 2.264 |
| false | 2.204 |
| false | 1.738 |
| false | 2.129 |
| false | 1.707 |
| false | 2.662 |
| false | 2.065 |
| false | 1.945 |
| false | 1.794 |
| true | 3.210 |
First 60 of 74 rows.
View data
| Patch column | Patch row | Mahalanobis distance |
|---|---|---|
| c1 | r1 | 0.5068 |
| c2 | r1 | 0.8162 |
| c3 | r1 | 0.8840 |
| c4 | r1 | 0.6934 |
| c5 | r1 | 0.2435 |
| c6 | r1 | 0.4036 |
| c7 | r1 | 0.6556 |
| c8 | r1 | 0.9375 |
| c1 | r2 | 0.7006 |
| c2 | r2 | 0.5628 |
| c3 | r2 | 1.428 |
| c4 | r2 | 1.337 |
| c5 | r2 | 1.720 |
| c6 | r2 | 1.577 |
| c7 | r2 | 0.5016 |
| c8 | r2 | 0.8314 |
| c1 | r3 | 1.022 |
| c2 | r3 | 1.886 |
| c3 | r3 | 34.494 |
| c4 | r3 | 3.303 |
| c5 | r3 | 0.9112 |
| c6 | r3 | 1.472 |
| c7 | r3 | 1.290 |
| c8 | r3 | 0.5595 |
| c1 | r4 | 0.3229 |
| c2 | r4 | 1.755 |
| c3 | r4 | 19.914 |
| c4 | r4 | 120.77 |
| c5 | r4 | 29.766 |
| c6 | r4 | 1.497 |
| c7 | r4 | 1.848 |
| c8 | r4 | 0.8055 |
| c1 | r5 | 1.196 |
| c2 | r5 | 1.335 |
| c3 | r5 | 1.033 |
| c4 | r5 | 29.770 |
| c5 | r5 | 123.56 |
| c6 | r5 | 22.680 |
| c7 | r5 | 1.362 |
| c8 | r5 | 0.8689 |
| c1 | r6 | 1.113 |
| c2 | r6 | 1.520 |
| c3 | r6 | 1.630 |
| c4 | r6 | 1.103 |
| c5 | r6 | 2.573 |
| c6 | r6 | 37.533 |
| c7 | r6 | 1.687 |
| c8 | r6 | 0.4656 |
| c1 | r7 | 1.004 |
| c2 | r7 | 0.5149 |
| c3 | r7 | 1.503 |
| c4 | r7 | 1.375 |
| c5 | r7 | 1.629 |
| c6 | r7 | 1.406 |
| c7 | r7 | 0.8440 |
| c8 | r7 | 1.033 |
| c1 | r8 | 0.6314 |
| c2 | r8 | 0.6945 |
| c3 | r8 | 1.100 |
| c4 | r8 | 0.1511 |
First 60 of 64 rows.
Assumptions
- Reference images are normal — 56 images with split = train are taken to be normal.
- Reference images are like the tested ones — The false-alarm guarantee assumes good tested images come from the same process as the calibration images.
- Enough calibration images — 28 calibration images; α = 0.05 needs at least 19.
Most unusual images
| Rank | Row | File | Largest patch distance | Conformal p | Role | Flagged |
|---|---|---|---|---|---|---|
| 1 | 67 | defect_scratch.png | 123.56 | .034 | test | yes |
| 2 | 68 | defect_spot.png | 122.19 | .034 | test | yes |
| 3 | 72 | good_dark.png | 66.022 | .034 | test | yes |
| 4 | 70 | defect_smudge.png | 38.113 | .034 | test | yes |
| 5 | 71 | good_blurred.png | 15.729 | .034 | test | yes |
| 6 | 69 | defect_bite.png | 15.547 | .034 | test | yes |
| 7 | 74 | good_05_edit.png | 3.516 | .034 | test | yes |
| 8 | 60 | good_59.png | 3.210 | .034 | test | yes |
| 9 | 65 | good_64.png | 2.633 | .103 | test | no |
| 10 | 62 | good_61.png | 2.304 | .207 | test | no |
| 11 | 63 | good_62.png | 2.230 | .379 | test | no |
| 12 | 73 | good_03_copy.png | 2.077 | .586 | test | no |
| 13 | 64 | good_63.png | 2.065 | .586 | test | no |
| 14 | 57 | good_56.png | 2.065 | .586 | test | no |
| 15 | 58 | good_57.png | 1.945 | .897 | test | no |
| 16 | 61 | good_60.png | 1.931 | .897 | test | no |
| 17 | 66 | good_65.png | 1.858 | .931 | test | no |
| 18 | 59 | good_58.png | 1.794 | .966 | test | no |
- 1 rows have no path and are left out.
- 1 files could not be decoded and are left out.
8 of 18 tested images are flagged as anomalies (false-alarm rate 0.05, 28 calibration images).
- Anomalies
- 8
- Images tested
- 18
- Calibration images
- 28
- Highest score
- 123.56
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Reference images are normal — 56 images with split = train are taken to be normal.
- Reference images are like the tested ones — The false-alarm guarantee assumes good tested images come from the same process as the calibration images.
- Enough calibration images — 28 calibration images; α = 0.05 needs at least 19.
Most unusual images
| Rank | Row | File | Largest patch distance | Conformal p | Role | Flagged |
|---|---|---|---|---|---|---|
| 1 | 67 | defect_scratch.png | 123.56 | .034 | test | yes |
| 2 | 68 | defect_spot.png | 122.19 | .034 | test | yes |
| 3 | 72 | good_dark.png | 66.022 | .034 | test | yes |
| 4 | 70 | defect_smudge.png | 38.113 | .034 | test | yes |
| 5 | 71 | good_blurred.png | 15.729 | .034 | test | yes |
| 6 | 69 | defect_bite.png | 15.547 | .034 | test | yes |
| 7 | 74 | good_05_edit.png | 3.516 | .034 | test | yes |
| 8 | 60 | good_59.png | 3.210 | .034 | test | yes |
| 9 | 65 | good_64.png | 2.633 | .103 | test | no |
| 10 | 62 | good_61.png | 2.304 | .207 | test | no |
| 11 | 63 | good_62.png | 2.230 | .379 | test | no |
| 12 | 73 | good_03_copy.png | 2.077 | .586 | test | no |
| 13 | 64 | good_63.png | 2.065 | .586 | test | no |
| 14 | 57 | good_56.png | 2.065 | .586 | test | no |
| 15 | 58 | good_57.png | 1.945 | .897 | test | no |
| 16 | 61 | good_60.png | 1.931 | .897 | test | no |
| 17 | 66 | good_65.png | 1.858 | .931 | test | no |
| 18 | 59 | good_58.png | 1.794 | .966 | test | no |
- 1 rows have no path and are left out.
- 1 files could not be decoded and are left out.
Do it in CodeSplash Run it on your own data. It's in the Experimental lane in the app.
Worked examples in the app
- Parts padim referenceimg2_parts · image: path · reference: split
- Parts knn fdrimg2_parts · image: path · reference: split
- Parts thumbnail seedimg2_parts · image: path · reference: label
- Parts resnet50 knnimg2_parts · image: path · reference: split
- Parts dinov2 knnimg2_parts · image: path · reference: split
- Parts padim no referenceimg2_parts · image: path
- Degenerate all naimg2_parts · image: path
- Degenerate empty after filterimg2_parts · image: path · reference: split
In the guides
Where it sits in the decision guides
- Anomaly detection · DS & ML Decision Guide · Discover — find structure without labels
What you need
- Image pathcategorical · 1 column
- A column of image file paths, such as a media collection's path column.
- Reference images marked bycategorical / boolean · 0–1 column · 2–20 levels
- Optional: a column whose chosen value marks images taken to be normal (a train split, a 'good' label).
Choices you make
model
- Modeldefault padim
How an image's distance from the normal ones is measured.
- PaDiM patch Gaussian(default) — A Gaussian per patch position over the reference images; scores the most unusual patch and maps where it is.
- kNN distance (patch features) — Mean distance to the k nearest reference images over all patch features; no map.
- kNN distance (8 × 8 thumbnails) — Mean distance to the k nearest reference images' gray 8 × 8 thumbnails; a quick baseline.
- kNN distance (ResNet-50 embeddings, ~100 MB) — Pretrained ImageNet features compare what the images show; runs locally after a one-time download you approve.
- kNN distance (DINOv2-small embeddings, ~90 MB) — Self-supervised features that capture fine texture and shape; runs locally after a one-time download you approve.
- Patch griddefault 8
Patches per side of the 128 × 128 analysis copy; finer grids find smaller defects but need more reference images.
- 4 × 4 (32-pixel patches) — Coarse: robust with few reference images; misses small defects.
- 8 × 8 (16-pixel patches)(default) — Balanced default.
- 16 × 16 (8-pixel patches) — Fine: finds small spots and scratches; needs more reference images.
- Neighbors (k)default 5
Reference images averaged for the distance; fewer react to close look-alikes, more smooth the score.
options
- Reference valuedefault —
The value that marks normal images (default: train, training, good, normal, ok or pass when present, else the first value).
- Share that fits the modeldefault 0.5
Share of the reference images that builds the model; the rest calibrate the alarms.
- Flag images bydefault false_alarm
How calibrated p-values become flags (needs reference images).
- False-alarm rate(default) — Flag p ≤ α: a good image is flagged with probability at most α.
- False discovery rate — Benjamini–Hochberg at α: among flagged images, the expected share of good ones is at most α.
- Target rate (α)default 0.05
The false-alarm rate or false discovery rate to hold.
- Share flagged without referencedefault 0.05
With no reference column, the model fits every image and this share of the highest scores is flagged.
Advanced
- Seeddefault 1
Seed of the shared random stream that splits the reference images into fit and calibration images.
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.
Reference images are normal
Calibration assumes the reference images are good parts like the ones being tested; a defect among them makes the alarms more cautious.
Reference images are like the tested ones
The false-alarm guarantee holds when a good tested image is exchangeable with the calibration images (same camera, light and product).
Enough calibration images
With n calibration images no p-value is below 1/(n + 1): α = 0.05 needs at least 19.
What it reports
- n_rows
- Reference images held back from fitting; their scores show what a good image scores, which sets calibrated p-values.
- n_images
- Reference images held back from fitting; their scores show what a good image scores, which sets calibrated p-values.
- n_no_path
- Reference images held back from fitting; their scores show what a good image scores, which sets calibrated p-values.
- n_unreadable
- Reference images held back from fitting; their scores show what a good image scores, which sets calibrated p-values.
- n_reference
- Reference images held back from fitting; their scores show what a good image scores, which sets calibrated p-values.
- n_fit
- Reference images held back from fitting; their scores show what a good image scores, which sets calibrated p-values.
- n_calibration
- Reference images held back from fitting; their scores show what a good image scores, which sets calibrated p-values.
- n_tested
- Reference images held back from fitting; their scores show what a good image scores, which sets calibrated p-values.
- n_flagged
- Each image's distance from the normal ones; flagged images have calibrated p ≤ α, or the top share without reference images.
- calibrated
- Reference images held back from fitting; their scores show what a good image scores, which sets calibrated p-values.
- alpha
- Reference images held back from fitting; their scores show what a good image scores, which sets calibrated p-values.
- cutoff
- Each image's distance from the normal ones; flagged images have calibrated p ≤ α, or the top share without reference images.
- threshold
- Each image's distance from the normal ones; flagged images have calibrated p ≤ α, or the top share without reference images.
- score_check
- Each image's distance from the normal ones; flagged images have calibrated p ≤ α, or the top share without reference images.
- score_max
- Each image's distance from the normal ones; flagged images have calibrated p ≤ α, or the top share without reference images.
- score_mean
- Each image's distance from the normal ones; flagged images have calibrated p ≤ α, or the top share without reference images.
- score_cal_median
- Each image's distance from the normal ones; flagged images have calibrated p ≤ α, or the top share without reference images.
- model
- An anomaly model fitting one Gaussian per image patch position to normal images; an image scores as its most unusual patch.
- grid
- An anomaly model fitting one Gaussian per image patch position to normal images; an image scores as its most unusual patch.
- k
- An image's mean distance to its k nearest reference images; far from every normal image means unusual.
Per group, level or term: top_row[<rank>], top_score[<rank>], top_p[<rank>]
Python and R
Python and R agree to 6 decimals (relative tolerance 1e-8). Python uses numpy, scipy, pandas, codesplash; R uses nanoparquet, codesplashr.
Default traps between the two languages
- Both engines read the same decoded copies (float32 tensor shards from the sidecar) and run the same twins (codesplash.images.anomaly ↔ R/images_anomaly.R); the reference split uses the shared Wichmann–Hill stream. Scores differ only by matrix and Cholesky rounding.
- The ResNet-50 and DINOv2 choices embed with the encoder twins (codesplash.images.backbones ↔ R/images_backbones.R, written out in torch from the same safetensors); their case is skipped, and counted, when the weights aren't in the store.
The exact script CodeSplash ran for example “Parts padim reference” · Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Image inspection anomalies (PaDiM, kNN)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.image_anomaly 1.0.0 · spec 758f9e57afd1cb0e
# Dataset: img2_parts (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import os
import numpy as np
import pandas as pd
import codesplash as cs
from codesplash import ml as csml
from codesplash.images import anomaly as A
from codesplash.ml import anomaly as csanom
from codesplash.ml import embed as csembed
# %% Images listed in the path column
PATH = "path"
REF = "split"
df = pd.read_parquet("tests/parity/fixtures/img2_parts.parquet", columns=list(dict.fromkeys(c for c in (PATH, REF) if c is not None)))
if not len(df):
cs.cs_error("CS_E_NO_ROWS")
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\":\"stretch\",\"mode\":\"rgb\",\"normalize\":\"none\",\"size\":[128,128]}}"), "target/academy-parity/run-8142/discover.image_anomaly/parts_padim_reference/out-python", df, "tests/parity/fixtures/img2_parts.parquet")
media_ids = cs_media.ids_of(media, df)
def _text(v):
return None if pd.isna(v) else str(v) # None, NaN, pd.NA
from codesplash.images import collection as cimg
ok, n_no_path, n_unreadable, X = cimg.read(media, media_ids, df[PATH].tolist()) # X: float32 (n, c, h, w) on 0–1
if not ok:
if n_no_path == len(df):
cs.cs_error("CS_E_ALL_MISSING", column=PATH)
# None of the listed files could be decoded.
cs.cs_error("CS_E_INVALID_VALUES", column=PATH, requirement="an image file that can be decoded", count=n_unreadable)
if n_no_path:
warnings.append(f"{n_no_path} rows have no path and are left out.")
if n_unreadable:
warnings.append(f"{n_unreadable} files could not be decoded and are left out.")
n = len(ok)
rows = np.array(ok, dtype=np.int64) # 0-based input rows scored
files = [os.path.basename(str(df[PATH].iloc[k])) for k in ok]
# %% Reference images: fit the model on part of them, calibrate the alarms on the rest
MODEL = "padim"
SEED = 1
FIT_SHARE = 0.5
ALPHA = 0.05
ALERT = "false_alarm"
if REF is not None:
_levels = sorted({_text(v) for v in df[REF].tolist() if _text(v) is not None})
_given = None
if _given is not None:
REF_LEVEL = str(_given)
else:
_pref = [lv for lv in _levels if str(lv).strip().lower() in ("train", "training", "good", "normal", "ok", "pass", "true")]
REF_LEVEL = str(_pref[0] if _pref else _levels[0])
ref = np.array([j for j, k in enumerate(ok) if _text(df[REF].iloc[k]) == REF_LEVEL], dtype=np.int64)
if len(ref) < 3:
cs.cs_error("CS_E_TOO_FEW_ROWS", what=f"Reference images ({REF} = {REF_LEVEL})", min=3, n=len(ref))
fit, cal = A.reference_split(ref, FIT_SHARE, SEED)
else:
REF_LEVEL = None
ref = np.arange(n)
fit, cal = ref, np.zeros(0, dtype=np.int64)
if n < 2:
cs.cs_error("CS_E_TOO_FEW_ROWS", what="An anomaly model", min=2, n=n)
calibrated = len(cal) > 0
is_ref = np.zeros(n, dtype=bool)
is_ref[ref] = True
role = np.array(["test"] * n, dtype=object)
role[cal] = "calibration"
role[fit] = "fit"
tested = np.flatnonzero(~is_ref) if calibrated else np.arange(n)
# %% Scores
GRID = int("8") if MODEL in ("padim", "knn") else None
K = 5 if MODEL.startswith("knn") else None
maps = None
if MODEL in ("padim", "knn"):
F = A.patch_features(X, GRID)
Z = A.standardize(F, A.standardizer(F[fit]))
if MODEL == "padim":
maps = A.padim_maps(Z, A.padim_fit(Z[fit]))
scores = maps.max(axis=1)
SCORE_LABEL = "Largest patch distance"
else:
scores = A.knn_scores(Z.reshape(n, -1), fit, K)
SCORE_LABEL = "Mean distance to the nearest reference images"
else:
from codesplash import encoders
ENCODER = {"knn_thumbnail": "thumbnail", "knn_resnet50": "resnet50", "knn_dinov2_small": "dinov2_small"}[MODEL]
E = np.asarray(encoders.embed(ENCODER, X), dtype=np.float64)
if ENCODER == "thumbnail":
# Pixel values: standardized with the fit images' mean and SD.
mu, sd = E[fit].mean(axis=0), E[fit].std(axis=0)
E = (E - mu) / np.where(sd > 0, sd, 1.0)
SCORE_LABEL = "Mean distance to the nearest reference thumbnails"
else:
# Pretrained embeddings: compared by direction (unit length), as cosine similarity does.
E = A.unit_rows(E)
SCORE_LABEL = "Mean distance to the nearest reference embeddings"
scores = A.knn_scores(E, fit, K)
# %% Alarms
p_value = np.full(n, np.nan)
flags = np.zeros(n, dtype=bool)
cutoff = None
if calibrated:
cal_scores = np.sort(scores[cal])
p_value[tested] = A.conformal_p(cal_scores, scores[tested])
if ALERT == "fdr":
flags[tested] = A.bh_flags(p_value[tested], ALPHA)
else:
allowed = A.allowed_at_or_above(len(cal), ALPHA)
above = len(cal_scores) - np.searchsorted(cal_scores, scores[tested], side="left")
flags[tested] = above <= allowed
cutoff = A.false_alarm_cutoff(cal_scores, ALPHA)
if cutoff is not None and not np.isfinite(cutoff):
cutoff = None
if len(cal) < A.min_calibration(ALPHA):
warnings.append(f"With {len(cal)} calibration images no image can be flagged at α = {ALPHA:g}; it needs at least {A.min_calibration(ALPHA)}.")
threshold = float(scores[flags].min()) if flags.any() else None
else:
flags, threshold = csanom.flag(scores, "share", 0.05, 0.0)
warnings.append("No reference images: the model fitted every image and the highest scores are flagged; calibrated alarms need a reference column.")
# %% Artifacts
out = csml.out_dir("target/academy-parity/run-8142/discover.image_anomaly/parts_padim_reference/out-python")
pd.DataFrame({"row": rows, "score": scores, "anomaly": flags, "p_value": p_value,
"role": pd.array(role.tolist(), dtype="string")}).to_parquet(os.path.join(out, "labels.parquet"), index=False)
order = np.concatenate([np.sort(cal), np.sort(tested)]) if calibrated else np.arange(n)
pd.DataFrame({"order": np.arange(1, len(order) + 1, dtype=np.int64), "row": rows[order] + 1,
"file": pd.array([files[j] for j in order], dtype="string"), "role": pd.array(role[order].tolist(), dtype="string"),
"score": scores[order], "p_value": p_value[order], "anomaly": flags[order]}).to_parquet(os.path.join(out, "series.parquet"), index=False)
artifacts = [{"key": "labels", "path": os.path.join(out, "labels.parquet"), "format": "parquet"},
{"key": "series", "path": os.path.join(out, "series.parquet"), "format": "parquet"}]
if maps is not None:
gy, gx = np.divmod(np.arange(GRID * GRID), GRID)
pd.DataFrame({"row": np.repeat(rows + 1, GRID * GRID), "patch_row": np.tile(gy + 1, n), "patch_col": np.tile(gx + 1, n),
"distance": maps.ravel()}).to_parquet(os.path.join(out, "maps.parquet"), index=False)
artifacts.append({"key": "maps", "path": os.path.join(out, "maps.parquet"), "format": "parquet"})
# %% Result
pool = tested if len(tested) else np.arange(n)
rank = pool[np.lexsort((pool, -scores[pool]))]
values = {
"n_rows": len(df), "n_images": n, "n_no_path": n_no_path, "n_unreadable": n_unreadable,
"n_reference": int(is_ref.sum()) if REF is not None else 0, "n_fit": len(fit), "n_calibration": len(cal),
"n_tested": len(tested), "n_flagged": int(flags.sum()), "calibrated": bool(calibrated),
"alpha": ALPHA if calibrated else None, "cutoff": cutoff, "threshold": threshold,
"score_check": csembed.checksum(scores, rows), "score_max": float(scores.max()), "score_mean": float(scores.mean()),
"score_cal_median": float(np.median(scores[cal])) if calibrated else None,
"model": MODEL, "grid": GRID, "k": K,
}
for r, j in enumerate(rank[:10], start=1):
values[f"top_row[{r}]"] = int(rows[j]) + 1
values[f"top_score[{r}]"] = float(scores[j])
values[f"top_p[{r}]"] = None if np.isnan(p_value[j]) else float(p_value[j])
table_rows = [{"rank": r, "row": int(rows[j]) + 1, "file": files[j], "score": float(scores[j]),
"p_value": None if np.isnan(p_value[j]) else float(p_value[j]), "role": str(role[j]), "flagged": bool(flags[j])}
for r, j in enumerate(rank[:20], start=1)]
assumptions = [
{"key": "reference_normal", "label": "Reference images are normal", "status": "info" if REF is not None else "warn",
"detail": f"{int(is_ref.sum())} images with {REF} = {REF_LEVEL} are taken to be normal." if REF is not None else "No reference column: every image fitted the model."},
{"key": "exchangeable", "label": "Reference images are like the tested ones", "status": "info",
"detail": "The false-alarm guarantee assumes good tested images come from the same process as the calibration images."},
{"key": "calibration_size", "label": "Enough calibration images",
"status": "pass" if calibrated and len(cal) >= A.min_calibration(ALPHA) else ("warn" if calibrated else "info"),
"detail": f"{len(cal)} calibration images; α = {ALPHA:g} needs at least {A.min_calibration(ALPHA)}." if calibrated else "Not calibrated (no reference column)."},
]
charts = [cs.chart("scores", "anomaly-scores", f"{SCORE_LABEL}", {
"score": cs.col(SCORE_LABEL, scores, "numeric"),
"anomaly": cs.col("Flagged", [bool(x) for x in flags], "boolean"),
}, controls={"threshold": float(threshold) if threshold is not None else 0.0})]
if maps is not None:
top = int(rank[0])
labels_r = [f"r{int(v) + 1}" for v in np.repeat(np.arange(GRID), GRID)]
labels_c = [f"c{int(v) + 1}" for v in np.tile(np.arange(GRID), GRID)]
charts.append(cs.chart("map", "matrix-heatmap", f"Patch distances of row {int(rows[top]) + 1} ({files[top]})", {
"row": cs.col("Patch row", labels_r, "categorical", [f"r{i + 1}" for i in range(GRID)]),
"col": cs.col("Patch column", labels_c, "categorical", [f"c{i + 1}" for i in range(GRID)]),
"value": cs.col("Mahalanobis distance", maps[top], "numeric"),
}, controls={"scale": "sequential"}))
tested_label = "tested" if calibrated else "scored"
cs.publish({
"title": "Image inspection anomalies (PaDiM, kNN)",
"engine": cs.engine_info("numpy", "scipy", "pandas"),
"n": n,
"summary": f"{int(flags.sum())} of {len(tested)} {tested_label} images are flagged as anomalies"
+ (f" ({'false discovery' if ALERT == 'fdr' else 'false-alarm'} rate {ALPHA:g}, {len(cal)} calibration images)." if calibrated else "."),
"statistics": [
{"key": "n_flagged", "label": "Anomalies", "value": int(flags.sum()), "format": "integer"},
{"key": "n_tested", "label": "Images tested", "value": len(tested), "format": "integer"},
{"key": "n_calibration", "label": "Calibration images", "value": len(cal), "format": "integer"},
{"key": "score_max", "label": "Highest score", "value": float(scores.max())},
],
"tables": [{
"key": "top", "title": "Most unusual images",
"columns": [{"key": "rank", "label": "Rank", "type": "integer"}, {"key": "row", "label": "Row", "type": "integer"}, {"key": "file", "label": "File"},
{"key": "score", "label": SCORE_LABEL, "type": "number"}, {"key": "p_value", "label": "Conformal p", "type": "pvalue"},
{"key": "role", "label": "Role"}, {"key": "flagged", "label": "Flagged", "type": "boolean"}],
"rows": table_rows,
}],
"assumptions": assumptions,
"charts": charts,
"values": values,
"warnings": warnings,
"artifacts": artifacts,
})
The exact script CodeSplash ran for example “Parts padim reference” · R version 4.5.1 (2025-06-13)
# Image inspection anomalies (PaDiM, kNN)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.image_anomaly 1.0.0 · spec 758f9e57afd1cb0e
# Dataset: img2_parts (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr)
# %% Images listed in the path column
PATH <- "path"
REF <- "split"
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/img2_parts.parquet", col_select = unique(c(PATH, REF))))
if (!nrow(df)) cs_error("CS_E_NO_ROWS")
warnings <- character(0)
# %% 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\":\"stretch\",\"mode\":\"rgb\",\"normalize\":\"none\",\"size\":[128,128]}}", simplifyVector = FALSE), "target/academy-parity/run-8142/discover.image_anomaly/parts_padim_reference/out-r", df,
"tests/parity/fixtures/img2_parts.parquet")
media_ids <- cs_media_ids(media, df)
text_ <- function(v) { v <- as.character(v); v[!is.na(v) & !nzchar(v)] <- NA_character_; v }
paths_ <- text_(df[[PATH]])
rd_ <- cs_imgc_read(media, media_ids, paths_)
ok <- rd_$ok; n_no_path <- rd_$n_no_path; n_unreadable <- rd_$n_unreadable; X <- rd_$X # X: (n, c, h, w) on 0-1
if (!length(ok)) {
if (n_no_path == nrow(df)) cs_error("CS_E_ALL_MISSING", column = PATH)
# None of the listed files could be decoded.
cs_error("CS_E_INVALID_VALUES", column = PATH, requirement = "an image file that can be decoded", count = n_unreadable)
}
if (n_no_path) warnings <- c(warnings, sprintf("%d rows have no path and are left out.", n_no_path))
if (n_unreadable) warnings <- c(warnings, sprintf("%d files could not be decoded and are left out.", n_unreadable))
n <- length(ok)
rows <- ok - 1L # 0-based input rows scored
files <- basename(paths_[ok])
# %% Reference images: fit the model on part of them, calibrate the alarms on the rest
MODEL <- "padim"
SEED <- 1
FIT_SHARE <- 0.5
ALPHA <- 0.05
ALERT <- "false_alarm"
if (!is.null(REF)) {
levels_ <- sort(unique(text_(df[[REF]])[!is.na(text_(df[[REF]]))]), method = "radix")
given_ <- NULL
if (!is.null(given_)) {
REF_LEVEL <- as.character(given_)
} else {
pref_ <- levels_[tolower(trimws(as.character(levels_))) %in% c("train", "training", "good", "normal", "ok", "pass", "true")]
REF_LEVEL <- as.character(if (length(pref_)) pref_[1] else levels_[1])
}
refv_ <- text_(df[[REF]])[ok]
ref <- which(!is.na(refv_) & refv_ == REF_LEVEL)
if (length(ref) < 3) cs_error("CS_E_TOO_FEW_ROWS", what = sprintf("Reference images (%s = %s)", REF, REF_LEVEL), min = 3, n = length(ref))
sp_ <- cs_imga_reference_split(ref, FIT_SHARE, SEED)
fit <- sp_$fit; cal <- sp_$calibration
} else {
REF_LEVEL <- NULL
ref <- seq_len(n)
fit <- ref; cal <- integer(0)
if (n < 2) cs_error("CS_E_TOO_FEW_ROWS", what = "An anomaly model", min = 2, n = n)
}
calibrated <- length(cal) > 0
is_ref <- logical(n); is_ref[ref] <- TRUE
role <- rep("test", n); role[cal] <- "calibration"; role[fit] <- "fit"
tested <- if (calibrated) which(!is_ref) else seq_len(n)
# %% Scores
GRID <- if (MODEL %in% c("padim", "knn")) as.integer("8") else NULL
K <- if (startsWith(MODEL, "knn")) 5 else NULL
maps <- NULL
if (MODEL %in% c("padim", "knn")) {
F_ <- cs_imga_patch_features(X, GRID)
Z <- cs_imga_standardize(F_, cs_imga_standardizer(F_[fit, , , drop = FALSE]))
if (MODEL == "padim") {
maps <- cs_imga_padim_maps(Z, cs_imga_padim_fit(Z[fit, , , drop = FALSE]))
scores <- apply(maps, 1, max)
SCORE_LABEL <- "Largest patch distance"
} else {
scores <- cs_imga_knn_scores(matrix(Z, n), fit, K)
SCORE_LABEL <- "Mean distance to the nearest reference images"
}
} else {
ENCODER <- c(knn_thumbnail = "thumbnail", knn_resnet50 = "resnet50", knn_dinov2_small = "dinov2_small")[[MODEL]]
E <- as.matrix(cs_encoder_embed(ENCODER, X)) * 1.0
if (ENCODER == "thumbnail") {
# Pixel values: standardized with the fit images' mean and SD.
mu_ <- colMeans(E[fit, , drop = FALSE])
sd_ <- sqrt(colMeans(sweep(E[fit, , drop = FALSE], 2, mu_)^2))
E <- sweep(sweep(E, 2, mu_), 2, ifelse(sd_ > 0, sd_, 1), "/")
SCORE_LABEL <- "Mean distance to the nearest reference thumbnails"
} else {
# Pretrained embeddings: compared by direction (unit length), as cosine similarity does.
E <- cs_imga_unit_rows(E)
SCORE_LABEL <- "Mean distance to the nearest reference embeddings"
}
scores <- cs_imga_knn_scores(E, fit, K)
}
# %% Alarms
p_value <- rep(NaN, n)
flags <- logical(n)
cutoff <- NULL
if (calibrated) {
cal_scores <- sort(scores[cal])
p_value[tested] <- cs_imga_conformal_p(cal_scores, scores[tested])
if (ALERT == "fdr") {
flags[tested] <- cs_imga_bh_flags(p_value[tested], ALPHA)
} else {
allowed <- floor(ALPHA * (length(cal) + 1) + 1e-9) - 1
above <- length(cal_scores) - findInterval(scores[tested], cal_scores, left.open = TRUE)
flags[tested] <- above <= allowed
cutoff <- cs_imga_false_alarm_cutoff(cal_scores, ALPHA)
if (!is.null(cutoff) && !is.finite(cutoff)) cutoff <- NULL
if (length(cal) < cs_imga_min_calibration(ALPHA)) {
warnings <- c(warnings, sprintf("With %d calibration images no image can be flagged at α = %s; it needs at least %d.",
length(cal), format(ALPHA), as.integer(cs_imga_min_calibration(ALPHA))))
}
}
threshold <- if (any(flags)) min(scores[flags]) else NULL
} else {
fl_ <- cs_ml_flag(scores, "share", 0.05, 0)
flags <- fl_$flag; threshold <- fl_$threshold
warnings <- c(warnings, "No reference images: the model fitted every image and the highest scores are flagged; calibrated alarms need a reference column.")
}
# %% Artifacts
out <- cs_ml_out_dir("target/academy-parity/run-8142/discover.image_anomaly/parts_padim_reference/out-r")
nanoparquet::write_parquet(data.frame(row = as.integer(rows), score = scores, anomaly = flags, p_value = p_value, role = role,
stringsAsFactors = FALSE), file.path(out, "labels.parquet"))
ord <- if (calibrated) c(sort(cal), sort(tested)) else seq_len(n)
nanoparquet::write_parquet(data.frame(order = seq_along(ord), row = as.integer(rows[ord] + 1L), file = files[ord], role = role[ord],
score = scores[ord], p_value = p_value[ord], anomaly = flags[ord], stringsAsFactors = FALSE),
file.path(out, "series.parquet"))
artifacts <- list(list(key = "labels", path = file.path(out, "labels.parquet"), format = "parquet"),
list(key = "series", path = file.path(out, "series.parquet"), format = "parquet"))
if (!is.null(maps)) {
G2 <- GRID * GRID
nanoparquet::write_parquet(data.frame(row = rep(as.integer(rows + 1L), each = G2), patch_row = rep(rep(seq_len(GRID), each = GRID), n),
patch_col = rep(rep(seq_len(GRID), times = GRID), n), distance = as.vector(t(maps))),
file.path(out, "maps.parquet"))
artifacts[[length(artifacts) + 1L]] <- list(key = "maps", path = file.path(out, "maps.parquet"), format = "parquet")
}
# %% Result
pool <- if (length(tested)) tested else seq_len(n)
rank <- pool[order(-scores[pool], pool)]
values <- list(
n_rows = nrow(df), n_images = n, n_no_path = n_no_path, n_unreadable = n_unreadable,
n_reference = if (!is.null(REF)) sum(is_ref) else 0L, n_fit = length(fit), n_calibration = length(cal),
n_tested = length(tested), n_flagged = sum(flags), calibrated = calibrated,
alpha = if (calibrated) ALPHA else NULL, cutoff = cutoff, threshold = threshold,
score_check = cs_ml_checksum(scores, rows), score_max = max(scores), score_mean = mean(scores),
score_cal_median = if (calibrated) stats::median(scores[cal]) else NULL,
model = MODEL, grid = GRID, k = K
)
for (r in seq_len(min(10L, length(rank)))) {
j <- rank[r]
values[[sprintf("top_row[%d]", r)]] <- rows[j] + 1L
values[[sprintf("top_score[%d]", r)]] <- scores[j]
values[sprintf("top_p[%d]", r)] <- list(if (is.nan(p_value[j])) NULL else p_value[j])
}
table_rows <- lapply(seq_len(min(20L, length(rank))), function(r) {
j <- rank[r]
list(rank = r, row = rows[j] + 1L, file = files[j], score = scores[j], p_value = if (is.nan(p_value[j])) NULL else p_value[j],
role = role[j], flagged = flags[j])
})
min_cal <- as.integer(cs_imga_min_calibration(ALPHA))
assumptions <- list(
list(key = "reference_normal", label = "Reference images are normal", status = if (!is.null(REF)) "info" else "warn",
detail = if (!is.null(REF)) sprintf("%d images with %s = %s are taken to be normal.", sum(is_ref), REF, REF_LEVEL) else "No reference column: every image fitted the model."),
list(key = "exchangeable", label = "Reference images are like the tested ones", status = "info",
detail = "The false-alarm guarantee assumes good tested images come from the same process as the calibration images."),
list(key = "calibration_size", label = "Enough calibration images",
status = if (calibrated && length(cal) >= min_cal) "pass" else if (calibrated) "warn" else "info",
detail = if (calibrated) sprintf("%d calibration images; α = %s needs at least %d.", length(cal), format(ALPHA), min_cal) else "Not calibrated (no reference column).")
)
charts <- list(cs_chart("scores", "anomaly-scores", SCORE_LABEL, list(
score = cs_col(SCORE_LABEL, scores, "numeric"),
anomaly = cs_col("Flagged", flags, "boolean")
), controls = list(threshold = if (!is.null(threshold)) threshold else 0)))
if (!is.null(maps)) {
top <- rank[1]
charts[[length(charts) + 1L]] <- cs_chart("map", "matrix-heatmap", sprintf("Patch distances of row %d (%s)", rows[top] + 1L, files[top]), list(
row = cs_col("Patch row", paste0("r", rep(seq_len(GRID), each = GRID)), "categorical", paste0("r", seq_len(GRID))),
col = cs_col("Patch column", paste0("c", rep(seq_len(GRID), times = GRID)), "categorical", paste0("c", seq_len(GRID))),
value = cs_col("Mahalanobis distance", maps[top, ], "numeric")
), controls = list(scale = "sequential"))
}
tested_label <- if (calibrated) "tested" else "scored"
cs_publish(list(
title = "Image inspection anomalies (PaDiM, kNN)",
engine = cs_engine_info("codesplashr", "nanoparquet"),
n = n,
summary = paste0(sprintf("%d of %d %s images are flagged as anomalies", sum(flags), length(tested), tested_label),
if (calibrated) sprintf(" (%s rate %s, %d calibration images).", if (ALERT == "fdr") "false discovery" else "false-alarm", format(ALPHA), length(cal)) else "."),
statistics = list(
list(key = "n_flagged", label = "Anomalies", value = sum(flags), format = "integer"),
list(key = "n_tested", label = "Images tested", value = length(tested), format = "integer"),
list(key = "n_calibration", label = "Calibration images", value = length(cal), format = "integer"),
list(key = "score_max", label = "Highest score", value = max(scores))
),
tables = list(list(
key = "top", title = "Most unusual images",
columns = list(list(key = "rank", label = "Rank", type = "integer"), list(key = "row", label = "Row", type = "integer"), list(key = "file", label = "File"),
list(key = "score", label = SCORE_LABEL, type = "number"), list(key = "p_value", label = "Conformal p", type = "pvalue"),
list(key = "role", label = "Role"), list(key = "flagged", label = "Flagged", type = "boolean")),
rows = table_rows
)),
assumptions = assumptions,
charts = charts,
values = values,
warnings = as.list(warnings),
artifacts = artifacts
))
Sources
- Defard T, Setkov A, Loesch A, Audigier R (2021). PaDiM: a patch distribution modeling framework for anomaly detection and localization. ICPR 2020 Workshops, LNCS 12664, 475–489.
- Ramaswamy S, Rastogi R, Shim K (2000). Efficient algorithms for mining outliers from large data sets. SIGMOD 2000, 427–438.
- Vovk V, Gammerman A, Shafer G (2005). Algorithmic Learning in a Random World. Springer.
- Laxhammar R, Falkman G (2015). Inductive conformal anomaly detection for sequential detection of anomalous sub-trajectories. Annals of Mathematics and Artificial Intelligence 74:67–94.
- Bates S, Candès E, Lei L, Romano Y, Sesia M (2023). Testing for outliers with conformal p-values. Annals of Statistics 51(1):149–178.
- Pech-Pacheco JL, Cristóbal G, Chamorro-Martínez J, Fernández-Valdivia J (2000). Diatom autofocusing in brightfield microscopy: a comparative study. ICPR 2000, 314–317.
- Wightman R, Touvron H, Jégou H (2021). ResNet strikes back: an improved training procedure in timm. arXiv:2110.00476.
- Oquab M, Darcet T, Moutakanni T, et al. (2023). DINOv2: learning robust visual features without supervision. arXiv:2304.07193.
From the CodeSplash method registry · discover.image_anomaly v1.0.0.