Inspection anomalies on images: PaDiM, kNN and calibrated alarms
Learn what good parts look like from reference images, score every new image by how far it strays, calibrate the alarms so a good part is flagged at most 5% of the time, and watch the scores on a control chart.
What runs in CodeSplash
- Image inspection anomalies (PaDiM, kNN) Experimental
You will be able to
- Explain how a patch Gaussian (PaDiM) scores an image and maps where it differs
- Split reference images into fit and calibration images and read a conformal p-value
- Send the scores to a control chart with the reference images as phase I
Learning "good" from pictures
ReadOn an inspection line nearly every part is good, and defects are rare and varied: a scratch today, a missing chip tomorrow. Instead of training a classifier on defects you may never have seen, learn what good parts look like and flag whatever strays.
You need reference images: frames taken to be good, marked in a column (a train split, a "good" label).
Patches and their Gaussians
CheckpointPaDiMPaDiM patch GaussianAn anomaly model fitting one Gaussian per image patch position to normal images; an image scores as its most unusual patch. cuts every image into a grid of patches. Each patch is described by a few numbers (patch featuresPatch features (images)Seven numbers per patch of a grid over the image: mean red, green and blue, luma spread, gradients and Laplacian variance.: color, contrast, gradients, sharpness). For every patch position it fits a Gaussian over the reference images, so position (3, 5) learns what that corner of a good part looks like.
A new image's patch is scored by its Mahalanobis distance from that Gaussian; the image scores as its most unusual patch. The patch scores form a map of where it differs.
View data
| variable | with | r |
|---|---|---|
| age | age | 1 |
| age | BMI | 0.1207 |
| age | systolic BP | 0.1471 |
| age | cholesterol | 0.1467 |
| age | glucose | 0.1912 |
| age | activity | −0.1247 |
| BMI | age | 0.1207 |
| BMI | BMI | 1 |
| BMI | systolic BP | 0.3132 |
| BMI | cholesterol | 0.3194 |
| BMI | glucose | 0.3629 |
| BMI | activity | −0.1770 |
| systolic BP | age | 0.1471 |
| systolic BP | BMI | 0.3132 |
| systolic BP | systolic BP | 1 |
| systolic BP | cholesterol | 0.4537 |
| systolic BP | glucose | 0.5647 |
| systolic BP | activity | −0.3672 |
| cholesterol | age | 0.1467 |
| cholesterol | BMI | 0.3194 |
| cholesterol | systolic BP | 0.4537 |
| cholesterol | cholesterol | 1 |
| cholesterol | glucose | 0.6006 |
| cholesterol | activity | −0.3861 |
| glucose | age | 0.1912 |
| glucose | BMI | 0.3629 |
| glucose | systolic BP | 0.5647 |
| glucose | cholesterol | 0.6006 |
| glucose | glucose | 1 |
| glucose | activity | −0.4105 |
| activity | age | −0.1247 |
| activity | BMI | −0.1770 |
| activity | systolic BP | −0.3672 |
| activity | cholesterol | −0.3861 |
| activity | glucose | −0.4105 |
| activity | activity | 1 |
Check yourself
Why fit one Gaussian per patch position instead of one for the whole image?
Show the answer
Answer: b
Averaging over the image dilutes a small scratch; comparing each position with its own normal range keeps it visible and localizes it.
How unusual is unusual?
Explore8 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.
The exact R script · R 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
))
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.
The exact Python script · Python 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 reference images are split on the shared random stream: half fit the Gaussians, half are held back as calibration imagesCalibration imagesReference images held back from fitting; their scores show what a good image scores, which sets calibrated p-values. and scored like any other image. A tested image's conformal p-value is one plus the calibration images scoring at least as high, divided by their count plus one.
Here 28 calibration images set the bar, and 8 of 18 tested images are flagged at a 5% false-alarm rate.
View data
| anomaly score | flagged |
|---|---|
| 0.4217 | false |
| 0.4499 | false |
| 0.5103 | false |
| 0.5028 | false |
| 0.4336 | false |
| 0.5026 | false |
| 0.5002 | false |
| 0.5199 | false |
| 0.4377 | false |
| 0.5178 | false |
| 0.4528 | false |
| 0.4401 | false |
| 0.4395 | false |
| 0.4971 | false |
| 0.4508 | false |
| 0.4541 | false |
| 0.4738 | false |
| 0.4640 | false |
| 0.4289 | false |
| 0.4376 | false |
| 0.4474 | false |
| 0.5025 | false |
| 0.4309 | false |
| 0.4250 | false |
| 0.4255 | false |
| 0.5547 | false |
| 0.4777 | false |
| 0.4272 | false |
| 0.4347 | false |
| 0.4316 | false |
| 0.4482 | false |
| 0.4415 | false |
| 0.4450 | false |
| 0.5123 | false |
| 0.5606 | false |
| 0.4290 | false |
| 0.4287 | false |
| 0.4343 | false |
| 0.4322 | false |
| 0.4788 | false |
| 0.4677 | false |
| 0.4839 | false |
| 0.4386 | false |
| 0.5540 | false |
| 0.4545 | false |
| 0.4542 | false |
| 0.4528 | false |
| 0.4476 | false |
| 0.4649 | false |
| 0.5142 | false |
| 0.4437 | false |
| 0.4764 | false |
| 0.4597 | false |
| 0.4426 | false |
| 0.5354 | false |
| 0.4325 | false |
| 0.4305 | false |
| 0.4485 | false |
| 0.5064 | false |
| 0.4441 | false |
First 60 of 1200 rows.
Check yourself
You hold back 10 calibration images and ask for a 5% false-alarm rate. What happens?
Show the answer
Answer: b
With n calibration images no p-value falls below 1/(n + 1). A 5% rate needs at least 19; the method warns you.
kNN: distance to the nearest good parts
CheckpointThe kNN distancekNN distance (images)An image's mean distance to its k nearest reference images; far from every normal image means unusual. model scores each image by its mean distance to the k nearest reference images. It ranks the same defects but draws no map. The false discovery rate rule is offered too: among flagged images, the expected share of good ones stays at most α.
Watch the line: open in a control chart
In the appOpen in control chart saves the scores in order, with the calibration images first, and opens an individuals chart whose phase I is those images. Points past the limit or a run of rising scores signal a process drifting from the good parts: a lens collecting dust, a light dimming.
Check yourself
Why put the calibration images first, as phase I?
Show the answer
Answer: b
Phase I estimates the center and limits from in-control data; phase II monitors new points against them.
Do it on your own data
In the appOpen Discover → Images → Image inspection anomalies on an image collection, choose the column that marks good images, and run. Without a reference column the model fits every image and flags the highest scores, uncalibrated.
from codesplash.images import anomaly as A
F = A.patch_features(x, 8) # x: (n, 3, 128, 128) on 0–1
Z = A.standardize(F, A.standardizer(F[fit]))
scores = A.padim_maps(Z, A.padim_fit(Z[fit])).max(axis=1)
p = A.conformal_p(scores[cal], scores) # (1 + #{cal ≥ s}) / (n_cal + 1)library(codesplashr)
F <- cs_imga_patch_features(x, 8L)
Z <- cs_imga_standardize(F, cs_imga_standardizer(F[fit, , , drop = FALSE]))
scores <- apply(cs_imga_padim_maps(Z, cs_imga_padim_fit(Z[fit, , , drop = FALSE])), 1, max)
p <- cs_imga_conformal_p(scores[cal], scores)Recap
Recap- PaDiM fits a Gaussian per patch position over good images; an image scores as its worst patch, and the map shows where.
- Held-back calibration images turn scores into p-values with a false-alarm rate you choose; at least 19 are needed for 5%.
- Scores on a control chart, with the calibration images as phase I, watch the line for drift.
Concepts in this lesson