Skip to content

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.

Applied ~14 min7 steps

What runs in CodeSplash

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

Read first

01

Learning "good" from pictures

Read

On 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).

02

Patches and their Gaussians

Checkpoint

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

Matrix heatmapWhat do the values of a square or rectangular result matrix look like at a glance?
View data
variablewithr
ageage1
ageBMI0.1207
agesystolic BP0.1471
agecholesterol0.1467
ageglucose0.1912
ageactivity−0.1247
BMIage0.1207
BMIBMI1
BMIsystolic BP0.3132
BMIcholesterol0.3194
BMIglucose0.3629
BMIactivity−0.1770
systolic BPage0.1471
systolic BPBMI0.3132
systolic BPsystolic BP1
systolic BPcholesterol0.4537
systolic BPglucose0.5647
systolic BPactivity−0.3672
cholesterolage0.1467
cholesterolBMI0.3194
cholesterolsystolic BP0.4537
cholesterolcholesterol1
cholesterolglucose0.6006
cholesterolactivity−0.3861
glucoseage0.1912
glucoseBMI0.3629
glucosesystolic BP0.5647
glucosecholesterol0.6006
glucoseglucose1
glucoseactivity−0.4105
activityage−0.1247
activityBMI−0.1770
activitysystolic BP−0.3672
activitycholesterol−0.3861
activityglucose−0.4105
activityactivity1

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.

03

How unusual is unusual?

Explore
Image inspection anomalies (PaDiM, kNN)Recorded · Python and R agreeRecorded 2026-11-25 · 50 values compared
R

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

Largest patch distanceHow unusual are the most anomalous rows compared with the rest, and where is the cut?
View data
FlaggedLargest patch distance
false2.165
false2.134
false2.134
false2.077
false2.125
false3.118
false1.885
false2.409
false1.980
false2.024
false2.057
false2.043
false1.856
false1.987
false2.320
false1.954
false2.304
false1.833
false1.879
false2.117
false1.771
false2.008
false2.190
false2.202
false2.042
false2.155
false2.246
false1.769
false2.056
false2.746
false2.021
false2.023
false2.023
false2.026
false2.015
false2.469
false1.818
false1.875
false2.109
false1.673
false2.149
false2.207
false2.230
false2.015
false1.921
false1.863
false2.295
false2.261
false2.012
false2.063
false2.264
false2.204
false1.738
false2.129
false1.707
false2.662
false2.065
false1.945
false1.794
true3.210

First 60 of 74 rows.

Patch distances of row 67 (defect_scratch.png)What do the values of a square or rectangular result matrix look like at a glance?
View data
Patch columnPatch rowMahalanobis distance
c1r10.5068
c2r10.8162
c3r10.8840
c4r10.6934
c5r10.2435
c6r10.4036
c7r10.6556
c8r10.9375
c1r20.7006
c2r20.5628
c3r21.428
c4r21.337
c5r21.720
c6r21.577
c7r20.5016
c8r20.8314
c1r31.022
c2r31.886
c3r334.494
c4r33.303
c5r30.9112
c6r31.472
c7r31.290
c8r30.5595
c1r40.3229
c2r41.755
c3r419.914
c4r4120.77
c5r429.766
c6r41.497
c7r41.848
c8r40.8055
c1r51.196
c2r51.335
c3r51.033
c4r529.770
c5r5123.56
c6r522.680
c7r51.362
c8r50.8689
c1r61.113
c2r61.520
c3r61.630
c4r61.103
c5r62.573
c6r637.533
c7r61.687
c8r60.4656
c1r71.004
c2r70.5149
c3r71.503
c4r71.375
c5r71.629
c6r71.406
c7r70.8440
c8r71.033
c1r80.6314
c2r80.6945
c3r81.100
c4r80.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

RankRowFileLargest patch distanceConformal pRoleFlagged
167defect_scratch.png123.56.034testyes
268defect_spot.png122.19.034testyes
372good_dark.png66.022.034testyes
470defect_smudge.png38.113.034testyes
571good_blurred.png15.729.034testyes
669defect_bite.png15.547.034testyes
774good_05_edit.png3.516.034testyes
860good_59.png3.210.034testyes
965good_64.png2.633.103testno
1062good_61.png2.304.207testno
1163good_62.png2.230.379testno
1273good_03_copy.png2.077.586testno
1364good_63.png2.065.586testno
1457good_56.png2.065.586testno
1558good_57.png1.945.897testno
1661good_60.png1.931.897testno
1766good_65.png1.858.931testno
1859good_58.png1.794.966testno
  • 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
))
Python

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

RankRowFileLargest patch distanceConformal pRoleFlagged
167defect_scratch.png123.56.034testyes
268defect_spot.png122.19.034testyes
372good_dark.png66.022.034testyes
470defect_smudge.png38.113.034testyes
571good_blurred.png15.729.034testyes
669defect_bite.png15.547.034testyes
774good_05_edit.png3.516.034testyes
860good_59.png3.210.034testyes
965good_64.png2.633.103testno
1062good_61.png2.304.207testno
1163good_62.png2.230.379testno
1273good_03_copy.png2.077.586testno
1364good_63.png2.065.586testno
1457good_56.png2.065.586testno
1558good_57.png1.945.897testno
1661good_60.png1.931.897testno
1766good_65.png1.858.931testno
1859good_58.png1.794.966testno
  • 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.

Anomaly score distributionHow unusual are the most anomalous rows compared with the rest, and where is the cut?
View data
anomaly scoreflagged
0.4217false
0.4499false
0.5103false
0.5028false
0.4336false
0.5026false
0.5002false
0.5199false
0.4377false
0.5178false
0.4528false
0.4401false
0.4395false
0.4971false
0.4508false
0.4541false
0.4738false
0.4640false
0.4289false
0.4376false
0.4474false
0.5025false
0.4309false
0.4250false
0.4255false
0.5547false
0.4777false
0.4272false
0.4347false
0.4316false
0.4482false
0.4415false
0.4450false
0.5123false
0.5606false
0.4290false
0.4287false
0.4343false
0.4322false
0.4788false
0.4677false
0.4839false
0.4386false
0.5540false
0.4545false
0.4542false
0.4528false
0.4476false
0.4649false
0.5142false
0.4437false
0.4764false
0.4597false
0.4426false
0.5354false
0.4325false
0.4305false
0.4485false
0.5064false
0.4441false

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.

04

kNN: distance to the nearest good parts

Checkpoint

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

05

Watch the line: open in a control chart

In the app

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

06

Do it on your own data

In the app

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

Python
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)
R
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)
07

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