Skip to content

A detection workflow: from boxes to a score you can defend

Run a detector, score it against your own labels, and read what the numbers hide: per-class and per-size AP, the detection limit, class confusion against loose boxes, and scores that aren't probabilities.

Applied ~15 min8 steps

What runs in CodeSplash

You will be able to

  • Lay out a detection evaluation that holds up on new images
  • Read AP, AP50, AP75 and AP by object size from one run
  • Use a class-agnostic score to separate wrong classes from missed objects
  • Treat detection scores as rankings, not calibrated probabilities

Read first

01

The workflow in five steps

Read
  1. Label a few hundred images like the ones you'll run on, or import labels (COCO, Pascal VOC or YOLO files) into a boxes table.
  2. Split by source: camera, site or day, never by single image.
  3. Detect on the held-out images only.
  4. Score predictions against labels: one table, a source column saying annotation or prediction.
  5. Read the score by class and by object size, then look at a gallery of misses and false boxes.

A pretrained detector skips training, not evaluation. Its benchmark score was earned on someone else's images.

02

Score against your labels

Read
Object detection qualityRecorded · Python and R agreeRecorded 2026-11-25 · 37 values compared
R

Across 10 images and 3 classes, AP (IoU 0.50:0.95) = 0.473, AP50 = 0.560 and AP75 = 0.560; average recall with up to 100 detections per image = 0.534. At IoU 0.50: 16 true positives, 16 false positives, 10 missed objects.

AP (0.50:0.95)
0.4726
AP50
0.5600
AP75
0.5600
AR@100
0.5342

Plots

Precision–recall at IoU 0.50, by classHow much precision does the model keep as it finds more of the positives?

COCO's interpolated precision at 101 recall points, up to the recall each class reaches.

View data
labelPrecision (interpolated)Recall
person10
person10.0100
person10.0200
person10.0300
person10.0400
person10.0500
person10.0600
person10.0700
person10.0800
person10.0900
person10.1000
person10.1100
person10.1200
person10.1300
person10.1400
person10.1500
person10.1600
person10.1700
person10.1800
person10.1900
person10.2000
person10.2100
person10.2200
person10.2300
person10.2400
person10.2500
person10.2600
person10.2700
person10.2800
person10.2900
person10.3000
person10.3100
person10.3200
person10.3300
person10.3400
person10.3500
person10.3600
person10.3700
person10.3800
person10.3900
person10.4000
person10.4100
person10.4200
person10.4300
person10.4400
person10.4500
person10.4600
person10.4700
person10.4800
person10.4900
person10.5000
person10.5100
person10.5200
person10.5300
person10.5400
person10.5500
person10.5600
person10.5700
person10.5800
person10.5900

First 60 of 184 rows.

Average precision by classHow do categories compare on one value — and across up to three groups?
View data
labelMeasureAverage precision
bicycleAP0.3373
bicycleAP500.4323
bicycleAP750.4323
carAP0.5007
carAP500.5545
carAP750.5545
personAP0.5799
personAP500.6931
personAP750.6931

Assumptions

  • Every object is labeled — Predictions of objects that the reference doesn't list count as false positives.
  • Predicted classes are in the reference — 1 predictions of 1 unknown class(es) were left out.
  • Enough objects per class — Fewer than 10 reference objects: bicycle, car.

COCO summary (boxes)

MetricIoUObject sizeDetections per imageValue
AP0.50:0.95all1000.4726
AP0.50all1000.5600
AP0.75all1000.5600
AP0.50:0.95small1000.2472
AP0.50:0.95medium1000.7396
AP0.50:0.95large1000.4713
AR0.50:0.95all10.3971
AR0.50:0.95all100.5342
AR0.50:0.95all1000.5342
AR0.50:0.95small1000.2667
AR0.50:0.95medium1000.7619
AR0.50:0.95large1000.4667

Size groups use the reference area: small < 32², medium 32²–96², large > 96² pixels. Empty = no object of that size.

Per class (IoU 0.50 counts with every image's top detections)

labelReference objectsCrowd regionsPredictionsAPAP50AP75AR@100True positivesFalse positivesMissed
bicycle70100.33730.43230.43230.4714463
car9090.50070.55450.55450.5111544
person101150.57990.69310.69310.6200763

Per image at IoU 0.50

media_idReference objectsPredictionsTrue positivesFalse positivesMissed
img0122111
img0234310
img0357233
img0423121
img0547430
img0625230
img0723121
img0832201
img0901010
img1030003
  • 1 predicted boxes have a class the reference never uses (dog); they can't be scored and were left out.
  • Reference rows: source = annotation; predictions: source = prediction. Crowd regions (iscrowd) absorb overlapping predictions without counting them. COCO conventions: IoU 0.50:0.05:0.95, 101 recall points, greedy matching by score within each image and class.
The exact R script · R R version 4.5.1 (2025-06-13)
# Object detection quality (COCO average precision)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method evaluate.detections 1.1.0 · spec b85c9129c0a7e375
# Dataset: img4_boxes (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr)  # cs_eval_det_* (COCO evaluation), cs_eval_stacked, cs_rle_* (COCO RLE strings)

# %% Data
IMG <- "media_id"
FRAME <- NULL
X0 <- "x0"; Y0 <- "y0"; X1 <- "x1"; Y1 <- "y1"
LABEL <- "label"; SCORE <- "score"
SOURCE <- "source"
CROWD <- "iscrowd"
AREA <- "area"
MASK <- NULL
WIDTH <- NULL
HEIGHT <- NULL
IOU_TYPE <- "bbox"  # bbox | segm
MAX_DETS <- as.integer(100)
AGNOSTIC <- FALSE
REF_LEVEL <- NULL
SOURCE_LEVELS <- c("annotation", "prediction")  # stored order
# Reference rows from a second table (option reference_table): its own column for each role, or NULL.
REF_ROLES <- NULL
columns <- unique(c(IMG, FRAME, X0, Y0, X1, Y1, LABEL, SCORE, SOURCE, CROWD, AREA, MASK, WIDTH, HEIGHT))
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/img4_boxes.parquet", col_select = columns))
if (IOU_TYPE == "segm" && (is.null(MASK) || is.null(WIDTH) || is.null(HEIGHT))) {
  cs_error("CS_E_INVALID_OPTION", option = "Overlap measured on", allowed = "Boxes unless the mask, width and height columns are set", value = "Masks")
}
pre_warnings <- list()
if (!is.null(REF_ROLES)) {
  # The reference table's rows go above this table's rows under an added source column (twin: with_reference).
  w <- cs_eval_with_reference(df, cs_graph_dataset_option("target/academy-parity/run-8142/evaluate.detections/boxes-coco/out-r", "reference_table"),
                              list(image = IMG, frame = FRAME, x0 = X0, y0 = Y0, x1 = X1, y1 = Y1, label = LABEL, score = SCORE,
                                   crowd = CROWD, area = AREA, mask = MASK, width = WIDTH, height = HEIGHT), REF_ROLES,
                              c(list(frame = "Frame"), if (IOU_TYPE == "segm") list(mask = "Mask", width = "Image width", height = "Image height")),
                              SOURCE, REF_LEVEL, c("image", "x0", "y0", "x1", "y1", "label", if (IOU_TYPE == "segm") c("mask", "width", "height")))
  df <- w$df
  pre_warnings <- w$warnings
  wc <- w$columns
  IMG <- wc$image; FRAME <- wc$frame; X0 <- wc$x0; Y0 <- wc$y0; X1 <- wc$x1; Y1 <- wc$y1
  LABEL <- wc$label; CROWD <- wc$crowd; AREA <- wc$area; MASK <- wc$mask; WIDTH <- wc$width; HEIGHT <- wc$height
  SOURCE <- w$source; REF_LEVEL <- w$reference; SOURCE_LEVELS <- w$levels
} else if (is.null(SOURCE)) {
  cs_error("CS_E_INVALID_OPTION", option = "Reference table", allowed = "a table of reference rows unless the Reference or prediction column is set", value = "none")
}
needed <- c(IMG, X0, Y0, X1, Y1, LABEL, SOURCE, if (IOU_TYPE == "segm") c(MASK, WIDTH, HEIGHT))
st <- cs_eval_stacked(df, needed, c(X0, Y0, X1, Y1, SCORE, AREA, WIDTH, HEIGHT), SOURCE, REF_LEVEL, SOURCE_LEVELS)
df <- st$df
is_ref <- st$is_ref
warnings <- c(pre_warnings, st$warnings)
score_all <- as.numeric(df[[SCORE]])
no_score <- !is_ref & is.na(score_all)
if (any(no_score)) {
  warnings <- c(warnings, sprintf("%d predicted boxes have no %s and were left out.", sum(no_score), SCORE))
  df <- df[!no_score, , drop = FALSE]
  is_ref <- is_ref[!no_score]
  score_all <- score_all[!no_score]
}
box <- cbind(as.numeric(df[[X0]]), as.numeric(df[[Y0]]), as.numeric(df[[X1]]), as.numeric(df[[Y1]]))
bad <- (box[, 3] < box[, 1]) | (box[, 4] < box[, 2])
if (any(bad)) cs_error("CS_E_INVALID_VALUES", column = sprintf("%s and %s", X1, Y1), requirement = sprintf("at least %s and %s", X0, Y0), count = sum(bad))
if (sum(is_ref) == 0L || sum(!is_ref) == 0L) cs_error("CS_E_GROUP_COUNT", column = SOURCE, expected = 2, k = 1)
crowd <- if (!is.null(CROWD)) cs_eval_flags(df[[CROWD]]) else logical(nrow(df))
crowd[!is_ref] <- FALSE  # predictions are never crowd regions
ik <- cs_eval_image_keys(df[[IMG]], if (!is.null(FRAME)) df[[FRAME]] else NULL)
img_idx <- ik$index
n_img <- length(ik$media)
labels_all <- as.character(df[[LABEL]])

# %% Masks (COCO run-length strings, column-major)
runs <- NULL
if (IOU_TYPE == "segm") {
  n_bad <- 0L
  ws <- as.numeric(df[[WIDTH]])
  hs <- as.numeric(df[[HEIGHT]])
  runs <- lapply(seq_len(nrow(df)), function(i) {
    tryCatch(cs_eval_det_runs(cs_rle_string_to_counts(as.character(df[[MASK]][i])), as.integer(hs[i]), as.integer(ws[i])),
             error = function(e) NULL)
  })
  n_bad <- sum(vapply(runs, is.null, logical(1)))
  if (n_bad > 0) cs_error("CS_E_INVALID_VALUES", column = MASK, requirement = "a COCO RLE string that covers width × height pixels", count = n_bad)
  sizes <- list()
  for (i in seq_along(runs)) {
    key <- as.character(img_idx[i])
    if (is.null(sizes[[key]])) sizes[[key]] <- runs[[i]]$size
    if (!identical(sizes[[key]], runs[[i]]$size)) {
      cs_error("CS_E_INVALID_VALUES", column = sprintf("%s and %s", WIDTH, HEIGHT), requirement = "the same size for every mask of an image", count = 1)
    }
  }
  obj_area <- vapply(runs, function(r) sum(r$e - r$s), numeric(1))
} else {
  obj_area <- cs_eval_det_box_area(box)
}

# %% Classes and areas
ref_classes <- sort(unique(labels_all[is_ref]), method = "radix")
classes <- if (AGNOSTIC) "(all classes)" else ref_classes
unknown <- sort(setdiff(unique(labels_all[!is_ref]), ref_classes), method = "radix")
known_pred <- !is_ref & labels_all %in% ref_classes
n_unk <- 0L
if (length(unknown)) {
  n_unk <- sum(!is_ref & !known_pred)
  shown <- paste0(paste(utils::head(unknown, 5), collapse = ", "), if (length(unknown) > 5) " …" else "")
  warnings <- c(warnings, sprintf("%d predicted boxes have a class the reference never uses (%s); they can't be scored and were left out.", n_unk, shown))
}
ref_area <- obj_area
if (!is.null(AREA)) {
  a_col <- as.numeric(df[[AREA]])
  ref_area <- ifelse(is.na(a_col), obj_area, a_col)
}
cat_all <- if (AGNOSTIC) rep(0L, nrow(df)) else { m <- match(labels_all, ref_classes) - 1L; m[is.na(m)] <- -1L; m }
gi <- which(is_ref)
di <- which(known_pred)
gt <- list(img = img_idx[gi], cat = cat_all[gi], box = box[gi, , drop = FALSE], area = ref_area[gi], crowd = crowd[gi],
           runs = if (!is.null(runs)) runs[gi] else NULL)
dt <- list(img = img_idx[di], cat = cat_all[di], box = box[di, , drop = FALSE], score = score_all[di], area = obj_area[di],
           runs = if (!is.null(runs)) runs[di] else NULL)

# %% COCO evaluation
max_dets <- c(1L, 10L, MAX_DETS)
ev <- cs_eval_det_evaluate(gt, dt, n_img, length(classes), IOU_TYPE, max_dets)
stats <- ev$stats
status <- ev$det_status  # per evaluated prediction at IoU 0.50: tp | fp | ignored | beyond
matched <- ev$det_match  # the reference it matched (0-based position in gt), -1 none
thr <- ev$thresholds
t50 <- which(thr == 0.5)[1]
nz <- function(v) if (is.null(v)) NA_real_ else v
n_ref_regular <- sum(!gt$crowd)
ref_hit <- logical(length(gi))
for (q in seq_along(di)) if (status[q] == "tp") ref_hit[matched[q] + 1L] <- TRUE
tp50 <- sum(status == "tp")
fp50 <- sum(status == "fp")
fn50 <- sum(!ref_hit & !gt$crowd)
per <- lapply(seq_along(classes), function(k) {
  pc <- cs_eval_det_per_class(ev$precision, ev$recall, thr, k)
  in_g <- gt$cat == k - 1L
  in_d <- dt$cat == k - 1L
  list(class = classes[k], n_ref = sum(in_g & !gt$crowd), n_crowd = sum(in_g & gt$crowd), n_pred = sum(in_d),
       ap = nz(pc$ap), ap50 = nz(pc$ap50), ap75 = nz(pc$ap75), ar = nz(pc$ar),
       tp = sum(in_d & status == "tp"), fp = sum(in_d & status == "fp"), fn = sum(in_g & !ref_hit & !gt$crowd))
})

# %% Assumptions
small <- vapply(Filter(function(p) p$n_ref < 10, per), function(p) p$class, character(1))
assumptions <- list(
  list(key = "complete", label = "Every object is labeled", status = "info",
       detail = "Predictions of objects that the reference doesn't list count as false positives."),
  list(key = "classes", label = "Predicted classes are in the reference", status = if (length(unknown)) "warn" else "pass",
       detail = if (length(unknown)) sprintf("%d predictions of %d unknown class(es) were left out.", n_unk, length(unknown)) else "Every predicted class appears in the reference."),
  list(key = "images", label = "Enough objects per class", status = if (length(small)) "warn" else "pass",
       detail = if (length(small)) sprintf("Fewer than 10 reference objects: %s%s.", paste(utils::head(small, 8), collapse = ", "), if (length(small) > 8) " …" else "") else "Every class has at least 10 reference objects.")
)

# %% Result
f3 <- function(v) if (is.null(v) || is.na(v)) "—" else sprintf("%.3f", v)
values <- list(n_images = n_img, n_classes = length(classes), n_reference = n_ref_regular, n_crowd = sum(gt$crowd),
               n_predictions = length(di), n_unknown_label = n_unk, iou_type = IOU_TYPE, max_dets = MAX_DETS,
               ap = nz(stats$ap), ap50 = nz(stats$ap50), ap75 = nz(stats$ap75), ap_small = nz(stats$ap_small),
               ap_medium = nz(stats$ap_medium), ap_large = nz(stats$ap_large), ar1 = nz(stats$ar_0), ar10 = nz(stats$ar_1),
               ar_max = nz(stats$ar_2), ar_small = nz(stats$ar_small), ar_medium = nz(stats$ar_medium), ar_large = nz(stats$ar_large),
               tp50 = tp50, fp50 = fp50, fn50 = fn50,
               precision50 = if (tp50 + fp50 > 0) tp50 / (tp50 + fp50) else NA_real_,
               recall50 = if (n_ref_regular > 0) tp50 / n_ref_regular else NA_real_)
for (p in per) for (key in c("ap", "ap50", "ap75", "ar")) values[[sprintf("%s[%s]", key, p$class)]] <- p[[key]]
sr <- list(list("AP", "0.50:0.95", "all", MAX_DETS, stats$ap), list("AP", "0.50", "all", MAX_DETS, stats$ap50),
           list("AP", "0.75", "all", MAX_DETS, stats$ap75), list("AP", "0.50:0.95", "small", MAX_DETS, stats$ap_small),
           list("AP", "0.50:0.95", "medium", MAX_DETS, stats$ap_medium), list("AP", "0.50:0.95", "large", MAX_DETS, stats$ap_large),
           list("AR", "0.50:0.95", "all", 1L, stats$ar_0), list("AR", "0.50:0.95", "all", 10L, stats$ar_1),
           list("AR", "0.50:0.95", "all", MAX_DETS, stats$ar_2), list("AR", "0.50:0.95", "small", MAX_DETS, stats$ar_small),
           list("AR", "0.50:0.95", "medium", MAX_DETS, stats$ar_medium), list("AR", "0.50:0.95", "large", MAX_DETS, stats$ar_large))
tables <- list(
  list(key = "coco", title = paste0("COCO summary", if (IOU_TYPE == "segm") " (masks)" else " (boxes)"),
       columns = list(list(key = "metric", label = "Metric", type = "string"), list(key = "iou", label = "IoU", type = "string"),
                      list(key = "area", label = "Object size", type = "string"), list(key = "max_dets", label = "Detections per image", type = "integer"),
                      list(key = "value", label = "Value", type = "number")),
       rows = lapply(sr, function(r) list(metric = r[[1]], iou = r[[2]], area = r[[3]], max_dets = r[[4]], value = nz(r[[5]]))),
       note = "Size groups use the reference area: small < 32², medium 32²–96², large > 96² pixels. Empty = no object of that size."),
  list(key = "classes", title = "Per class (IoU 0.50 counts with every image's top detections)",
       columns = list(list(key = "class", label = LABEL, type = "string"), list(key = "n_ref", label = "Reference objects", type = "integer"),
                      list(key = "n_crowd", label = "Crowd regions", type = "integer"), list(key = "n_pred", label = "Predictions", type = "integer"),
                      list(key = "ap", label = "AP", type = "number"), list(key = "ap50", label = "AP50", type = "number"),
                      list(key = "ap75", label = "AP75", type = "number"), list(key = "ar", label = sprintf("AR@%d", MAX_DETS), type = "number"),
                      list(key = "tp", label = "True positives", type = "integer"), list(key = "fp", label = "False positives", type = "integer"),
                      list(key = "fn", label = "Missed", type = "integer")),
       rows = per)
)
img_rows <- lapply(seq_len(n_img), function(i) {
  in_g <- gt$img == i - 1L
  in_d <- dt$img == i - 1L
  list(image = ik$media[i], frame = if (is.infinite(ik$frame[i])) NA_real_ else ik$frame[i], n_ref = sum(in_g & !gt$crowd),
       n_pred = sum(in_d), tp = sum(in_d & status == "tp"), fp = sum(in_d & status == "fp"), fn = sum(in_g & !ref_hit & !gt$crowd))
})
img_cols <- c(list(list(key = "image", label = IMG, type = "string")), if (!is.null(FRAME)) list(list(key = "frame", label = FRAME, type = "number")),
              list(list(key = "n_ref", label = "Reference objects", type = "integer"), list(key = "n_pred", label = "Predictions", type = "integer"),
                   list(key = "tp", label = "True positives", type = "integer"), list(key = "fp", label = "False positives", type = "integer"),
                   list(key = "fn", label = "Missed", type = "integer")))
tables[[length(tables) + 1L]] <- list(key = "images", title = "Per image at IoU 0.50", columns = img_cols, rows = utils::head(img_rows, 500),
                                      note = if (n_img > 500) "First 500 images." else NULL)
charts <- list()
rec <- ev$recall_points
m_last <- length(max_dets)
nref <- vapply(per, function(p) p$n_ref, numeric(1))
top <- utils::head(order(-nref, seq_along(per), method = "radix"), 8)
cr <- numeric(0); cp <- numeric(0); cc <- character(0)
for (k in top) {
  if (per[[k]]$n_ref == 0) next
  reach <- ev$recall[t50, k, 1, m_last]
  pk <- ev$precision[t50, , k, 1, m_last]
  sel <- rec <= reach
  cr <- c(cr, rec[sel]); cp <- c(cp, pk[sel]); cc <- c(cc, rep(per[[k]]$class, sum(sel)))
}
if (length(cr)) {
  shown <- vapply(Filter(function(k) per[[k]]$n_ref > 0, top), function(k) per[[k]]$class, character(1))
  charts[[length(charts) + 1L]] <- cs_chart("pr", "pr-curve", "Precision–recall at IoU 0.50, by class", list(
    recall = cs_col("Recall", cr, "numeric"), precision = cs_col("Precision (interpolated)", cp, "numeric"),
    curve = cs_col(LABEL, cc, "categorical", levels = shown)),
    note = paste0("COCO's interpolated precision at 101 recall points, up to the recall each class reaches.", if (length(per) > 8) " The 8 classes with the most reference objects." else ""))
}
dc <- character(0); dm <- character(0); dv <- numeric(0)
for (p in per) for (km in list(c("ap", "AP"), c("ap50", "AP50"), c("ap75", "AP75"))) if (!is.na(p[[km[1]]])) {
  dc <- c(dc, p$class); dm <- c(dm, km[2]); dv <- c(dv, p[[km[1]]])
}
if (length(dv)) {
  charts[[length(charts) + 1L]] <- cs_chart("ap-by-class", "cleveland-dot", "Average precision by class", list(
    category = cs_col(LABEL, dc, "categorical", levels = classes), value = cs_col("Average precision", dv, "numeric"),
    group = cs_col("Measure", dm, "categorical", levels = c("AP", "AP50", "AP75"))))
}
summary <- sprintf("Across %d images and %d class%s, AP (IoU 0.50:0.95) = %s, AP50 = %s and AP75 = %s; average recall with up to %d detections per image = %s. At IoU 0.50: %d true positives, %d false positives, %d missed objects.",
                   n_img, length(classes), if (length(classes) != 1) "es" else "", f3(stats$ap), f3(stats$ap50), f3(stats$ap75), MAX_DETS, f3(stats$ar_2), tp50, fp50, fn50)
cs_publish(list(
  method = "evaluate.detections",
  methodVersion = "1.1.0",
  title = "Object detection quality",
  engine = cs_engine_info("nanoparquet"),
  n = nrow(df),
  summary = summary,
  statistics = list(list(key = "ap", label = "AP (0.50:0.95)", value = nz(stats$ap)), list(key = "ap50", label = "AP50", value = nz(stats$ap50)),
                    list(key = "ap75", label = "AP75", value = nz(stats$ap75)), list(key = "ar_max", label = sprintf("AR@%d", MAX_DETS), value = nz(stats$ar_2))),
  tables = tables,
  assumptions = assumptions,
  warnings = warnings,
  notes = list(paste0(if (is.null(REF_ROLES)) sprintf("Reference rows: %s = %s; predictions: %s = %s. ", SOURCE, st$reference, SOURCE, st$prediction)
                      else "Reference rows come from the reference table; this table's rows are the predictions. ",
                      if (AGNOSTIC) "Classes ignored: any predicted box can match any reference box. " else "",
                      if (!is.null(CROWD)) sprintf("Crowd regions (%s) absorb overlapping predictions without counting them. ", CROWD) else "",
                      "COCO conventions: IoU 0.50:0.05:0.95, 101 recall points, greedy matching by score within each image and class.")),
  charts = charts,
  values = values
))
Python

Across 10 images and 3 classes, AP (IoU 0.50:0.95) = 0.473, AP50 = 0.560 and AP75 = 0.560; average recall with up to 100 detections per image = 0.534. At IoU 0.50: 16 true positives, 16 false positives, 10 missed objects.

AP (0.50:0.95)
0.4726
AP50
0.5600
AP75
0.5600
AR@100
0.5342

To keep this page light, the plots are shown once, under the R tab.

Assumptions

  • Every object is labeled — Predictions of objects that the reference doesn't list count as false positives.
  • Predicted classes are in the reference — 1 predictions of 1 unknown class(es) were left out.
  • Enough objects per class — Fewer than 10 reference objects: bicycle, car.

COCO summary (boxes)

MetricIoUObject sizeDetections per imageValue
AP0.50:0.95all1000.4726
AP0.50all1000.5600
AP0.75all1000.5600
AP0.50:0.95small1000.2472
AP0.50:0.95medium1000.7396
AP0.50:0.95large1000.4713
AR0.50:0.95all10.3971
AR0.50:0.95all100.5342
AR0.50:0.95all1000.5342
AR0.50:0.95small1000.2667
AR0.50:0.95medium1000.7619
AR0.50:0.95large1000.4667

Size groups use the reference area: small < 32², medium 32²–96², large > 96² pixels. Empty = no object of that size.

Per class (IoU 0.50 counts with every image's top detections)

labelReference objectsCrowd regionsPredictionsAPAP50AP75AR@100True positivesFalse positivesMissed
bicycle70100.33730.43230.43230.4714463
car9090.50070.55450.55450.5111544
person101150.57990.69310.69310.6200763

Per image at IoU 0.50

media_idReference objectsPredictionsTrue positivesFalse positivesMissed
img0122111
img0234310
img0357233
img0423121
img0547430
img0625230
img0723121
img0832201
img0901010
img1030003
  • 1 predicted boxes have a class the reference never uses (dog); they can't be scored and were left out.
  • Reference rows: source = annotation; predictions: source = prediction. Crowd regions (iscrowd) absorb overlapping predictions without counting them. COCO conventions: IoU 0.50:0.05:0.95, 101 recall points, greedy matching by score within each image and class.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Object detection quality (COCO average precision)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method evaluate.detections 1.1.0 · spec b85c9129c0a7e375
# Dataset: img4_boxes (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
import numpy as np
import pandas as pd

import codesplash as cs
from codesplash.evaluate import detection as det  # twin: codesplashr cs_eval_det_*
from codesplash.evaluate.stacked import flags, image_keys, stacked  # twin: cs_eval_stacked
from codesplash.vision import boxes as vb  # COCO RLE strings (twin: cs_rle_*)

# %% Data
IMG = "media_id"
FRAME = None
X0, Y0, X1, Y1 = "x0", "y0", "x1", "y1"
LABEL, SCORE = "label", "score"
SOURCE = "source"
CROWD = "iscrowd"
AREA = "area"
MASK = None
WIDTH = None
HEIGHT = None
IOU_TYPE = "bbox"  # bbox | segm
MAX_DETS = int(100)
AGNOSTIC = False
REF_LEVEL = None
SOURCE_LEVELS = ["annotation", "prediction"]  # stored order
# Reference rows from a second table (option reference_table): its own column for each role, or None.
REF_ROLES = None
columns = list(dict.fromkeys(c for c in [IMG, FRAME, X0, Y0, X1, Y1, LABEL, SCORE, SOURCE, CROWD, AREA, MASK, WIDTH, HEIGHT] if c))
df = pd.read_parquet("tests/parity/fixtures/img4_boxes.parquet", columns=columns)
if IOU_TYPE == "segm" and not (MASK and WIDTH and HEIGHT):
    cs.cs_error("CS_E_INVALID_OPTION", option="Overlap measured on", allowed="Boxes unless the mask, width and height columns are set", value="Masks")
pre_warnings = []
if REF_ROLES is not None:
    # The reference table's rows go above this table's rows under an added source column (twin: cs_eval_with_reference).
    from codesplash.graph import dataset_option  # the table the host wrote for the option
    from codesplash.evaluate.stacked import with_reference
    w = with_reference(df, dataset_option("target/academy-parity/run-8142/evaluate.detections/boxes-coco/out-python", "reference_table"),
                       {"image": IMG, "frame": FRAME, "x0": X0, "y0": Y0, "x1": X1, "y1": Y1, "label": LABEL, "score": SCORE,
                        "crowd": CROWD, "area": AREA, "mask": MASK, "width": WIDTH, "height": HEIGHT}, REF_ROLES,
                       {"frame": "Frame", **({"mask": "Mask", "width": "Image width", "height": "Image height"} if IOU_TYPE == "segm" else {})},
                       SOURCE, REF_LEVEL, ["image", "x0", "y0", "x1", "y1", "label"] + (["mask", "width", "height"] if IOU_TYPE == "segm" else []))
    df, pre_warnings, wc = w["df"], w["warnings"], w["columns"]
    IMG, FRAME, X0, Y0, X1, Y1 = wc["image"], wc["frame"], wc["x0"], wc["y0"], wc["x1"], wc["y1"]
    LABEL, CROWD, AREA, MASK, WIDTH, HEIGHT = wc["label"], wc["crowd"], wc["area"], wc["mask"], wc["width"], wc["height"]
    SOURCE, REF_LEVEL, SOURCE_LEVELS = w["source"], w["reference"], w["levels"]
elif SOURCE is None:
    cs.cs_error("CS_E_INVALID_OPTION", option="Reference table", allowed="a table of reference rows unless the Reference or prediction column is set", value="none")
needed = [IMG, X0, Y0, X1, Y1, LABEL, SOURCE] + ([MASK, WIDTH, HEIGHT] if IOU_TYPE == "segm" else [])
st = stacked(df, needed, [c for c in [X0, Y0, X1, Y1, SCORE, AREA, WIDTH, HEIGHT] if c], SOURCE, REF_LEVEL, SOURCE_LEVELS)
df, is_ref, warnings = st["df"], st["is_ref"], pre_warnings + st["warnings"]
score_all = df[SCORE].to_numpy(dtype=float, na_value=np.nan)
no_score = ~is_ref & np.isnan(score_all)
if no_score.any():
    warnings.append(f"{int(no_score.sum())} predicted boxes have no {SCORE} and were left out.")
    df, is_ref, score_all = df.loc[~no_score].reset_index(drop=True), is_ref[~no_score], score_all[~no_score]
box = df[[X0, Y0, X1, Y1]].to_numpy(dtype=float)
bad = (box[:, 2] < box[:, 0]) | (box[:, 3] < box[:, 1])
if bad.any():
    cs.cs_error("CS_E_INVALID_VALUES", column=f"{X1} and {Y1}", requirement=f"at least {X0} and {Y0}", count=int(bad.sum()))
if int(is_ref.sum()) == 0 or int((~is_ref).sum()) == 0:
    cs.cs_error("CS_E_GROUP_COUNT", column=SOURCE, expected=2, k=1)
crowd = flags(df[CROWD]) if CROWD else np.zeros(len(df), dtype=bool)
crowd[~is_ref] = False  # predictions are never crowd regions
img_idx, images = image_keys(df[IMG], df[FRAME] if FRAME else None)
labels_all = np.asarray([str(x) for x in df[LABEL].tolist()], dtype=object)

# %% Masks (COCO run-length strings, column-major)
runs = None
if IOU_TYPE == "segm":
    runs, n_bad = [], 0
    for s, w, h in zip(df[MASK].tolist(), df[WIDTH].to_numpy(dtype=float), df[HEIGHT].to_numpy(dtype=float)):
        try:
            runs.append(det.runs_from_counts(vb.string_to_counts(str(s)), int(h), int(w)))
        except (ValueError, OverflowError):
            runs.append(None)
            n_bad += 1
    if n_bad:
        cs.cs_error("CS_E_INVALID_VALUES", column=MASK, requirement="a COCO RLE string that covers width × height pixels", count=n_bad)
    sizes = {}
    for i, r in enumerate(runs):
        if sizes.setdefault(int(img_idx[i]), r[2]) != r[2]:
            cs.cs_error("CS_E_INVALID_VALUES", column=f"{WIDTH} and {HEIGHT}", requirement="the same size for every mask of an image", count=1)
    obj_area = np.asarray([det.runs_area(r) for r in runs])
else:
    obj_area = det.box_area(box)

# %% Classes and areas
ref_classes = sorted(set(labels_all[is_ref].tolist()))
classes = ["(all classes)"] if AGNOSTIC else ref_classes
cat_of = {c: i for i, c in enumerate(ref_classes)}
unknown = sorted(set(labels_all[~is_ref].tolist()) - set(ref_classes))
known_pred = ~is_ref & np.asarray([lab in cat_of for lab in labels_all])
if unknown:
    n_unk = int((~is_ref & ~known_pred).sum())
    shown = ", ".join(unknown[:5]) + (" …" if len(unknown) > 5 else "")
    warnings.append(f"{n_unk} predicted boxes have a class the reference never uses ({shown}); they can't be scored and were left out.")
else:
    n_unk = 0
ref_area = obj_area.copy()
if AREA:
    a_col = df[AREA].to_numpy(dtype=float, na_value=np.nan)
    ref_area = np.where(np.isnan(a_col), obj_area, a_col)
cat_all = np.asarray([0 if AGNOSTIC else cat_of.get(lab, -1) for lab in labels_all], dtype=int)
gi = np.flatnonzero(is_ref)
di = np.flatnonzero(known_pred)
gt = {"img": img_idx[gi], "cat": cat_all[gi], "box": box[gi], "area": ref_area[gi], "crowd": crowd[gi],
      "runs": [runs[j] for j in gi] if runs is not None else None}
dt = {"img": img_idx[di], "cat": cat_all[di], "box": box[di], "score": score_all[di], "area": obj_area[di],
      "runs": [runs[j] for j in di] if runs is not None else None}

# %% COCO evaluation
max_dets = (1, 10, MAX_DETS)
ev = det.evaluate(gt, dt, len(images), len(classes), IOU_TYPE, max_dets)
stats = ev["stats"]
status = ev["det_status"]   # per evaluated prediction at IoU 0.50: tp | fp | ignored | beyond
matched = ev["det_match"]   # the reference it matched (position in gt), −1 none
thr = ev["thresholds"]
t50 = int(np.flatnonzero(thr == 0.5)[0])
n_ref_regular = int((~gt["crowd"]).sum())
ref_hit = np.zeros(gi.size, dtype=bool)
for q in range(di.size):
    if status[q] == "tp":
        ref_hit[matched[q]] = True
tp50 = int(np.sum(status == "tp"))
fp50 = int(np.sum(status == "fp"))
fn50 = int(np.sum(~ref_hit & ~gt["crowd"]))
per = []
for k, c in enumerate(classes):
    pc = det.per_class(ev["precision"], ev["recall"], thr, k)
    in_g = gt["cat"] == k
    in_d = dt["cat"] == k
    per.append({"class": c, "n_ref": int(np.sum(in_g & ~gt["crowd"])), "n_crowd": int(np.sum(in_g & gt["crowd"])),
                "n_pred": int(np.sum(in_d)), "ap": pc["ap"], "ap50": pc["ap50"], "ap75": pc["ap75"], "ar": pc["ar"],
                "tp": int(np.sum(in_d & (status == "tp"))), "fp": int(np.sum(in_d & (status == "fp"))),
                "fn": int(np.sum(in_g & ~ref_hit & ~gt["crowd"]))})

# %% Assumptions
small = [p["class"] for p in per if p["n_ref"] < 10]
assumptions = [
    {"key": "complete", "label": "Every object is labeled", "status": "info",
     "detail": "Predictions of objects that the reference doesn't list count as false positives."},
    {"key": "classes", "label": "Predicted classes are in the reference", "status": "warn" if unknown else "pass",
     "detail": (f"{n_unk} predictions of {len(unknown)} unknown class(es) were left out." if unknown else "Every predicted class appears in the reference.")},
    {"key": "images", "label": "Enough objects per class", "status": "warn" if small else "pass",
     "detail": (f"Fewer than 10 reference objects: {', '.join(small[:8])}{' …' if len(small) > 8 else ''}." if small else "Every class has at least 10 reference objects.")},
]

# %% Result
f3 = lambda v: "—" if v is None else f"{v:.3f}"
values = {"n_images": len(images), "n_classes": len(classes), "n_reference": n_ref_regular, "n_crowd": int(gt["crowd"].sum()),
          "n_predictions": int(di.size), "n_unknown_label": n_unk, "iou_type": IOU_TYPE, "max_dets": MAX_DETS,
          "ap": stats["ap"], "ap50": stats["ap50"], "ap75": stats["ap75"], "ap_small": stats["ap_small"],
          "ap_medium": stats["ap_medium"], "ap_large": stats["ap_large"], "ar1": stats["ar_0"], "ar10": stats["ar_1"],
          "ar_max": stats["ar_2"], "ar_small": stats["ar_small"], "ar_medium": stats["ar_medium"], "ar_large": stats["ar_large"],
          "tp50": tp50, "fp50": fp50, "fn50": fn50,
          "precision50": tp50 / (tp50 + fp50) if (tp50 + fp50) else None,
          "recall50": tp50 / n_ref_regular if n_ref_regular else None}
for p in per:
    for key in ("ap", "ap50", "ap75", "ar"):
        values[f"{key}[{p['class']}]"] = p[key]
summary_rows = [
    ("AP", "0.50:0.95", "all", MAX_DETS, stats["ap"]), ("AP", "0.50", "all", MAX_DETS, stats["ap50"]),
    ("AP", "0.75", "all", MAX_DETS, stats["ap75"]), ("AP", "0.50:0.95", "small", MAX_DETS, stats["ap_small"]),
    ("AP", "0.50:0.95", "medium", MAX_DETS, stats["ap_medium"]), ("AP", "0.50:0.95", "large", MAX_DETS, stats["ap_large"]),
    ("AR", "0.50:0.95", "all", 1, stats["ar_0"]), ("AR", "0.50:0.95", "all", 10, stats["ar_1"]),
    ("AR", "0.50:0.95", "all", MAX_DETS, stats["ar_2"]), ("AR", "0.50:0.95", "small", MAX_DETS, stats["ar_small"]),
    ("AR", "0.50:0.95", "medium", MAX_DETS, stats["ar_medium"]), ("AR", "0.50:0.95", "large", MAX_DETS, stats["ar_large"]),
]
tables = [
    {"key": "coco", "title": "COCO summary" + (" (masks)" if IOU_TYPE == "segm" else " (boxes)"),
     "columns": [{"key": "metric", "label": "Metric", "type": "string"}, {"key": "iou", "label": "IoU", "type": "string"},
                 {"key": "area", "label": "Object size", "type": "string"}, {"key": "max_dets", "label": "Detections per image", "type": "integer"},
                 {"key": "value", "label": "Value", "type": "number"}],
     "rows": [{"metric": m, "iou": t, "area": a, "max_dets": d, "value": v} for m, t, a, d, v in summary_rows],
     "note": "Size groups use the reference area: small < 32², medium 32²–96², large > 96² pixels. Empty = no object of that size."},
    {"key": "classes", "title": "Per class (IoU 0.50 counts with every image's top detections)",
     "columns": [{"key": "class", "label": LABEL, "type": "string"}, {"key": "n_ref", "label": "Reference objects", "type": "integer"},
                 {"key": "n_crowd", "label": "Crowd regions", "type": "integer"}, {"key": "n_pred", "label": "Predictions", "type": "integer"},
                 {"key": "ap", "label": "AP", "type": "number"}, {"key": "ap50", "label": "AP50", "type": "number"},
                 {"key": "ap75", "label": "AP75", "type": "number"}, {"key": "ar", "label": f"AR@{MAX_DETS}", "type": "number"},
                 {"key": "tp", "label": "True positives", "type": "integer"}, {"key": "fp", "label": "False positives", "type": "integer"},
                 {"key": "fn", "label": "Missed", "type": "integer"}],
     "rows": per},
]
img_rows = []
for i, (m, f) in enumerate(images):
    in_g = gt["img"] == i
    in_d = dt["img"] == i
    img_rows.append({"image": m, "frame": None if f == float("-inf") else f, "n_ref": int(np.sum(in_g & ~gt["crowd"])),
                     "n_pred": int(np.sum(in_d)), "tp": int(np.sum(in_d & (status == "tp"))), "fp": int(np.sum(in_d & (status == "fp"))),
                     "fn": int(np.sum(in_g & ~ref_hit & ~gt["crowd"]))})
img_cols = [{"key": "image", "label": IMG, "type": "string"}] + ([{"key": "frame", "label": FRAME, "type": "number"}] if FRAME else []) + [
    {"key": "n_ref", "label": "Reference objects", "type": "integer"}, {"key": "n_pred", "label": "Predictions", "type": "integer"},
    {"key": "tp", "label": "True positives", "type": "integer"}, {"key": "fp", "label": "False positives", "type": "integer"},
    {"key": "fn", "label": "Missed", "type": "integer"}]
tables.append({"key": "images", "title": "Per image at IoU 0.50", "columns": img_cols, "rows": img_rows[:500],
               "note": "First 500 images." if len(img_rows) > 500 else None})
charts = []
rec = ev["recall_points"]
top = sorted(range(len(per)), key=lambda k: (-per[k]["n_ref"], k))[:8]
cr, cp, cc = [], [], []
for k in top:
    if per[k]["n_ref"] == 0:
        continue
    reach = ev["recall"][t50, k, 0, -1]
    for r, p in zip(rec, ev["precision"][t50, :, k, 0, -1]):
        if r <= reach:
            cr.append(float(r))
            cp.append(float(p))
            cc.append(per[k]["class"])
if cr:
    shown = [per[k]["class"] for k in top if per[k]["n_ref"] > 0]
    charts.append(cs.chart("pr", "pr-curve", "Precision–recall at IoU 0.50, by class", {
        "recall": cs.col("Recall", cr, "numeric"), "precision": cs.col("Precision (interpolated)", cp, "numeric"),
        "curve": cs.col(LABEL, cc, "categorical", levels=shown)},
        note="COCO's interpolated precision at 101 recall points, up to the recall each class reaches." + (" The 8 classes with the most reference objects." if len(per) > 8 else "")))
dots = [(p["class"], m, p[key]) for p in per for key, m in (("ap", "AP"), ("ap50", "AP50"), ("ap75", "AP75")) if p[key] is not None]
if dots:
    charts.append(cs.chart("ap-by-class", "cleveland-dot", "Average precision by class", {
        "category": cs.col(LABEL, [d[0] for d in dots], "categorical", levels=classes),
        "value": cs.col("Average precision", [d[2] for d in dots], "numeric"),
        "group": cs.col("Measure", [d[1] for d in dots], "categorical", levels=["AP", "AP50", "AP75"])}))
summary = (f"Across {len(images)} images and {len(classes)} class{'es' if len(classes) != 1 else ''}, AP (IoU 0.50:0.95) = {f3(stats['ap'])}, "
           f"AP50 = {f3(stats['ap50'])} and AP75 = {f3(stats['ap75'])}; average recall with up to {MAX_DETS} detections per image = {f3(stats['ar_2'])}. "
           f"At IoU 0.50: {tp50} true positives, {fp50} false positives, {fn50} missed objects.")
cs.publish({
    "method": "evaluate.detections",
    "methodVersion": "1.1.0",
    "title": "Object detection quality",
    "engine": cs.engine_info("pandas", "numpy"),
    "n": int(len(df)),
    "summary": summary,
    "statistics": [{"key": "ap", "label": "AP (0.50:0.95)", "value": stats["ap"]}, {"key": "ap50", "label": "AP50", "value": stats["ap50"]},
                   {"key": "ap75", "label": "AP75", "value": stats["ap75"]}, {"key": "ar_max", "label": f"AR@{MAX_DETS}", "value": stats["ar_2"]}],
    "tables": tables,
    "assumptions": assumptions,
    "warnings": warnings,
    "notes": [(f"Reference rows: {SOURCE} = {st['reference']}; predictions: {SOURCE} = {st['prediction']}. " if REF_ROLES is None
               else "Reference rows come from the reference table; this table's rows are the predictions. ")
              + ("Classes ignored: any predicted box can match any reference box. " if AGNOSTIC else "")
              + ("Crowd regions (" + CROWD + ") absorb overlapping predictions without counting them. " if CROWD else "")
              + "COCO conventions: IoU 0.50:0.05:0.95, 101 recall points, greedy matching by score within each image and class."],
    "charts": charts,
    "values": values,
})

On these 10 images the detector reaches AP 0.473, AP50 0.560 and AP75 0.560. The size split matters more: AP on small objects is 0.247 against 0.740 on medium ones. If your objects are small (parts on a belt, birds on a cliff), the headline number overstates what you'll get.

03

The detection limit

Predict

Predict first

The same predictions are scored again, but only each image's 20 highest-scoring boxes count (instead of 100). What happens to AP?

AP goes upAP goes downAP stays the same
Reveal

It goes down here, from 0.473 to 0.456: some correct boxes ranked below 20th in their image. Busy scenes need a higher limit, and two scores are only comparable at the same limit.

Object detection qualityRecorded · Python and R agreeRecorded 2026-11-25 · 37 values compared
R

Across 10 images and 3 classes, AP (IoU 0.50:0.95) = 0.456, AP50 = 0.540 and AP75 = 0.540; average recall with up to 20 detections per image = 0.515. At IoU 0.50: 16 true positives, 18 false positives, 11 missed objects.

AP (0.50:0.95)
0.4557
AP50
0.5402
AP75
0.5402
AR@20
0.5154

Plots

Precision–recall at IoU 0.50, by classHow much precision does the model keep as it finds more of the positives?

COCO's interpolated precision at 101 recall points, up to the recall each class reaches.

View data
labelPrecision (interpolated)Recall
person10
person10.0100
person10.0200
person10.0300
person10.0400
person10.0500
person10.0600
person10.0700
person10.0800
person10.0900
person10.1000
person10.1100
person10.1200
person10.1300
person10.1400
person10.1500
person10.1600
person10.1700
person10.1800
person10.1900
person10.2000
person10.2100
person10.2200
person10.2300
person10.2400
person10.2500
person10.2600
person10.2700
person10.2800
person10.2900
person10.3000
person10.3100
person10.3200
person10.3300
person10.3400
person10.3500
person10.3600
person10.3700
person10.3800
person10.3900
person10.4000
person10.4100
person10.4200
person10.4300
person10.4400
person10.4500
person10.4600
person10.4700
person10.4800
person10.4900
person10.5000
person10.5100
person10.5200
person10.5300
person10.5400
person10.5500
person10.5600
person10.5700
person10.5800
person10.5900

First 60 of 178 rows.

Average precision by classHow do categories compare on one value — and across up to three groups?
View data
labelMeasureAverage precision
bicycleAP0.3373
bicycleAP500.4323
bicycleAP750.4323
carAP0.5007
carAP500.5545
carAP750.5545
personAP0.5290
personAP500.6337
personAP750.6337

Assumptions

  • Every object is labeled — Predictions of objects that the reference doesn't list count as false positives.
  • Predicted classes are in the reference — 1 predictions of 1 unknown class(es) were left out.
  • Enough objects per class — Fewer than 10 reference objects: bicycle, car.

COCO summary (boxes)

MetricIoUObject sizeDetections per imageValue
AP0.50:0.95all200.4557
AP0.50all200.5402
AP0.75all200.5402
AP0.50:0.95small200.2785
AP0.50:0.95medium200.5325
AP0.50:0.95large200.6238
AR0.50:0.95all10.3814
AR0.50:0.95all100.5154
AR0.50:0.95all200.5154
AR0.50:0.95small200.3042
AR0.50:0.95medium200.5524
AR0.50:0.95large200.7889

Size groups use the reference area: small < 32², medium 32²–96², large > 96² pixels. Empty = no object of that size.

Per class (IoU 0.50 counts with every image's top detections)

labelReference objectsCrowd regionsPredictionsAPAP50AP75AR@20True positivesFalse positivesMissed
bicycle70100.33730.43230.43230.4714463
car9090.50070.55450.55450.5111544
person110150.52900.63370.63370.5636784

Per image at IoU 0.50

media_idReference objectsPredictionsTrue positivesFalse positivesMissed
img0122111
img0234310
img0367254
img0423121
img0547430
img0625230
img0723121
img0832201
img0901010
img1030003
  • 1 predicted boxes have a class the reference never uses (dog); they can't be scored and were left out.
  • Reference rows: source = annotation; predictions: source = prediction. COCO conventions: IoU 0.50:0.05:0.95, 101 recall points, greedy matching by score within each image and class.
The exact R script · R R version 4.5.1 (2025-06-13)
# Object detection quality (COCO average precision)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method evaluate.detections 1.1.0 · spec f62e80af7d49a7b5
# Dataset: img4_boxes (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr)  # cs_eval_det_* (COCO evaluation), cs_eval_stacked, cs_rle_* (COCO RLE strings)

# %% Data
IMG <- "media_id"
FRAME <- NULL
X0 <- "x0"; Y0 <- "y0"; X1 <- "x1"; Y1 <- "y1"
LABEL <- "label"; SCORE <- "score"
SOURCE <- "source"
CROWD <- NULL
AREA <- NULL
MASK <- NULL
WIDTH <- NULL
HEIGHT <- NULL
IOU_TYPE <- "bbox"  # bbox | segm
MAX_DETS <- as.integer(20)
AGNOSTIC <- FALSE
REF_LEVEL <- NULL
SOURCE_LEVELS <- c("annotation", "prediction")  # stored order
# Reference rows from a second table (option reference_table): its own column for each role, or NULL.
REF_ROLES <- NULL
columns <- unique(c(IMG, FRAME, X0, Y0, X1, Y1, LABEL, SCORE, SOURCE, CROWD, AREA, MASK, WIDTH, HEIGHT))
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/img4_boxes.parquet", col_select = columns))
if (IOU_TYPE == "segm" && (is.null(MASK) || is.null(WIDTH) || is.null(HEIGHT))) {
  cs_error("CS_E_INVALID_OPTION", option = "Overlap measured on", allowed = "Boxes unless the mask, width and height columns are set", value = "Masks")
}
pre_warnings <- list()
if (!is.null(REF_ROLES)) {
  # The reference table's rows go above this table's rows under an added source column (twin: with_reference).
  w <- cs_eval_with_reference(df, cs_graph_dataset_option("target/academy-parity/run-8142/evaluate.detections/boxes-plain-limit-20/out-r", "reference_table"),
                              list(image = IMG, frame = FRAME, x0 = X0, y0 = Y0, x1 = X1, y1 = Y1, label = LABEL, score = SCORE,
                                   crowd = CROWD, area = AREA, mask = MASK, width = WIDTH, height = HEIGHT), REF_ROLES,
                              c(list(frame = "Frame"), if (IOU_TYPE == "segm") list(mask = "Mask", width = "Image width", height = "Image height")),
                              SOURCE, REF_LEVEL, c("image", "x0", "y0", "x1", "y1", "label", if (IOU_TYPE == "segm") c("mask", "width", "height")))
  df <- w$df
  pre_warnings <- w$warnings
  wc <- w$columns
  IMG <- wc$image; FRAME <- wc$frame; X0 <- wc$x0; Y0 <- wc$y0; X1 <- wc$x1; Y1 <- wc$y1
  LABEL <- wc$label; CROWD <- wc$crowd; AREA <- wc$area; MASK <- wc$mask; WIDTH <- wc$width; HEIGHT <- wc$height
  SOURCE <- w$source; REF_LEVEL <- w$reference; SOURCE_LEVELS <- w$levels
} else if (is.null(SOURCE)) {
  cs_error("CS_E_INVALID_OPTION", option = "Reference table", allowed = "a table of reference rows unless the Reference or prediction column is set", value = "none")
}
needed <- c(IMG, X0, Y0, X1, Y1, LABEL, SOURCE, if (IOU_TYPE == "segm") c(MASK, WIDTH, HEIGHT))
st <- cs_eval_stacked(df, needed, c(X0, Y0, X1, Y1, SCORE, AREA, WIDTH, HEIGHT), SOURCE, REF_LEVEL, SOURCE_LEVELS)
df <- st$df
is_ref <- st$is_ref
warnings <- c(pre_warnings, st$warnings)
score_all <- as.numeric(df[[SCORE]])
no_score <- !is_ref & is.na(score_all)
if (any(no_score)) {
  warnings <- c(warnings, sprintf("%d predicted boxes have no %s and were left out.", sum(no_score), SCORE))
  df <- df[!no_score, , drop = FALSE]
  is_ref <- is_ref[!no_score]
  score_all <- score_all[!no_score]
}
box <- cbind(as.numeric(df[[X0]]), as.numeric(df[[Y0]]), as.numeric(df[[X1]]), as.numeric(df[[Y1]]))
bad <- (box[, 3] < box[, 1]) | (box[, 4] < box[, 2])
if (any(bad)) cs_error("CS_E_INVALID_VALUES", column = sprintf("%s and %s", X1, Y1), requirement = sprintf("at least %s and %s", X0, Y0), count = sum(bad))
if (sum(is_ref) == 0L || sum(!is_ref) == 0L) cs_error("CS_E_GROUP_COUNT", column = SOURCE, expected = 2, k = 1)
crowd <- if (!is.null(CROWD)) cs_eval_flags(df[[CROWD]]) else logical(nrow(df))
crowd[!is_ref] <- FALSE  # predictions are never crowd regions
ik <- cs_eval_image_keys(df[[IMG]], if (!is.null(FRAME)) df[[FRAME]] else NULL)
img_idx <- ik$index
n_img <- length(ik$media)
labels_all <- as.character(df[[LABEL]])

# %% Masks (COCO run-length strings, column-major)
runs <- NULL
if (IOU_TYPE == "segm") {
  n_bad <- 0L
  ws <- as.numeric(df[[WIDTH]])
  hs <- as.numeric(df[[HEIGHT]])
  runs <- lapply(seq_len(nrow(df)), function(i) {
    tryCatch(cs_eval_det_runs(cs_rle_string_to_counts(as.character(df[[MASK]][i])), as.integer(hs[i]), as.integer(ws[i])),
             error = function(e) NULL)
  })
  n_bad <- sum(vapply(runs, is.null, logical(1)))
  if (n_bad > 0) cs_error("CS_E_INVALID_VALUES", column = MASK, requirement = "a COCO RLE string that covers width × height pixels", count = n_bad)
  sizes <- list()
  for (i in seq_along(runs)) {
    key <- as.character(img_idx[i])
    if (is.null(sizes[[key]])) sizes[[key]] <- runs[[i]]$size
    if (!identical(sizes[[key]], runs[[i]]$size)) {
      cs_error("CS_E_INVALID_VALUES", column = sprintf("%s and %s", WIDTH, HEIGHT), requirement = "the same size for every mask of an image", count = 1)
    }
  }
  obj_area <- vapply(runs, function(r) sum(r$e - r$s), numeric(1))
} else {
  obj_area <- cs_eval_det_box_area(box)
}

# %% Classes and areas
ref_classes <- sort(unique(labels_all[is_ref]), method = "radix")
classes <- if (AGNOSTIC) "(all classes)" else ref_classes
unknown <- sort(setdiff(unique(labels_all[!is_ref]), ref_classes), method = "radix")
known_pred <- !is_ref & labels_all %in% ref_classes
n_unk <- 0L
if (length(unknown)) {
  n_unk <- sum(!is_ref & !known_pred)
  shown <- paste0(paste(utils::head(unknown, 5), collapse = ", "), if (length(unknown) > 5) " …" else "")
  warnings <- c(warnings, sprintf("%d predicted boxes have a class the reference never uses (%s); they can't be scored and were left out.", n_unk, shown))
}
ref_area <- obj_area
if (!is.null(AREA)) {
  a_col <- as.numeric(df[[AREA]])
  ref_area <- ifelse(is.na(a_col), obj_area, a_col)
}
cat_all <- if (AGNOSTIC) rep(0L, nrow(df)) else { m <- match(labels_all, ref_classes) - 1L; m[is.na(m)] <- -1L; m }
gi <- which(is_ref)
di <- which(known_pred)
gt <- list(img = img_idx[gi], cat = cat_all[gi], box = box[gi, , drop = FALSE], area = ref_area[gi], crowd = crowd[gi],
           runs = if (!is.null(runs)) runs[gi] else NULL)
dt <- list(img = img_idx[di], cat = cat_all[di], box = box[di, , drop = FALSE], score = score_all[di], area = obj_area[di],
           runs = if (!is.null(runs)) runs[di] else NULL)

# %% COCO evaluation
max_dets <- c(1L, 10L, MAX_DETS)
ev <- cs_eval_det_evaluate(gt, dt, n_img, length(classes), IOU_TYPE, max_dets)
stats <- ev$stats
status <- ev$det_status  # per evaluated prediction at IoU 0.50: tp | fp | ignored | beyond
matched <- ev$det_match  # the reference it matched (0-based position in gt), -1 none
thr <- ev$thresholds
t50 <- which(thr == 0.5)[1]
nz <- function(v) if (is.null(v)) NA_real_ else v
n_ref_regular <- sum(!gt$crowd)
ref_hit <- logical(length(gi))
for (q in seq_along(di)) if (status[q] == "tp") ref_hit[matched[q] + 1L] <- TRUE
tp50 <- sum(status == "tp")
fp50 <- sum(status == "fp")
fn50 <- sum(!ref_hit & !gt$crowd)
per <- lapply(seq_along(classes), function(k) {
  pc <- cs_eval_det_per_class(ev$precision, ev$recall, thr, k)
  in_g <- gt$cat == k - 1L
  in_d <- dt$cat == k - 1L
  list(class = classes[k], n_ref = sum(in_g & !gt$crowd), n_crowd = sum(in_g & gt$crowd), n_pred = sum(in_d),
       ap = nz(pc$ap), ap50 = nz(pc$ap50), ap75 = nz(pc$ap75), ar = nz(pc$ar),
       tp = sum(in_d & status == "tp"), fp = sum(in_d & status == "fp"), fn = sum(in_g & !ref_hit & !gt$crowd))
})

# %% Assumptions
small <- vapply(Filter(function(p) p$n_ref < 10, per), function(p) p$class, character(1))
assumptions <- list(
  list(key = "complete", label = "Every object is labeled", status = "info",
       detail = "Predictions of objects that the reference doesn't list count as false positives."),
  list(key = "classes", label = "Predicted classes are in the reference", status = if (length(unknown)) "warn" else "pass",
       detail = if (length(unknown)) sprintf("%d predictions of %d unknown class(es) were left out.", n_unk, length(unknown)) else "Every predicted class appears in the reference."),
  list(key = "images", label = "Enough objects per class", status = if (length(small)) "warn" else "pass",
       detail = if (length(small)) sprintf("Fewer than 10 reference objects: %s%s.", paste(utils::head(small, 8), collapse = ", "), if (length(small) > 8) " …" else "") else "Every class has at least 10 reference objects.")
)

# %% Result
f3 <- function(v) if (is.null(v) || is.na(v)) "—" else sprintf("%.3f", v)
values <- list(n_images = n_img, n_classes = length(classes), n_reference = n_ref_regular, n_crowd = sum(gt$crowd),
               n_predictions = length(di), n_unknown_label = n_unk, iou_type = IOU_TYPE, max_dets = MAX_DETS,
               ap = nz(stats$ap), ap50 = nz(stats$ap50), ap75 = nz(stats$ap75), ap_small = nz(stats$ap_small),
               ap_medium = nz(stats$ap_medium), ap_large = nz(stats$ap_large), ar1 = nz(stats$ar_0), ar10 = nz(stats$ar_1),
               ar_max = nz(stats$ar_2), ar_small = nz(stats$ar_small), ar_medium = nz(stats$ar_medium), ar_large = nz(stats$ar_large),
               tp50 = tp50, fp50 = fp50, fn50 = fn50,
               precision50 = if (tp50 + fp50 > 0) tp50 / (tp50 + fp50) else NA_real_,
               recall50 = if (n_ref_regular > 0) tp50 / n_ref_regular else NA_real_)
for (p in per) for (key in c("ap", "ap50", "ap75", "ar")) values[[sprintf("%s[%s]", key, p$class)]] <- p[[key]]
sr <- list(list("AP", "0.50:0.95", "all", MAX_DETS, stats$ap), list("AP", "0.50", "all", MAX_DETS, stats$ap50),
           list("AP", "0.75", "all", MAX_DETS, stats$ap75), list("AP", "0.50:0.95", "small", MAX_DETS, stats$ap_small),
           list("AP", "0.50:0.95", "medium", MAX_DETS, stats$ap_medium), list("AP", "0.50:0.95", "large", MAX_DETS, stats$ap_large),
           list("AR", "0.50:0.95", "all", 1L, stats$ar_0), list("AR", "0.50:0.95", "all", 10L, stats$ar_1),
           list("AR", "0.50:0.95", "all", MAX_DETS, stats$ar_2), list("AR", "0.50:0.95", "small", MAX_DETS, stats$ar_small),
           list("AR", "0.50:0.95", "medium", MAX_DETS, stats$ar_medium), list("AR", "0.50:0.95", "large", MAX_DETS, stats$ar_large))
tables <- list(
  list(key = "coco", title = paste0("COCO summary", if (IOU_TYPE == "segm") " (masks)" else " (boxes)"),
       columns = list(list(key = "metric", label = "Metric", type = "string"), list(key = "iou", label = "IoU", type = "string"),
                      list(key = "area", label = "Object size", type = "string"), list(key = "max_dets", label = "Detections per image", type = "integer"),
                      list(key = "value", label = "Value", type = "number")),
       rows = lapply(sr, function(r) list(metric = r[[1]], iou = r[[2]], area = r[[3]], max_dets = r[[4]], value = nz(r[[5]]))),
       note = "Size groups use the reference area: small < 32², medium 32²–96², large > 96² pixels. Empty = no object of that size."),
  list(key = "classes", title = "Per class (IoU 0.50 counts with every image's top detections)",
       columns = list(list(key = "class", label = LABEL, type = "string"), list(key = "n_ref", label = "Reference objects", type = "integer"),
                      list(key = "n_crowd", label = "Crowd regions", type = "integer"), list(key = "n_pred", label = "Predictions", type = "integer"),
                      list(key = "ap", label = "AP", type = "number"), list(key = "ap50", label = "AP50", type = "number"),
                      list(key = "ap75", label = "AP75", type = "number"), list(key = "ar", label = sprintf("AR@%d", MAX_DETS), type = "number"),
                      list(key = "tp", label = "True positives", type = "integer"), list(key = "fp", label = "False positives", type = "integer"),
                      list(key = "fn", label = "Missed", type = "integer")),
       rows = per)
)
img_rows <- lapply(seq_len(n_img), function(i) {
  in_g <- gt$img == i - 1L
  in_d <- dt$img == i - 1L
  list(image = ik$media[i], frame = if (is.infinite(ik$frame[i])) NA_real_ else ik$frame[i], n_ref = sum(in_g & !gt$crowd),
       n_pred = sum(in_d), tp = sum(in_d & status == "tp"), fp = sum(in_d & status == "fp"), fn = sum(in_g & !ref_hit & !gt$crowd))
})
img_cols <- c(list(list(key = "image", label = IMG, type = "string")), if (!is.null(FRAME)) list(list(key = "frame", label = FRAME, type = "number")),
              list(list(key = "n_ref", label = "Reference objects", type = "integer"), list(key = "n_pred", label = "Predictions", type = "integer"),
                   list(key = "tp", label = "True positives", type = "integer"), list(key = "fp", label = "False positives", type = "integer"),
                   list(key = "fn", label = "Missed", type = "integer")))
tables[[length(tables) + 1L]] <- list(key = "images", title = "Per image at IoU 0.50", columns = img_cols, rows = utils::head(img_rows, 500),
                                      note = if (n_img > 500) "First 500 images." else NULL)
charts <- list()
rec <- ev$recall_points
m_last <- length(max_dets)
nref <- vapply(per, function(p) p$n_ref, numeric(1))
top <- utils::head(order(-nref, seq_along(per), method = "radix"), 8)
cr <- numeric(0); cp <- numeric(0); cc <- character(0)
for (k in top) {
  if (per[[k]]$n_ref == 0) next
  reach <- ev$recall[t50, k, 1, m_last]
  pk <- ev$precision[t50, , k, 1, m_last]
  sel <- rec <= reach
  cr <- c(cr, rec[sel]); cp <- c(cp, pk[sel]); cc <- c(cc, rep(per[[k]]$class, sum(sel)))
}
if (length(cr)) {
  shown <- vapply(Filter(function(k) per[[k]]$n_ref > 0, top), function(k) per[[k]]$class, character(1))
  charts[[length(charts) + 1L]] <- cs_chart("pr", "pr-curve", "Precision–recall at IoU 0.50, by class", list(
    recall = cs_col("Recall", cr, "numeric"), precision = cs_col("Precision (interpolated)", cp, "numeric"),
    curve = cs_col(LABEL, cc, "categorical", levels = shown)),
    note = paste0("COCO's interpolated precision at 101 recall points, up to the recall each class reaches.", if (length(per) > 8) " The 8 classes with the most reference objects." else ""))
}
dc <- character(0); dm <- character(0); dv <- numeric(0)
for (p in per) for (km in list(c("ap", "AP"), c("ap50", "AP50"), c("ap75", "AP75"))) if (!is.na(p[[km[1]]])) {
  dc <- c(dc, p$class); dm <- c(dm, km[2]); dv <- c(dv, p[[km[1]]])
}
if (length(dv)) {
  charts[[length(charts) + 1L]] <- cs_chart("ap-by-class", "cleveland-dot", "Average precision by class", list(
    category = cs_col(LABEL, dc, "categorical", levels = classes), value = cs_col("Average precision", dv, "numeric"),
    group = cs_col("Measure", dm, "categorical", levels = c("AP", "AP50", "AP75"))))
}
summary <- sprintf("Across %d images and %d class%s, AP (IoU 0.50:0.95) = %s, AP50 = %s and AP75 = %s; average recall with up to %d detections per image = %s. At IoU 0.50: %d true positives, %d false positives, %d missed objects.",
                   n_img, length(classes), if (length(classes) != 1) "es" else "", f3(stats$ap), f3(stats$ap50), f3(stats$ap75), MAX_DETS, f3(stats$ar_2), tp50, fp50, fn50)
cs_publish(list(
  method = "evaluate.detections",
  methodVersion = "1.1.0",
  title = "Object detection quality",
  engine = cs_engine_info("nanoparquet"),
  n = nrow(df),
  summary = summary,
  statistics = list(list(key = "ap", label = "AP (0.50:0.95)", value = nz(stats$ap)), list(key = "ap50", label = "AP50", value = nz(stats$ap50)),
                    list(key = "ap75", label = "AP75", value = nz(stats$ap75)), list(key = "ar_max", label = sprintf("AR@%d", MAX_DETS), value = nz(stats$ar_2))),
  tables = tables,
  assumptions = assumptions,
  warnings = warnings,
  notes = list(paste0(if (is.null(REF_ROLES)) sprintf("Reference rows: %s = %s; predictions: %s = %s. ", SOURCE, st$reference, SOURCE, st$prediction)
                      else "Reference rows come from the reference table; this table's rows are the predictions. ",
                      if (AGNOSTIC) "Classes ignored: any predicted box can match any reference box. " else "",
                      if (!is.null(CROWD)) sprintf("Crowd regions (%s) absorb overlapping predictions without counting them. ", CROWD) else "",
                      "COCO conventions: IoU 0.50:0.05:0.95, 101 recall points, greedy matching by score within each image and class.")),
  charts = charts,
  values = values
))
Python

Across 10 images and 3 classes, AP (IoU 0.50:0.95) = 0.456, AP50 = 0.540 and AP75 = 0.540; average recall with up to 20 detections per image = 0.515. At IoU 0.50: 16 true positives, 18 false positives, 11 missed objects.

AP (0.50:0.95)
0.4557
AP50
0.5402
AP75
0.5402
AR@20
0.5154

To keep this page light, the plots are shown once, under the R tab.

Assumptions

  • Every object is labeled — Predictions of objects that the reference doesn't list count as false positives.
  • Predicted classes are in the reference — 1 predictions of 1 unknown class(es) were left out.
  • Enough objects per class — Fewer than 10 reference objects: bicycle, car.

COCO summary (boxes)

MetricIoUObject sizeDetections per imageValue
AP0.50:0.95all200.4557
AP0.50all200.5402
AP0.75all200.5402
AP0.50:0.95small200.2785
AP0.50:0.95medium200.5325
AP0.50:0.95large200.6238
AR0.50:0.95all10.3814
AR0.50:0.95all100.5154
AR0.50:0.95all200.5154
AR0.50:0.95small200.3042
AR0.50:0.95medium200.5524
AR0.50:0.95large200.7889

Size groups use the reference area: small < 32², medium 32²–96², large > 96² pixels. Empty = no object of that size.

Per class (IoU 0.50 counts with every image's top detections)

labelReference objectsCrowd regionsPredictionsAPAP50AP75AR@20True positivesFalse positivesMissed
bicycle70100.33730.43230.43230.4714463
car9090.50070.55450.55450.5111544
person110150.52900.63370.63370.5636784

Per image at IoU 0.50

media_idReference objectsPredictionsTrue positivesFalse positivesMissed
img0122111
img0234310
img0367254
img0423121
img0547430
img0625230
img0723121
img0832201
img0901010
img1030003
  • 1 predicted boxes have a class the reference never uses (dog); they can't be scored and were left out.
  • Reference rows: source = annotation; predictions: source = prediction. COCO conventions: IoU 0.50:0.05:0.95, 101 recall points, greedy matching by score within each image and class.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Object detection quality (COCO average precision)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method evaluate.detections 1.1.0 · spec f62e80af7d49a7b5
# Dataset: img4_boxes (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
import numpy as np
import pandas as pd

import codesplash as cs
from codesplash.evaluate import detection as det  # twin: codesplashr cs_eval_det_*
from codesplash.evaluate.stacked import flags, image_keys, stacked  # twin: cs_eval_stacked
from codesplash.vision import boxes as vb  # COCO RLE strings (twin: cs_rle_*)

# %% Data
IMG = "media_id"
FRAME = None
X0, Y0, X1, Y1 = "x0", "y0", "x1", "y1"
LABEL, SCORE = "label", "score"
SOURCE = "source"
CROWD = None
AREA = None
MASK = None
WIDTH = None
HEIGHT = None
IOU_TYPE = "bbox"  # bbox | segm
MAX_DETS = int(20)
AGNOSTIC = False
REF_LEVEL = None
SOURCE_LEVELS = ["annotation", "prediction"]  # stored order
# Reference rows from a second table (option reference_table): its own column for each role, or None.
REF_ROLES = None
columns = list(dict.fromkeys(c for c in [IMG, FRAME, X0, Y0, X1, Y1, LABEL, SCORE, SOURCE, CROWD, AREA, MASK, WIDTH, HEIGHT] if c))
df = pd.read_parquet("tests/parity/fixtures/img4_boxes.parquet", columns=columns)
if IOU_TYPE == "segm" and not (MASK and WIDTH and HEIGHT):
    cs.cs_error("CS_E_INVALID_OPTION", option="Overlap measured on", allowed="Boxes unless the mask, width and height columns are set", value="Masks")
pre_warnings = []
if REF_ROLES is not None:
    # The reference table's rows go above this table's rows under an added source column (twin: cs_eval_with_reference).
    from codesplash.graph import dataset_option  # the table the host wrote for the option
    from codesplash.evaluate.stacked import with_reference
    w = with_reference(df, dataset_option("target/academy-parity/run-8142/evaluate.detections/boxes-plain-limit-20/out-python", "reference_table"),
                       {"image": IMG, "frame": FRAME, "x0": X0, "y0": Y0, "x1": X1, "y1": Y1, "label": LABEL, "score": SCORE,
                        "crowd": CROWD, "area": AREA, "mask": MASK, "width": WIDTH, "height": HEIGHT}, REF_ROLES,
                       {"frame": "Frame", **({"mask": "Mask", "width": "Image width", "height": "Image height"} if IOU_TYPE == "segm" else {})},
                       SOURCE, REF_LEVEL, ["image", "x0", "y0", "x1", "y1", "label"] + (["mask", "width", "height"] if IOU_TYPE == "segm" else []))
    df, pre_warnings, wc = w["df"], w["warnings"], w["columns"]
    IMG, FRAME, X0, Y0, X1, Y1 = wc["image"], wc["frame"], wc["x0"], wc["y0"], wc["x1"], wc["y1"]
    LABEL, CROWD, AREA, MASK, WIDTH, HEIGHT = wc["label"], wc["crowd"], wc["area"], wc["mask"], wc["width"], wc["height"]
    SOURCE, REF_LEVEL, SOURCE_LEVELS = w["source"], w["reference"], w["levels"]
elif SOURCE is None:
    cs.cs_error("CS_E_INVALID_OPTION", option="Reference table", allowed="a table of reference rows unless the Reference or prediction column is set", value="none")
needed = [IMG, X0, Y0, X1, Y1, LABEL, SOURCE] + ([MASK, WIDTH, HEIGHT] if IOU_TYPE == "segm" else [])
st = stacked(df, needed, [c for c in [X0, Y0, X1, Y1, SCORE, AREA, WIDTH, HEIGHT] if c], SOURCE, REF_LEVEL, SOURCE_LEVELS)
df, is_ref, warnings = st["df"], st["is_ref"], pre_warnings + st["warnings"]
score_all = df[SCORE].to_numpy(dtype=float, na_value=np.nan)
no_score = ~is_ref & np.isnan(score_all)
if no_score.any():
    warnings.append(f"{int(no_score.sum())} predicted boxes have no {SCORE} and were left out.")
    df, is_ref, score_all = df.loc[~no_score].reset_index(drop=True), is_ref[~no_score], score_all[~no_score]
box = df[[X0, Y0, X1, Y1]].to_numpy(dtype=float)
bad = (box[:, 2] < box[:, 0]) | (box[:, 3] < box[:, 1])
if bad.any():
    cs.cs_error("CS_E_INVALID_VALUES", column=f"{X1} and {Y1}", requirement=f"at least {X0} and {Y0}", count=int(bad.sum()))
if int(is_ref.sum()) == 0 or int((~is_ref).sum()) == 0:
    cs.cs_error("CS_E_GROUP_COUNT", column=SOURCE, expected=2, k=1)
crowd = flags(df[CROWD]) if CROWD else np.zeros(len(df), dtype=bool)
crowd[~is_ref] = False  # predictions are never crowd regions
img_idx, images = image_keys(df[IMG], df[FRAME] if FRAME else None)
labels_all = np.asarray([str(x) for x in df[LABEL].tolist()], dtype=object)

# %% Masks (COCO run-length strings, column-major)
runs = None
if IOU_TYPE == "segm":
    runs, n_bad = [], 0
    for s, w, h in zip(df[MASK].tolist(), df[WIDTH].to_numpy(dtype=float), df[HEIGHT].to_numpy(dtype=float)):
        try:
            runs.append(det.runs_from_counts(vb.string_to_counts(str(s)), int(h), int(w)))
        except (ValueError, OverflowError):
            runs.append(None)
            n_bad += 1
    if n_bad:
        cs.cs_error("CS_E_INVALID_VALUES", column=MASK, requirement="a COCO RLE string that covers width × height pixels", count=n_bad)
    sizes = {}
    for i, r in enumerate(runs):
        if sizes.setdefault(int(img_idx[i]), r[2]) != r[2]:
            cs.cs_error("CS_E_INVALID_VALUES", column=f"{WIDTH} and {HEIGHT}", requirement="the same size for every mask of an image", count=1)
    obj_area = np.asarray([det.runs_area(r) for r in runs])
else:
    obj_area = det.box_area(box)

# %% Classes and areas
ref_classes = sorted(set(labels_all[is_ref].tolist()))
classes = ["(all classes)"] if AGNOSTIC else ref_classes
cat_of = {c: i for i, c in enumerate(ref_classes)}
unknown = sorted(set(labels_all[~is_ref].tolist()) - set(ref_classes))
known_pred = ~is_ref & np.asarray([lab in cat_of for lab in labels_all])
if unknown:
    n_unk = int((~is_ref & ~known_pred).sum())
    shown = ", ".join(unknown[:5]) + (" …" if len(unknown) > 5 else "")
    warnings.append(f"{n_unk} predicted boxes have a class the reference never uses ({shown}); they can't be scored and were left out.")
else:
    n_unk = 0
ref_area = obj_area.copy()
if AREA:
    a_col = df[AREA].to_numpy(dtype=float, na_value=np.nan)
    ref_area = np.where(np.isnan(a_col), obj_area, a_col)
cat_all = np.asarray([0 if AGNOSTIC else cat_of.get(lab, -1) for lab in labels_all], dtype=int)
gi = np.flatnonzero(is_ref)
di = np.flatnonzero(known_pred)
gt = {"img": img_idx[gi], "cat": cat_all[gi], "box": box[gi], "area": ref_area[gi], "crowd": crowd[gi],
      "runs": [runs[j] for j in gi] if runs is not None else None}
dt = {"img": img_idx[di], "cat": cat_all[di], "box": box[di], "score": score_all[di], "area": obj_area[di],
      "runs": [runs[j] for j in di] if runs is not None else None}

# %% COCO evaluation
max_dets = (1, 10, MAX_DETS)
ev = det.evaluate(gt, dt, len(images), len(classes), IOU_TYPE, max_dets)
stats = ev["stats"]
status = ev["det_status"]   # per evaluated prediction at IoU 0.50: tp | fp | ignored | beyond
matched = ev["det_match"]   # the reference it matched (position in gt), −1 none
thr = ev["thresholds"]
t50 = int(np.flatnonzero(thr == 0.5)[0])
n_ref_regular = int((~gt["crowd"]).sum())
ref_hit = np.zeros(gi.size, dtype=bool)
for q in range(di.size):
    if status[q] == "tp":
        ref_hit[matched[q]] = True
tp50 = int(np.sum(status == "tp"))
fp50 = int(np.sum(status == "fp"))
fn50 = int(np.sum(~ref_hit & ~gt["crowd"]))
per = []
for k, c in enumerate(classes):
    pc = det.per_class(ev["precision"], ev["recall"], thr, k)
    in_g = gt["cat"] == k
    in_d = dt["cat"] == k
    per.append({"class": c, "n_ref": int(np.sum(in_g & ~gt["crowd"])), "n_crowd": int(np.sum(in_g & gt["crowd"])),
                "n_pred": int(np.sum(in_d)), "ap": pc["ap"], "ap50": pc["ap50"], "ap75": pc["ap75"], "ar": pc["ar"],
                "tp": int(np.sum(in_d & (status == "tp"))), "fp": int(np.sum(in_d & (status == "fp"))),
                "fn": int(np.sum(in_g & ~ref_hit & ~gt["crowd"]))})

# %% Assumptions
small = [p["class"] for p in per if p["n_ref"] < 10]
assumptions = [
    {"key": "complete", "label": "Every object is labeled", "status": "info",
     "detail": "Predictions of objects that the reference doesn't list count as false positives."},
    {"key": "classes", "label": "Predicted classes are in the reference", "status": "warn" if unknown else "pass",
     "detail": (f"{n_unk} predictions of {len(unknown)} unknown class(es) were left out." if unknown else "Every predicted class appears in the reference.")},
    {"key": "images", "label": "Enough objects per class", "status": "warn" if small else "pass",
     "detail": (f"Fewer than 10 reference objects: {', '.join(small[:8])}{' …' if len(small) > 8 else ''}." if small else "Every class has at least 10 reference objects.")},
]

# %% Result
f3 = lambda v: "—" if v is None else f"{v:.3f}"
values = {"n_images": len(images), "n_classes": len(classes), "n_reference": n_ref_regular, "n_crowd": int(gt["crowd"].sum()),
          "n_predictions": int(di.size), "n_unknown_label": n_unk, "iou_type": IOU_TYPE, "max_dets": MAX_DETS,
          "ap": stats["ap"], "ap50": stats["ap50"], "ap75": stats["ap75"], "ap_small": stats["ap_small"],
          "ap_medium": stats["ap_medium"], "ap_large": stats["ap_large"], "ar1": stats["ar_0"], "ar10": stats["ar_1"],
          "ar_max": stats["ar_2"], "ar_small": stats["ar_small"], "ar_medium": stats["ar_medium"], "ar_large": stats["ar_large"],
          "tp50": tp50, "fp50": fp50, "fn50": fn50,
          "precision50": tp50 / (tp50 + fp50) if (tp50 + fp50) else None,
          "recall50": tp50 / n_ref_regular if n_ref_regular else None}
for p in per:
    for key in ("ap", "ap50", "ap75", "ar"):
        values[f"{key}[{p['class']}]"] = p[key]
summary_rows = [
    ("AP", "0.50:0.95", "all", MAX_DETS, stats["ap"]), ("AP", "0.50", "all", MAX_DETS, stats["ap50"]),
    ("AP", "0.75", "all", MAX_DETS, stats["ap75"]), ("AP", "0.50:0.95", "small", MAX_DETS, stats["ap_small"]),
    ("AP", "0.50:0.95", "medium", MAX_DETS, stats["ap_medium"]), ("AP", "0.50:0.95", "large", MAX_DETS, stats["ap_large"]),
    ("AR", "0.50:0.95", "all", 1, stats["ar_0"]), ("AR", "0.50:0.95", "all", 10, stats["ar_1"]),
    ("AR", "0.50:0.95", "all", MAX_DETS, stats["ar_2"]), ("AR", "0.50:0.95", "small", MAX_DETS, stats["ar_small"]),
    ("AR", "0.50:0.95", "medium", MAX_DETS, stats["ar_medium"]), ("AR", "0.50:0.95", "large", MAX_DETS, stats["ar_large"]),
]
tables = [
    {"key": "coco", "title": "COCO summary" + (" (masks)" if IOU_TYPE == "segm" else " (boxes)"),
     "columns": [{"key": "metric", "label": "Metric", "type": "string"}, {"key": "iou", "label": "IoU", "type": "string"},
                 {"key": "area", "label": "Object size", "type": "string"}, {"key": "max_dets", "label": "Detections per image", "type": "integer"},
                 {"key": "value", "label": "Value", "type": "number"}],
     "rows": [{"metric": m, "iou": t, "area": a, "max_dets": d, "value": v} for m, t, a, d, v in summary_rows],
     "note": "Size groups use the reference area: small < 32², medium 32²–96², large > 96² pixels. Empty = no object of that size."},
    {"key": "classes", "title": "Per class (IoU 0.50 counts with every image's top detections)",
     "columns": [{"key": "class", "label": LABEL, "type": "string"}, {"key": "n_ref", "label": "Reference objects", "type": "integer"},
                 {"key": "n_crowd", "label": "Crowd regions", "type": "integer"}, {"key": "n_pred", "label": "Predictions", "type": "integer"},
                 {"key": "ap", "label": "AP", "type": "number"}, {"key": "ap50", "label": "AP50", "type": "number"},
                 {"key": "ap75", "label": "AP75", "type": "number"}, {"key": "ar", "label": f"AR@{MAX_DETS}", "type": "number"},
                 {"key": "tp", "label": "True positives", "type": "integer"}, {"key": "fp", "label": "False positives", "type": "integer"},
                 {"key": "fn", "label": "Missed", "type": "integer"}],
     "rows": per},
]
img_rows = []
for i, (m, f) in enumerate(images):
    in_g = gt["img"] == i
    in_d = dt["img"] == i
    img_rows.append({"image": m, "frame": None if f == float("-inf") else f, "n_ref": int(np.sum(in_g & ~gt["crowd"])),
                     "n_pred": int(np.sum(in_d)), "tp": int(np.sum(in_d & (status == "tp"))), "fp": int(np.sum(in_d & (status == "fp"))),
                     "fn": int(np.sum(in_g & ~ref_hit & ~gt["crowd"]))})
img_cols = [{"key": "image", "label": IMG, "type": "string"}] + ([{"key": "frame", "label": FRAME, "type": "number"}] if FRAME else []) + [
    {"key": "n_ref", "label": "Reference objects", "type": "integer"}, {"key": "n_pred", "label": "Predictions", "type": "integer"},
    {"key": "tp", "label": "True positives", "type": "integer"}, {"key": "fp", "label": "False positives", "type": "integer"},
    {"key": "fn", "label": "Missed", "type": "integer"}]
tables.append({"key": "images", "title": "Per image at IoU 0.50", "columns": img_cols, "rows": img_rows[:500],
               "note": "First 500 images." if len(img_rows) > 500 else None})
charts = []
rec = ev["recall_points"]
top = sorted(range(len(per)), key=lambda k: (-per[k]["n_ref"], k))[:8]
cr, cp, cc = [], [], []
for k in top:
    if per[k]["n_ref"] == 0:
        continue
    reach = ev["recall"][t50, k, 0, -1]
    for r, p in zip(rec, ev["precision"][t50, :, k, 0, -1]):
        if r <= reach:
            cr.append(float(r))
            cp.append(float(p))
            cc.append(per[k]["class"])
if cr:
    shown = [per[k]["class"] for k in top if per[k]["n_ref"] > 0]
    charts.append(cs.chart("pr", "pr-curve", "Precision–recall at IoU 0.50, by class", {
        "recall": cs.col("Recall", cr, "numeric"), "precision": cs.col("Precision (interpolated)", cp, "numeric"),
        "curve": cs.col(LABEL, cc, "categorical", levels=shown)},
        note="COCO's interpolated precision at 101 recall points, up to the recall each class reaches." + (" The 8 classes with the most reference objects." if len(per) > 8 else "")))
dots = [(p["class"], m, p[key]) for p in per for key, m in (("ap", "AP"), ("ap50", "AP50"), ("ap75", "AP75")) if p[key] is not None]
if dots:
    charts.append(cs.chart("ap-by-class", "cleveland-dot", "Average precision by class", {
        "category": cs.col(LABEL, [d[0] for d in dots], "categorical", levels=classes),
        "value": cs.col("Average precision", [d[2] for d in dots], "numeric"),
        "group": cs.col("Measure", [d[1] for d in dots], "categorical", levels=["AP", "AP50", "AP75"])}))
summary = (f"Across {len(images)} images and {len(classes)} class{'es' if len(classes) != 1 else ''}, AP (IoU 0.50:0.95) = {f3(stats['ap'])}, "
           f"AP50 = {f3(stats['ap50'])} and AP75 = {f3(stats['ap75'])}; average recall with up to {MAX_DETS} detections per image = {f3(stats['ar_2'])}. "
           f"At IoU 0.50: {tp50} true positives, {fp50} false positives, {fn50} missed objects.")
cs.publish({
    "method": "evaluate.detections",
    "methodVersion": "1.1.0",
    "title": "Object detection quality",
    "engine": cs.engine_info("pandas", "numpy"),
    "n": int(len(df)),
    "summary": summary,
    "statistics": [{"key": "ap", "label": "AP (0.50:0.95)", "value": stats["ap"]}, {"key": "ap50", "label": "AP50", "value": stats["ap50"]},
                   {"key": "ap75", "label": "AP75", "value": stats["ap75"]}, {"key": "ar_max", "label": f"AR@{MAX_DETS}", "value": stats["ar_2"]}],
    "tables": tables,
    "assumptions": assumptions,
    "warnings": warnings,
    "notes": [(f"Reference rows: {SOURCE} = {st['reference']}; predictions: {SOURCE} = {st['prediction']}. " if REF_ROLES is None
               else "Reference rows come from the reference table; this table's rows are the predictions. ")
              + ("Classes ignored: any predicted box can match any reference box. " if AGNOSTIC else "")
              + ("Crowd regions (" + CROWD + ") absorb overlapping predictions without counting them. " if CROWD else "")
              + "COCO conventions: IoU 0.50:0.05:0.95, 101 recall points, greedy matching by score within each image and class."],
    "charts": charts,
    "values": values,
})
04

Wrong class or wrong place?

Read

Ignoring classes asks a narrower question: did a box land on some object?

Object detection qualityRecorded · Python and R agreeRecorded 2026-11-25 · 29 values compared
R

Across 10 images and 1 class, AP (IoU 0.50:0.95) = 0.502, AP50 = 0.596 and AP75 = 0.596; average recall with up to 100 detections per image = 0.546. At IoU 0.50: 16 true positives, 16 false positives, 10 missed objects.

AP (0.50:0.95)
0.5017
AP50
0.5961
AP75
0.5961
AR@100
0.5462

Plots

Precision–recall at IoU 0.50, by classHow much precision does the model keep as it finds more of the positives?

COCO's interpolated precision at 101 recall points, up to the recall each class reaches.

View data
labelPrecision (interpolated)Recall
(all classes)10
(all classes)10.0100
(all classes)10.0200
(all classes)10.0300
(all classes)10.0400
(all classes)10.0500
(all classes)10.0600
(all classes)10.0700
(all classes)10.0800
(all classes)10.0900
(all classes)10.1000
(all classes)10.1100
(all classes)10.1200
(all classes)10.1300
(all classes)10.1400
(all classes)10.1500
(all classes)10.1600
(all classes)10.1700
(all classes)10.1800
(all classes)10.1900
(all classes)10.2000
(all classes)10.2100
(all classes)10.2200
(all classes)10.2300
(all classes)10.2400
(all classes)10.2500
(all classes)10.2600
(all classes)10.2700
(all classes)10.2800
(all classes)10.2900
(all classes)10.3000
(all classes)10.3100
(all classes)10.3200
(all classes)10.3300
(all classes)10.3400
(all classes)10.3500
(all classes)10.3600
(all classes)10.3700
(all classes)10.3800
(all classes)10.3900
(all classes)10.4000
(all classes)10.4100
(all classes)10.4200
(all classes)0.92860.4300
(all classes)0.92860.4400
(all classes)0.92860.4500
(all classes)0.92860.4600
(all classes)0.92860.4700
(all classes)0.92860.4800
(all classes)0.92860.4900
(all classes)0.92860.5000
(all classes)0.88890.5100
(all classes)0.88890.5200
(all classes)0.88890.5300
(all classes)0.88890.5400
(all classes)0.88890.5500
(all classes)0.88890.5600
(all classes)0.88890.5700
(all classes)0.88890.5800
(all classes)0.88890.5900

First 60 of 62 rows.

Average precision by classHow do categories compare on one value — and across up to three groups?
View data
labelMeasureAverage precision
(all classes)AP0.5017
(all classes)AP500.5961
(all classes)AP750.5961

Assumptions

  • Every object is labeled — Predictions of objects that the reference doesn't list count as false positives.
  • Predicted classes are in the reference — 1 predictions of 1 unknown class(es) were left out.
  • Enough objects per class — Every class has at least 10 reference objects.

COCO summary (boxes)

MetricIoUObject sizeDetections per imageValue
AP0.50:0.95all1000.5017
AP0.50all1000.5961
AP0.75all1000.5961
AP0.50:0.95small1000.2812
AP0.50:0.95medium1000.6265
AP0.50:0.95large1000.5517
AR0.50:0.95all10.2769
AR0.50:0.95all100.5462
AR0.50:0.95all1000.5462
AR0.50:0.95small1000.3143
AR0.50:0.95medium1000.6545
AR0.50:0.95large1000.6000

Size groups use the reference area: small < 32², medium 32²–96², large > 96² pixels. Empty = no object of that size.

Per class (IoU 0.50 counts with every image's top detections)

labelReference objectsCrowd regionsPredictionsAPAP50AP75AR@100True positivesFalse positivesMissed
(all classes)261340.50170.59610.59610.5462161610

Per image at IoU 0.50

media_idReference objectsPredictionsTrue positivesFalse positivesMissed
img0122111
img0234310
img0357233
img0423121
img0547430
img0625230
img0723121
img0832201
img0901010
img1030003
  • 1 predicted boxes have a class the reference never uses (dog); they can't be scored and were left out.
  • Reference rows: source = annotation; predictions: source = prediction. Classes ignored: any predicted box can match any reference box. Crowd regions (iscrowd) absorb overlapping predictions without counting them. COCO conventions: IoU 0.50:0.05:0.95, 101 recall points, greedy matching by score within each image and class.
The exact R script · R R version 4.5.1 (2025-06-13)
# Object detection quality (COCO average precision)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method evaluate.detections 1.1.0 · spec ec9dd0ccd16d42f1
# Dataset: img4_boxes (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr)  # cs_eval_det_* (COCO evaluation), cs_eval_stacked, cs_rle_* (COCO RLE strings)

# %% Data
IMG <- "media_id"
FRAME <- NULL
X0 <- "x0"; Y0 <- "y0"; X1 <- "x1"; Y1 <- "y1"
LABEL <- "label"; SCORE <- "score"
SOURCE <- "source"
CROWD <- "iscrowd"
AREA <- NULL
MASK <- NULL
WIDTH <- NULL
HEIGHT <- NULL
IOU_TYPE <- "bbox"  # bbox | segm
MAX_DETS <- as.integer(100)
AGNOSTIC <- TRUE
REF_LEVEL <- NULL
SOURCE_LEVELS <- c("annotation", "prediction")  # stored order
# Reference rows from a second table (option reference_table): its own column for each role, or NULL.
REF_ROLES <- NULL
columns <- unique(c(IMG, FRAME, X0, Y0, X1, Y1, LABEL, SCORE, SOURCE, CROWD, AREA, MASK, WIDTH, HEIGHT))
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/img4_boxes.parquet", col_select = columns))
if (IOU_TYPE == "segm" && (is.null(MASK) || is.null(WIDTH) || is.null(HEIGHT))) {
  cs_error("CS_E_INVALID_OPTION", option = "Overlap measured on", allowed = "Boxes unless the mask, width and height columns are set", value = "Masks")
}
pre_warnings <- list()
if (!is.null(REF_ROLES)) {
  # The reference table's rows go above this table's rows under an added source column (twin: with_reference).
  w <- cs_eval_with_reference(df, cs_graph_dataset_option("target/academy-parity/run-8142/evaluate.detections/class-agnostic/out-r", "reference_table"),
                              list(image = IMG, frame = FRAME, x0 = X0, y0 = Y0, x1 = X1, y1 = Y1, label = LABEL, score = SCORE,
                                   crowd = CROWD, area = AREA, mask = MASK, width = WIDTH, height = HEIGHT), REF_ROLES,
                              c(list(frame = "Frame"), if (IOU_TYPE == "segm") list(mask = "Mask", width = "Image width", height = "Image height")),
                              SOURCE, REF_LEVEL, c("image", "x0", "y0", "x1", "y1", "label", if (IOU_TYPE == "segm") c("mask", "width", "height")))
  df <- w$df
  pre_warnings <- w$warnings
  wc <- w$columns
  IMG <- wc$image; FRAME <- wc$frame; X0 <- wc$x0; Y0 <- wc$y0; X1 <- wc$x1; Y1 <- wc$y1
  LABEL <- wc$label; CROWD <- wc$crowd; AREA <- wc$area; MASK <- wc$mask; WIDTH <- wc$width; HEIGHT <- wc$height
  SOURCE <- w$source; REF_LEVEL <- w$reference; SOURCE_LEVELS <- w$levels
} else if (is.null(SOURCE)) {
  cs_error("CS_E_INVALID_OPTION", option = "Reference table", allowed = "a table of reference rows unless the Reference or prediction column is set", value = "none")
}
needed <- c(IMG, X0, Y0, X1, Y1, LABEL, SOURCE, if (IOU_TYPE == "segm") c(MASK, WIDTH, HEIGHT))
st <- cs_eval_stacked(df, needed, c(X0, Y0, X1, Y1, SCORE, AREA, WIDTH, HEIGHT), SOURCE, REF_LEVEL, SOURCE_LEVELS)
df <- st$df
is_ref <- st$is_ref
warnings <- c(pre_warnings, st$warnings)
score_all <- as.numeric(df[[SCORE]])
no_score <- !is_ref & is.na(score_all)
if (any(no_score)) {
  warnings <- c(warnings, sprintf("%d predicted boxes have no %s and were left out.", sum(no_score), SCORE))
  df <- df[!no_score, , drop = FALSE]
  is_ref <- is_ref[!no_score]
  score_all <- score_all[!no_score]
}
box <- cbind(as.numeric(df[[X0]]), as.numeric(df[[Y0]]), as.numeric(df[[X1]]), as.numeric(df[[Y1]]))
bad <- (box[, 3] < box[, 1]) | (box[, 4] < box[, 2])
if (any(bad)) cs_error("CS_E_INVALID_VALUES", column = sprintf("%s and %s", X1, Y1), requirement = sprintf("at least %s and %s", X0, Y0), count = sum(bad))
if (sum(is_ref) == 0L || sum(!is_ref) == 0L) cs_error("CS_E_GROUP_COUNT", column = SOURCE, expected = 2, k = 1)
crowd <- if (!is.null(CROWD)) cs_eval_flags(df[[CROWD]]) else logical(nrow(df))
crowd[!is_ref] <- FALSE  # predictions are never crowd regions
ik <- cs_eval_image_keys(df[[IMG]], if (!is.null(FRAME)) df[[FRAME]] else NULL)
img_idx <- ik$index
n_img <- length(ik$media)
labels_all <- as.character(df[[LABEL]])

# %% Masks (COCO run-length strings, column-major)
runs <- NULL
if (IOU_TYPE == "segm") {
  n_bad <- 0L
  ws <- as.numeric(df[[WIDTH]])
  hs <- as.numeric(df[[HEIGHT]])
  runs <- lapply(seq_len(nrow(df)), function(i) {
    tryCatch(cs_eval_det_runs(cs_rle_string_to_counts(as.character(df[[MASK]][i])), as.integer(hs[i]), as.integer(ws[i])),
             error = function(e) NULL)
  })
  n_bad <- sum(vapply(runs, is.null, logical(1)))
  if (n_bad > 0) cs_error("CS_E_INVALID_VALUES", column = MASK, requirement = "a COCO RLE string that covers width × height pixels", count = n_bad)
  sizes <- list()
  for (i in seq_along(runs)) {
    key <- as.character(img_idx[i])
    if (is.null(sizes[[key]])) sizes[[key]] <- runs[[i]]$size
    if (!identical(sizes[[key]], runs[[i]]$size)) {
      cs_error("CS_E_INVALID_VALUES", column = sprintf("%s and %s", WIDTH, HEIGHT), requirement = "the same size for every mask of an image", count = 1)
    }
  }
  obj_area <- vapply(runs, function(r) sum(r$e - r$s), numeric(1))
} else {
  obj_area <- cs_eval_det_box_area(box)
}

# %% Classes and areas
ref_classes <- sort(unique(labels_all[is_ref]), method = "radix")
classes <- if (AGNOSTIC) "(all classes)" else ref_classes
unknown <- sort(setdiff(unique(labels_all[!is_ref]), ref_classes), method = "radix")
known_pred <- !is_ref & labels_all %in% ref_classes
n_unk <- 0L
if (length(unknown)) {
  n_unk <- sum(!is_ref & !known_pred)
  shown <- paste0(paste(utils::head(unknown, 5), collapse = ", "), if (length(unknown) > 5) " …" else "")
  warnings <- c(warnings, sprintf("%d predicted boxes have a class the reference never uses (%s); they can't be scored and were left out.", n_unk, shown))
}
ref_area <- obj_area
if (!is.null(AREA)) {
  a_col <- as.numeric(df[[AREA]])
  ref_area <- ifelse(is.na(a_col), obj_area, a_col)
}
cat_all <- if (AGNOSTIC) rep(0L, nrow(df)) else { m <- match(labels_all, ref_classes) - 1L; m[is.na(m)] <- -1L; m }
gi <- which(is_ref)
di <- which(known_pred)
gt <- list(img = img_idx[gi], cat = cat_all[gi], box = box[gi, , drop = FALSE], area = ref_area[gi], crowd = crowd[gi],
           runs = if (!is.null(runs)) runs[gi] else NULL)
dt <- list(img = img_idx[di], cat = cat_all[di], box = box[di, , drop = FALSE], score = score_all[di], area = obj_area[di],
           runs = if (!is.null(runs)) runs[di] else NULL)

# %% COCO evaluation
max_dets <- c(1L, 10L, MAX_DETS)
ev <- cs_eval_det_evaluate(gt, dt, n_img, length(classes), IOU_TYPE, max_dets)
stats <- ev$stats
status <- ev$det_status  # per evaluated prediction at IoU 0.50: tp | fp | ignored | beyond
matched <- ev$det_match  # the reference it matched (0-based position in gt), -1 none
thr <- ev$thresholds
t50 <- which(thr == 0.5)[1]
nz <- function(v) if (is.null(v)) NA_real_ else v
n_ref_regular <- sum(!gt$crowd)
ref_hit <- logical(length(gi))
for (q in seq_along(di)) if (status[q] == "tp") ref_hit[matched[q] + 1L] <- TRUE
tp50 <- sum(status == "tp")
fp50 <- sum(status == "fp")
fn50 <- sum(!ref_hit & !gt$crowd)
per <- lapply(seq_along(classes), function(k) {
  pc <- cs_eval_det_per_class(ev$precision, ev$recall, thr, k)
  in_g <- gt$cat == k - 1L
  in_d <- dt$cat == k - 1L
  list(class = classes[k], n_ref = sum(in_g & !gt$crowd), n_crowd = sum(in_g & gt$crowd), n_pred = sum(in_d),
       ap = nz(pc$ap), ap50 = nz(pc$ap50), ap75 = nz(pc$ap75), ar = nz(pc$ar),
       tp = sum(in_d & status == "tp"), fp = sum(in_d & status == "fp"), fn = sum(in_g & !ref_hit & !gt$crowd))
})

# %% Assumptions
small <- vapply(Filter(function(p) p$n_ref < 10, per), function(p) p$class, character(1))
assumptions <- list(
  list(key = "complete", label = "Every object is labeled", status = "info",
       detail = "Predictions of objects that the reference doesn't list count as false positives."),
  list(key = "classes", label = "Predicted classes are in the reference", status = if (length(unknown)) "warn" else "pass",
       detail = if (length(unknown)) sprintf("%d predictions of %d unknown class(es) were left out.", n_unk, length(unknown)) else "Every predicted class appears in the reference."),
  list(key = "images", label = "Enough objects per class", status = if (length(small)) "warn" else "pass",
       detail = if (length(small)) sprintf("Fewer than 10 reference objects: %s%s.", paste(utils::head(small, 8), collapse = ", "), if (length(small) > 8) " …" else "") else "Every class has at least 10 reference objects.")
)

# %% Result
f3 <- function(v) if (is.null(v) || is.na(v)) "—" else sprintf("%.3f", v)
values <- list(n_images = n_img, n_classes = length(classes), n_reference = n_ref_regular, n_crowd = sum(gt$crowd),
               n_predictions = length(di), n_unknown_label = n_unk, iou_type = IOU_TYPE, max_dets = MAX_DETS,
               ap = nz(stats$ap), ap50 = nz(stats$ap50), ap75 = nz(stats$ap75), ap_small = nz(stats$ap_small),
               ap_medium = nz(stats$ap_medium), ap_large = nz(stats$ap_large), ar1 = nz(stats$ar_0), ar10 = nz(stats$ar_1),
               ar_max = nz(stats$ar_2), ar_small = nz(stats$ar_small), ar_medium = nz(stats$ar_medium), ar_large = nz(stats$ar_large),
               tp50 = tp50, fp50 = fp50, fn50 = fn50,
               precision50 = if (tp50 + fp50 > 0) tp50 / (tp50 + fp50) else NA_real_,
               recall50 = if (n_ref_regular > 0) tp50 / n_ref_regular else NA_real_)
for (p in per) for (key in c("ap", "ap50", "ap75", "ar")) values[[sprintf("%s[%s]", key, p$class)]] <- p[[key]]
sr <- list(list("AP", "0.50:0.95", "all", MAX_DETS, stats$ap), list("AP", "0.50", "all", MAX_DETS, stats$ap50),
           list("AP", "0.75", "all", MAX_DETS, stats$ap75), list("AP", "0.50:0.95", "small", MAX_DETS, stats$ap_small),
           list("AP", "0.50:0.95", "medium", MAX_DETS, stats$ap_medium), list("AP", "0.50:0.95", "large", MAX_DETS, stats$ap_large),
           list("AR", "0.50:0.95", "all", 1L, stats$ar_0), list("AR", "0.50:0.95", "all", 10L, stats$ar_1),
           list("AR", "0.50:0.95", "all", MAX_DETS, stats$ar_2), list("AR", "0.50:0.95", "small", MAX_DETS, stats$ar_small),
           list("AR", "0.50:0.95", "medium", MAX_DETS, stats$ar_medium), list("AR", "0.50:0.95", "large", MAX_DETS, stats$ar_large))
tables <- list(
  list(key = "coco", title = paste0("COCO summary", if (IOU_TYPE == "segm") " (masks)" else " (boxes)"),
       columns = list(list(key = "metric", label = "Metric", type = "string"), list(key = "iou", label = "IoU", type = "string"),
                      list(key = "area", label = "Object size", type = "string"), list(key = "max_dets", label = "Detections per image", type = "integer"),
                      list(key = "value", label = "Value", type = "number")),
       rows = lapply(sr, function(r) list(metric = r[[1]], iou = r[[2]], area = r[[3]], max_dets = r[[4]], value = nz(r[[5]]))),
       note = "Size groups use the reference area: small < 32², medium 32²–96², large > 96² pixels. Empty = no object of that size."),
  list(key = "classes", title = "Per class (IoU 0.50 counts with every image's top detections)",
       columns = list(list(key = "class", label = LABEL, type = "string"), list(key = "n_ref", label = "Reference objects", type = "integer"),
                      list(key = "n_crowd", label = "Crowd regions", type = "integer"), list(key = "n_pred", label = "Predictions", type = "integer"),
                      list(key = "ap", label = "AP", type = "number"), list(key = "ap50", label = "AP50", type = "number"),
                      list(key = "ap75", label = "AP75", type = "number"), list(key = "ar", label = sprintf("AR@%d", MAX_DETS), type = "number"),
                      list(key = "tp", label = "True positives", type = "integer"), list(key = "fp", label = "False positives", type = "integer"),
                      list(key = "fn", label = "Missed", type = "integer")),
       rows = per)
)
img_rows <- lapply(seq_len(n_img), function(i) {
  in_g <- gt$img == i - 1L
  in_d <- dt$img == i - 1L
  list(image = ik$media[i], frame = if (is.infinite(ik$frame[i])) NA_real_ else ik$frame[i], n_ref = sum(in_g & !gt$crowd),
       n_pred = sum(in_d), tp = sum(in_d & status == "tp"), fp = sum(in_d & status == "fp"), fn = sum(in_g & !ref_hit & !gt$crowd))
})
img_cols <- c(list(list(key = "image", label = IMG, type = "string")), if (!is.null(FRAME)) list(list(key = "frame", label = FRAME, type = "number")),
              list(list(key = "n_ref", label = "Reference objects", type = "integer"), list(key = "n_pred", label = "Predictions", type = "integer"),
                   list(key = "tp", label = "True positives", type = "integer"), list(key = "fp", label = "False positives", type = "integer"),
                   list(key = "fn", label = "Missed", type = "integer")))
tables[[length(tables) + 1L]] <- list(key = "images", title = "Per image at IoU 0.50", columns = img_cols, rows = utils::head(img_rows, 500),
                                      note = if (n_img > 500) "First 500 images." else NULL)
charts <- list()
rec <- ev$recall_points
m_last <- length(max_dets)
nref <- vapply(per, function(p) p$n_ref, numeric(1))
top <- utils::head(order(-nref, seq_along(per), method = "radix"), 8)
cr <- numeric(0); cp <- numeric(0); cc <- character(0)
for (k in top) {
  if (per[[k]]$n_ref == 0) next
  reach <- ev$recall[t50, k, 1, m_last]
  pk <- ev$precision[t50, , k, 1, m_last]
  sel <- rec <= reach
  cr <- c(cr, rec[sel]); cp <- c(cp, pk[sel]); cc <- c(cc, rep(per[[k]]$class, sum(sel)))
}
if (length(cr)) {
  shown <- vapply(Filter(function(k) per[[k]]$n_ref > 0, top), function(k) per[[k]]$class, character(1))
  charts[[length(charts) + 1L]] <- cs_chart("pr", "pr-curve", "Precision–recall at IoU 0.50, by class", list(
    recall = cs_col("Recall", cr, "numeric"), precision = cs_col("Precision (interpolated)", cp, "numeric"),
    curve = cs_col(LABEL, cc, "categorical", levels = shown)),
    note = paste0("COCO's interpolated precision at 101 recall points, up to the recall each class reaches.", if (length(per) > 8) " The 8 classes with the most reference objects." else ""))
}
dc <- character(0); dm <- character(0); dv <- numeric(0)
for (p in per) for (km in list(c("ap", "AP"), c("ap50", "AP50"), c("ap75", "AP75"))) if (!is.na(p[[km[1]]])) {
  dc <- c(dc, p$class); dm <- c(dm, km[2]); dv <- c(dv, p[[km[1]]])
}
if (length(dv)) {
  charts[[length(charts) + 1L]] <- cs_chart("ap-by-class", "cleveland-dot", "Average precision by class", list(
    category = cs_col(LABEL, dc, "categorical", levels = classes), value = cs_col("Average precision", dv, "numeric"),
    group = cs_col("Measure", dm, "categorical", levels = c("AP", "AP50", "AP75"))))
}
summary <- sprintf("Across %d images and %d class%s, AP (IoU 0.50:0.95) = %s, AP50 = %s and AP75 = %s; average recall with up to %d detections per image = %s. At IoU 0.50: %d true positives, %d false positives, %d missed objects.",
                   n_img, length(classes), if (length(classes) != 1) "es" else "", f3(stats$ap), f3(stats$ap50), f3(stats$ap75), MAX_DETS, f3(stats$ar_2), tp50, fp50, fn50)
cs_publish(list(
  method = "evaluate.detections",
  methodVersion = "1.1.0",
  title = "Object detection quality",
  engine = cs_engine_info("nanoparquet"),
  n = nrow(df),
  summary = summary,
  statistics = list(list(key = "ap", label = "AP (0.50:0.95)", value = nz(stats$ap)), list(key = "ap50", label = "AP50", value = nz(stats$ap50)),
                    list(key = "ap75", label = "AP75", value = nz(stats$ap75)), list(key = "ar_max", label = sprintf("AR@%d", MAX_DETS), value = nz(stats$ar_2))),
  tables = tables,
  assumptions = assumptions,
  warnings = warnings,
  notes = list(paste0(if (is.null(REF_ROLES)) sprintf("Reference rows: %s = %s; predictions: %s = %s. ", SOURCE, st$reference, SOURCE, st$prediction)
                      else "Reference rows come from the reference table; this table's rows are the predictions. ",
                      if (AGNOSTIC) "Classes ignored: any predicted box can match any reference box. " else "",
                      if (!is.null(CROWD)) sprintf("Crowd regions (%s) absorb overlapping predictions without counting them. ", CROWD) else "",
                      "COCO conventions: IoU 0.50:0.05:0.95, 101 recall points, greedy matching by score within each image and class.")),
  charts = charts,
  values = values
))
Python

Across 10 images and 1 class, AP (IoU 0.50:0.95) = 0.502, AP50 = 0.596 and AP75 = 0.596; average recall with up to 100 detections per image = 0.546. At IoU 0.50: 16 true positives, 16 false positives, 10 missed objects.

AP (0.50:0.95)
0.5017
AP50
0.5961
AP75
0.5961
AR@100
0.5462

To keep this page light, the plots are shown once, under the R tab.

Assumptions

  • Every object is labeled — Predictions of objects that the reference doesn't list count as false positives.
  • Predicted classes are in the reference — 1 predictions of 1 unknown class(es) were left out.
  • Enough objects per class — Every class has at least 10 reference objects.

COCO summary (boxes)

MetricIoUObject sizeDetections per imageValue
AP0.50:0.95all1000.5017
AP0.50all1000.5961
AP0.75all1000.5961
AP0.50:0.95small1000.2812
AP0.50:0.95medium1000.6265
AP0.50:0.95large1000.5517
AR0.50:0.95all10.2769
AR0.50:0.95all100.5462
AR0.50:0.95all1000.5462
AR0.50:0.95small1000.3143
AR0.50:0.95medium1000.6545
AR0.50:0.95large1000.6000

Size groups use the reference area: small < 32², medium 32²–96², large > 96² pixels. Empty = no object of that size.

Per class (IoU 0.50 counts with every image's top detections)

labelReference objectsCrowd regionsPredictionsAPAP50AP75AR@100True positivesFalse positivesMissed
(all classes)261340.50170.59610.59610.5462161610

Per image at IoU 0.50

media_idReference objectsPredictionsTrue positivesFalse positivesMissed
img0122111
img0234310
img0357233
img0423121
img0547430
img0625230
img0723121
img0832201
img0901010
img1030003
  • 1 predicted boxes have a class the reference never uses (dog); they can't be scored and were left out.
  • Reference rows: source = annotation; predictions: source = prediction. Classes ignored: any predicted box can match any reference box. Crowd regions (iscrowd) absorb overlapping predictions without counting them. COCO conventions: IoU 0.50:0.05:0.95, 101 recall points, greedy matching by score within each image and class.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Object detection quality (COCO average precision)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method evaluate.detections 1.1.0 · spec ec9dd0ccd16d42f1
# Dataset: img4_boxes (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
import numpy as np
import pandas as pd

import codesplash as cs
from codesplash.evaluate import detection as det  # twin: codesplashr cs_eval_det_*
from codesplash.evaluate.stacked import flags, image_keys, stacked  # twin: cs_eval_stacked
from codesplash.vision import boxes as vb  # COCO RLE strings (twin: cs_rle_*)

# %% Data
IMG = "media_id"
FRAME = None
X0, Y0, X1, Y1 = "x0", "y0", "x1", "y1"
LABEL, SCORE = "label", "score"
SOURCE = "source"
CROWD = "iscrowd"
AREA = None
MASK = None
WIDTH = None
HEIGHT = None
IOU_TYPE = "bbox"  # bbox | segm
MAX_DETS = int(100)
AGNOSTIC = True
REF_LEVEL = None
SOURCE_LEVELS = ["annotation", "prediction"]  # stored order
# Reference rows from a second table (option reference_table): its own column for each role, or None.
REF_ROLES = None
columns = list(dict.fromkeys(c for c in [IMG, FRAME, X0, Y0, X1, Y1, LABEL, SCORE, SOURCE, CROWD, AREA, MASK, WIDTH, HEIGHT] if c))
df = pd.read_parquet("tests/parity/fixtures/img4_boxes.parquet", columns=columns)
if IOU_TYPE == "segm" and not (MASK and WIDTH and HEIGHT):
    cs.cs_error("CS_E_INVALID_OPTION", option="Overlap measured on", allowed="Boxes unless the mask, width and height columns are set", value="Masks")
pre_warnings = []
if REF_ROLES is not None:
    # The reference table's rows go above this table's rows under an added source column (twin: cs_eval_with_reference).
    from codesplash.graph import dataset_option  # the table the host wrote for the option
    from codesplash.evaluate.stacked import with_reference
    w = with_reference(df, dataset_option("target/academy-parity/run-8142/evaluate.detections/class-agnostic/out-python", "reference_table"),
                       {"image": IMG, "frame": FRAME, "x0": X0, "y0": Y0, "x1": X1, "y1": Y1, "label": LABEL, "score": SCORE,
                        "crowd": CROWD, "area": AREA, "mask": MASK, "width": WIDTH, "height": HEIGHT}, REF_ROLES,
                       {"frame": "Frame", **({"mask": "Mask", "width": "Image width", "height": "Image height"} if IOU_TYPE == "segm" else {})},
                       SOURCE, REF_LEVEL, ["image", "x0", "y0", "x1", "y1", "label"] + (["mask", "width", "height"] if IOU_TYPE == "segm" else []))
    df, pre_warnings, wc = w["df"], w["warnings"], w["columns"]
    IMG, FRAME, X0, Y0, X1, Y1 = wc["image"], wc["frame"], wc["x0"], wc["y0"], wc["x1"], wc["y1"]
    LABEL, CROWD, AREA, MASK, WIDTH, HEIGHT = wc["label"], wc["crowd"], wc["area"], wc["mask"], wc["width"], wc["height"]
    SOURCE, REF_LEVEL, SOURCE_LEVELS = w["source"], w["reference"], w["levels"]
elif SOURCE is None:
    cs.cs_error("CS_E_INVALID_OPTION", option="Reference table", allowed="a table of reference rows unless the Reference or prediction column is set", value="none")
needed = [IMG, X0, Y0, X1, Y1, LABEL, SOURCE] + ([MASK, WIDTH, HEIGHT] if IOU_TYPE == "segm" else [])
st = stacked(df, needed, [c for c in [X0, Y0, X1, Y1, SCORE, AREA, WIDTH, HEIGHT] if c], SOURCE, REF_LEVEL, SOURCE_LEVELS)
df, is_ref, warnings = st["df"], st["is_ref"], pre_warnings + st["warnings"]
score_all = df[SCORE].to_numpy(dtype=float, na_value=np.nan)
no_score = ~is_ref & np.isnan(score_all)
if no_score.any():
    warnings.append(f"{int(no_score.sum())} predicted boxes have no {SCORE} and were left out.")
    df, is_ref, score_all = df.loc[~no_score].reset_index(drop=True), is_ref[~no_score], score_all[~no_score]
box = df[[X0, Y0, X1, Y1]].to_numpy(dtype=float)
bad = (box[:, 2] < box[:, 0]) | (box[:, 3] < box[:, 1])
if bad.any():
    cs.cs_error("CS_E_INVALID_VALUES", column=f"{X1} and {Y1}", requirement=f"at least {X0} and {Y0}", count=int(bad.sum()))
if int(is_ref.sum()) == 0 or int((~is_ref).sum()) == 0:
    cs.cs_error("CS_E_GROUP_COUNT", column=SOURCE, expected=2, k=1)
crowd = flags(df[CROWD]) if CROWD else np.zeros(len(df), dtype=bool)
crowd[~is_ref] = False  # predictions are never crowd regions
img_idx, images = image_keys(df[IMG], df[FRAME] if FRAME else None)
labels_all = np.asarray([str(x) for x in df[LABEL].tolist()], dtype=object)

# %% Masks (COCO run-length strings, column-major)
runs = None
if IOU_TYPE == "segm":
    runs, n_bad = [], 0
    for s, w, h in zip(df[MASK].tolist(), df[WIDTH].to_numpy(dtype=float), df[HEIGHT].to_numpy(dtype=float)):
        try:
            runs.append(det.runs_from_counts(vb.string_to_counts(str(s)), int(h), int(w)))
        except (ValueError, OverflowError):
            runs.append(None)
            n_bad += 1
    if n_bad:
        cs.cs_error("CS_E_INVALID_VALUES", column=MASK, requirement="a COCO RLE string that covers width × height pixels", count=n_bad)
    sizes = {}
    for i, r in enumerate(runs):
        if sizes.setdefault(int(img_idx[i]), r[2]) != r[2]:
            cs.cs_error("CS_E_INVALID_VALUES", column=f"{WIDTH} and {HEIGHT}", requirement="the same size for every mask of an image", count=1)
    obj_area = np.asarray([det.runs_area(r) for r in runs])
else:
    obj_area = det.box_area(box)

# %% Classes and areas
ref_classes = sorted(set(labels_all[is_ref].tolist()))
classes = ["(all classes)"] if AGNOSTIC else ref_classes
cat_of = {c: i for i, c in enumerate(ref_classes)}
unknown = sorted(set(labels_all[~is_ref].tolist()) - set(ref_classes))
known_pred = ~is_ref & np.asarray([lab in cat_of for lab in labels_all])
if unknown:
    n_unk = int((~is_ref & ~known_pred).sum())
    shown = ", ".join(unknown[:5]) + (" …" if len(unknown) > 5 else "")
    warnings.append(f"{n_unk} predicted boxes have a class the reference never uses ({shown}); they can't be scored and were left out.")
else:
    n_unk = 0
ref_area = obj_area.copy()
if AREA:
    a_col = df[AREA].to_numpy(dtype=float, na_value=np.nan)
    ref_area = np.where(np.isnan(a_col), obj_area, a_col)
cat_all = np.asarray([0 if AGNOSTIC else cat_of.get(lab, -1) for lab in labels_all], dtype=int)
gi = np.flatnonzero(is_ref)
di = np.flatnonzero(known_pred)
gt = {"img": img_idx[gi], "cat": cat_all[gi], "box": box[gi], "area": ref_area[gi], "crowd": crowd[gi],
      "runs": [runs[j] for j in gi] if runs is not None else None}
dt = {"img": img_idx[di], "cat": cat_all[di], "box": box[di], "score": score_all[di], "area": obj_area[di],
      "runs": [runs[j] for j in di] if runs is not None else None}

# %% COCO evaluation
max_dets = (1, 10, MAX_DETS)
ev = det.evaluate(gt, dt, len(images), len(classes), IOU_TYPE, max_dets)
stats = ev["stats"]
status = ev["det_status"]   # per evaluated prediction at IoU 0.50: tp | fp | ignored | beyond
matched = ev["det_match"]   # the reference it matched (position in gt), −1 none
thr = ev["thresholds"]
t50 = int(np.flatnonzero(thr == 0.5)[0])
n_ref_regular = int((~gt["crowd"]).sum())
ref_hit = np.zeros(gi.size, dtype=bool)
for q in range(di.size):
    if status[q] == "tp":
        ref_hit[matched[q]] = True
tp50 = int(np.sum(status == "tp"))
fp50 = int(np.sum(status == "fp"))
fn50 = int(np.sum(~ref_hit & ~gt["crowd"]))
per = []
for k, c in enumerate(classes):
    pc = det.per_class(ev["precision"], ev["recall"], thr, k)
    in_g = gt["cat"] == k
    in_d = dt["cat"] == k
    per.append({"class": c, "n_ref": int(np.sum(in_g & ~gt["crowd"])), "n_crowd": int(np.sum(in_g & gt["crowd"])),
                "n_pred": int(np.sum(in_d)), "ap": pc["ap"], "ap50": pc["ap50"], "ap75": pc["ap75"], "ar": pc["ar"],
                "tp": int(np.sum(in_d & (status == "tp"))), "fp": int(np.sum(in_d & (status == "fp"))),
                "fn": int(np.sum(in_g & ~ref_hit & ~gt["crowd"]))})

# %% Assumptions
small = [p["class"] for p in per if p["n_ref"] < 10]
assumptions = [
    {"key": "complete", "label": "Every object is labeled", "status": "info",
     "detail": "Predictions of objects that the reference doesn't list count as false positives."},
    {"key": "classes", "label": "Predicted classes are in the reference", "status": "warn" if unknown else "pass",
     "detail": (f"{n_unk} predictions of {len(unknown)} unknown class(es) were left out." if unknown else "Every predicted class appears in the reference.")},
    {"key": "images", "label": "Enough objects per class", "status": "warn" if small else "pass",
     "detail": (f"Fewer than 10 reference objects: {', '.join(small[:8])}{' …' if len(small) > 8 else ''}." if small else "Every class has at least 10 reference objects.")},
]

# %% Result
f3 = lambda v: "—" if v is None else f"{v:.3f}"
values = {"n_images": len(images), "n_classes": len(classes), "n_reference": n_ref_regular, "n_crowd": int(gt["crowd"].sum()),
          "n_predictions": int(di.size), "n_unknown_label": n_unk, "iou_type": IOU_TYPE, "max_dets": MAX_DETS,
          "ap": stats["ap"], "ap50": stats["ap50"], "ap75": stats["ap75"], "ap_small": stats["ap_small"],
          "ap_medium": stats["ap_medium"], "ap_large": stats["ap_large"], "ar1": stats["ar_0"], "ar10": stats["ar_1"],
          "ar_max": stats["ar_2"], "ar_small": stats["ar_small"], "ar_medium": stats["ar_medium"], "ar_large": stats["ar_large"],
          "tp50": tp50, "fp50": fp50, "fn50": fn50,
          "precision50": tp50 / (tp50 + fp50) if (tp50 + fp50) else None,
          "recall50": tp50 / n_ref_regular if n_ref_regular else None}
for p in per:
    for key in ("ap", "ap50", "ap75", "ar"):
        values[f"{key}[{p['class']}]"] = p[key]
summary_rows = [
    ("AP", "0.50:0.95", "all", MAX_DETS, stats["ap"]), ("AP", "0.50", "all", MAX_DETS, stats["ap50"]),
    ("AP", "0.75", "all", MAX_DETS, stats["ap75"]), ("AP", "0.50:0.95", "small", MAX_DETS, stats["ap_small"]),
    ("AP", "0.50:0.95", "medium", MAX_DETS, stats["ap_medium"]), ("AP", "0.50:0.95", "large", MAX_DETS, stats["ap_large"]),
    ("AR", "0.50:0.95", "all", 1, stats["ar_0"]), ("AR", "0.50:0.95", "all", 10, stats["ar_1"]),
    ("AR", "0.50:0.95", "all", MAX_DETS, stats["ar_2"]), ("AR", "0.50:0.95", "small", MAX_DETS, stats["ar_small"]),
    ("AR", "0.50:0.95", "medium", MAX_DETS, stats["ar_medium"]), ("AR", "0.50:0.95", "large", MAX_DETS, stats["ar_large"]),
]
tables = [
    {"key": "coco", "title": "COCO summary" + (" (masks)" if IOU_TYPE == "segm" else " (boxes)"),
     "columns": [{"key": "metric", "label": "Metric", "type": "string"}, {"key": "iou", "label": "IoU", "type": "string"},
                 {"key": "area", "label": "Object size", "type": "string"}, {"key": "max_dets", "label": "Detections per image", "type": "integer"},
                 {"key": "value", "label": "Value", "type": "number"}],
     "rows": [{"metric": m, "iou": t, "area": a, "max_dets": d, "value": v} for m, t, a, d, v in summary_rows],
     "note": "Size groups use the reference area: small < 32², medium 32²–96², large > 96² pixels. Empty = no object of that size."},
    {"key": "classes", "title": "Per class (IoU 0.50 counts with every image's top detections)",
     "columns": [{"key": "class", "label": LABEL, "type": "string"}, {"key": "n_ref", "label": "Reference objects", "type": "integer"},
                 {"key": "n_crowd", "label": "Crowd regions", "type": "integer"}, {"key": "n_pred", "label": "Predictions", "type": "integer"},
                 {"key": "ap", "label": "AP", "type": "number"}, {"key": "ap50", "label": "AP50", "type": "number"},
                 {"key": "ap75", "label": "AP75", "type": "number"}, {"key": "ar", "label": f"AR@{MAX_DETS}", "type": "number"},
                 {"key": "tp", "label": "True positives", "type": "integer"}, {"key": "fp", "label": "False positives", "type": "integer"},
                 {"key": "fn", "label": "Missed", "type": "integer"}],
     "rows": per},
]
img_rows = []
for i, (m, f) in enumerate(images):
    in_g = gt["img"] == i
    in_d = dt["img"] == i
    img_rows.append({"image": m, "frame": None if f == float("-inf") else f, "n_ref": int(np.sum(in_g & ~gt["crowd"])),
                     "n_pred": int(np.sum(in_d)), "tp": int(np.sum(in_d & (status == "tp"))), "fp": int(np.sum(in_d & (status == "fp"))),
                     "fn": int(np.sum(in_g & ~ref_hit & ~gt["crowd"]))})
img_cols = [{"key": "image", "label": IMG, "type": "string"}] + ([{"key": "frame", "label": FRAME, "type": "number"}] if FRAME else []) + [
    {"key": "n_ref", "label": "Reference objects", "type": "integer"}, {"key": "n_pred", "label": "Predictions", "type": "integer"},
    {"key": "tp", "label": "True positives", "type": "integer"}, {"key": "fp", "label": "False positives", "type": "integer"},
    {"key": "fn", "label": "Missed", "type": "integer"}]
tables.append({"key": "images", "title": "Per image at IoU 0.50", "columns": img_cols, "rows": img_rows[:500],
               "note": "First 500 images." if len(img_rows) > 500 else None})
charts = []
rec = ev["recall_points"]
top = sorted(range(len(per)), key=lambda k: (-per[k]["n_ref"], k))[:8]
cr, cp, cc = [], [], []
for k in top:
    if per[k]["n_ref"] == 0:
        continue
    reach = ev["recall"][t50, k, 0, -1]
    for r, p in zip(rec, ev["precision"][t50, :, k, 0, -1]):
        if r <= reach:
            cr.append(float(r))
            cp.append(float(p))
            cc.append(per[k]["class"])
if cr:
    shown = [per[k]["class"] for k in top if per[k]["n_ref"] > 0]
    charts.append(cs.chart("pr", "pr-curve", "Precision–recall at IoU 0.50, by class", {
        "recall": cs.col("Recall", cr, "numeric"), "precision": cs.col("Precision (interpolated)", cp, "numeric"),
        "curve": cs.col(LABEL, cc, "categorical", levels=shown)},
        note="COCO's interpolated precision at 101 recall points, up to the recall each class reaches." + (" The 8 classes with the most reference objects." if len(per) > 8 else "")))
dots = [(p["class"], m, p[key]) for p in per for key, m in (("ap", "AP"), ("ap50", "AP50"), ("ap75", "AP75")) if p[key] is not None]
if dots:
    charts.append(cs.chart("ap-by-class", "cleveland-dot", "Average precision by class", {
        "category": cs.col(LABEL, [d[0] for d in dots], "categorical", levels=classes),
        "value": cs.col("Average precision", [d[2] for d in dots], "numeric"),
        "group": cs.col("Measure", [d[1] for d in dots], "categorical", levels=["AP", "AP50", "AP75"])}))
summary = (f"Across {len(images)} images and {len(classes)} class{'es' if len(classes) != 1 else ''}, AP (IoU 0.50:0.95) = {f3(stats['ap'])}, "
           f"AP50 = {f3(stats['ap50'])} and AP75 = {f3(stats['ap75'])}; average recall with up to {MAX_DETS} detections per image = {f3(stats['ar_2'])}. "
           f"At IoU 0.50: {tp50} true positives, {fp50} false positives, {fn50} missed objects.")
cs.publish({
    "method": "evaluate.detections",
    "methodVersion": "1.1.0",
    "title": "Object detection quality",
    "engine": cs.engine_info("pandas", "numpy"),
    "n": int(len(df)),
    "summary": summary,
    "statistics": [{"key": "ap", "label": "AP (0.50:0.95)", "value": stats["ap"]}, {"key": "ap50", "label": "AP50", "value": stats["ap50"]},
                   {"key": "ap75", "label": "AP75", "value": stats["ap75"]}, {"key": "ar_max", "label": f"AR@{MAX_DETS}", "value": stats["ar_2"]}],
    "tables": tables,
    "assumptions": assumptions,
    "warnings": warnings,
    "notes": [(f"Reference rows: {SOURCE} = {st['reference']}; predictions: {SOURCE} = {st['prediction']}. " if REF_ROLES is None
               else "Reference rows come from the reference table; this table's rows are the predictions. ")
              + ("Classes ignored: any predicted box can match any reference box. " if AGNOSTIC else "")
              + ("Crowd regions (" + CROWD + ") absorb overlapping predictions without counting them. " if CROWD else "")
              + "COCO conventions: IoU 0.50:0.05:0.95, 101 recall points, greedy matching by score within each image and class."],
    "charts": charts,
    "values": values,
})

Class-agnostic AP is 0.502, against 0.473 with classes. A large gap means the detector finds objects but names them wrongly; a small gap, as here, points at missed objects or loose boxes. Compare AP50 with AP75 for the second: a big drop means loose boxes.

05

Scores are rankings

Read

A detection scoreDetection scoreHow sure the detector is about one object, from 0 to 1; objects below the threshold are dropped. A rank, not a probability. of 0.9 doesn't mean "right nine times in ten". Detectors are trained to rank boxes, not to be calibrated. Choose the score threshold on validation images by the misses and false boxes you can afford, and recheck it whenever the images change.

HExplorable · Calibration and reliability

When a model says 80%, does the event happen 80% of the time?

If you make the model more overconfident, what happens to its AUC?

How sure?
2.00

Above 1 the model is too extreme; below 1 it hedges. At 1 it is perfectly calibrated.

2000
10
BrierECECalibration slopeAUC
0.1750.0870.500.835

Commit your prediction above to see the result

Make your prediction first; the figure appears when you commit.

Make your prediction to see the result.

DExplorable · Boxes, IoU, non-maximum suppression and average precision

How does a detector turn a cloud of overlapping guesses into one box per object, and how is it scored?

After NMS at this threshold, will every object still have at least one box?

How sure?

Scene

Three well-separated objects, two people standing close together plus one more, or four small objects.

0.70

A box is dropped when it overlaps a higher-scoring kept box by more than this IoU.

0.30

Candidates scoring below this are dropped before NMS.

IoU to count a hit

A kept box counts as a true positive when it overlaps an unmatched object by at least this much.

0.08

How far the detector's guesses wander from each true box, as a share of its size.

1230.990.990.860.750.740.710.690.580.31

Numbers on the kept boxes are their scores. AP averages the best precision reachable at 101 recall levels, so a false positive ranked above a hit costs more than one ranked last.

Commit your prediction above to see the result

Make your prediction first; the figure appears when you commit.

Make your prediction to see the result.

06

From frames to tracks

Read

Detections on video frames, one table with a frame column, can be linked into tracks. CodeSplash tracks on the boxes table, never on video files:

Object tracksRecorded · Python and R agreeRecorded 2026-11-25 · 25 values compared
R

7 tracks from 184 detections in 2 sequences (SORT association); 152 detections joined a track.

Tracks
7

Plots

When each track was seenWhen was each tracked object seen, and where did identities switch?

Bars break where a track missed more than one frame.

View data
media_idLast frameTrackframe
cam1510
cam11117
cam115114
cam122117
cam134129
cam137136
cam139139
cam1320
cam1625
cam11128
cam122215
cam136229
cam139238
cam11137
cam113313
cam129315
cam121418
cam124423
cam130427
cam138432
cam21053
cam213512
cam217515
cam220520
cam222522
cam225525
cam229527
cam21163
cam220613
cam223622
cam225625
cam229627
cam225710

Assumptions

  • Frames are in order — Tracks follow the frame numbers within each sequence; a gap between frame numbers counts as that many frames of motion and age.
  • Objects move smoothly — The constant-velocity motion model expects small changes from frame to frame; fast jumps between frames break tracks.

Tracks

Trackmedia_idFirst frameLast frameFrames spannedDetectionsMean score
1cam103940280.7934
2cam103940280.8313
3cam172923210.8348
4cam1183821170.8549
5cam232927190.7588
6cam232927230.8104
7cam2102516160.8254
  • 201 detections have no score and were left out.
  • Tracks start from detections and are confirmed after 3 detections; a confirmed track ends after 30 frames without one. Constant-velocity Kalman filter per box coordinate; assignment by the Hungarian method (clean-room implementation from the published papers).
The exact R script · R R version 4.5.1 (2025-06-13)
# Track objects across frames (SORT, ByteTrack, DeepSORT-style)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method track.objects 1.1.1 · spec 953cbf889d3f3c76
# Dataset: img4_tracks (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr)  # cs_track_objects (tracker), cs_eval_mot (tracking metrics), cs_eval_stacked

# %% Data
SEQ <- "media_id"; FRAME <- "frame"
X0 <- "x0"; Y0 <- "y0"; X1 <- "x1"; Y1 <- "y1"
SCORE <- "score"
LABEL <- NULL
FEATURES <- c()
SOURCE <- NULL
TRUTH <- NULL
MODE <- "sort"  # sort | bytetrack | deepsort
OPTS <- list(iou = 0.3, min_hits = as.integer(3), max_age = as.numeric(30),
             min_score = 0.5, high = 0.6, low = 0.1,
             low_iou = 0.5, max_cosine = 0.3, motion_weight = 0,
             per_class = TRUE)
MOT_IOU <- 0.5
REF_LEVEL <- NULL
SOURCE_LEVELS <- NULL  # stored order
# Reference tracks from a second table (option reference_table): its own column for each role, or NULL.
REF_ROLES <- NULL
FEATURES <- if (length(FEATURES)) as.character(FEATURES) else character(0)
columns <- unique(c(SEQ, FRAME, X0, Y0, X1, Y1, SCORE, LABEL, SOURCE, TRUTH, FEATURES))
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/img4_tracks.parquet", col_select = columns))
df$`__row` <- seq_len(nrow(df)) - 1L  # position in the analysis input
n_input <- nrow(df)
if (MODE == "bytetrack" && is.null(SCORE)) cs_error("CS_E_INVALID_OPTION", option = "Association", allowed = "SORT or DeepSORT-style unless a confidence score column is set", value = "ByteTrack")
if (MODE == "deepsort" && !length(FEATURES)) cs_error("CS_E_INVALID_OPTION", option = "Association", allowed = "SORT or ByteTrack unless embedding columns are set", value = "DeepSORT-style")
pre_warnings <- list()
if (!is.null(REF_ROLES)) {
  # The reference table's rows go above the detections under an added source column (twin: with_reference).
  w <- cs_eval_with_reference(df, cs_graph_dataset_option("target/academy-parity/run-8142/track.objects/detections-only/out-r", "reference_table"),
                              list(sequence = SEQ, frame = FRAME, x0 = X0, y0 = Y0, x1 = X1, y1 = Y1, score = SCORE, label = LABEL, truth = TRUTH),
                              REF_ROLES, list(label = "Class"), SOURCE, REF_LEVEL, c("sequence", "frame", "x0", "y0", "x1", "y1", if (!is.null(LABEL)) "label"))
  df <- w$df
  pre_warnings <- w$warnings
  wc <- w$columns
  SEQ <- wc$sequence; FRAME <- wc$frame; X0 <- wc$x0; Y0 <- wc$y0; X1 <- wc$x1; Y1 <- wc$y1
  LABEL <- wc$label; TRUTH <- wc$truth
  SOURCE <- w$source; REF_LEVEL <- w$reference; SOURCE_LEVELS <- w$levels
}
needed <- c(SEQ, FRAME, X0, Y0, X1, Y1, LABEL)
numeric_cols <- c(FRAME, X0, Y0, X1, Y1, SCORE, FEATURES)
if (!is.null(SOURCE)) {
  st <- cs_eval_stacked(df, c(needed, SOURCE), numeric_cols, SOURCE, REF_LEVEL, SOURCE_LEVELS)
  df <- st$df
  is_ref <- st$is_ref
  warnings <- c(pre_warnings, st$warnings)
} else {
  if (n_input == 0L) cs_error("CS_E_NO_ROWS")
  for (c in needed) if (all(is.na(df[[c]]))) cs_error("CS_E_ALL_MISSING", column = c)
  keep <- rep(TRUE, n_input)
  for (c in needed) keep <- keep & !is.na(df[[c]])
  df <- df[keep, , drop = FALSE]
  warnings <- if (nrow(df) < n_input) list(cs_warning("CS_W_ROWS_DROPPED", dropped = n_input - nrow(df), total = n_input)) else list()
  if (nrow(df) == 0L) cs_error("CS_E_NO_ROWS")
  for (c in numeric_cols) {
    k <- sum(is.infinite(as.numeric(df[[c]])))
    if (k > 0) cs_error("CS_E_NOT_FINITE", column = c, count = k)
  }
  is_ref <- logical(nrow(df))
}
box <- cbind(as.numeric(df[[X0]]), as.numeric(df[[Y0]]), as.numeric(df[[X1]]), as.numeric(df[[Y1]]))
bad <- (box[, 3] < box[, 1]) | (box[, 4] < box[, 2])
if (any(bad)) cs_error("CS_E_INVALID_VALUES", column = sprintf("%s and %s", X1, Y1), requirement = sprintf("at least %s and %s", X0, Y0), count = sum(bad))
det <- !is_ref
if (!is.null(SCORE)) {
  no_score <- det & is.na(as.numeric(df[[SCORE]]))
  if (any(no_score)) {
    warnings <- c(warnings, sprintf("%d detections have no %s and were left out.", sum(no_score), SCORE))
    det <- det & !no_score
  }
}
if (length(FEATURES)) {
  no_feat <- det & !stats::complete.cases(df[FEATURES])
  if (any(no_feat)) {
    warnings <- c(warnings, sprintf("%d detections miss an embedding value and were left out.", sum(no_feat)))
    det <- det & !no_feat
  }
}
if (sum(det) < 2L) cs_error("CS_E_TOO_FEW_ROWS", what = "Tracking", min = 2, n = sum(det))

# %% Tracks
di <- which(det)
seq_all <- as.character(df[[SEQ]])
frame_all <- as.numeric(df[[FRAME]])
lab_all <- if (!is.null(LABEL)) as.character(df[[LABEL]]) else NULL
feats <- if (length(FEATURES)) as.matrix(df[di, FEATURES, drop = FALSE]) else NULL
if (!is.null(feats)) storage.mode(feats) <- "double"
res <- cs_track_objects(seq_all[di], frame_all[di], box[di, , drop = FALSE], if (!is.null(SCORE)) as.numeric(df[[SCORE]])[di] else NULL,
                        if (!is.null(LABEL)) lab_all[di] else NULL, feats, MODE, OPTS)
tid_det <- res$track
track_id <- rep(NA_integer_, n_input)  # per input row; rows that weren't tracked stay empty
track_id[df$`__row`[di][tid_det > 0L] + 1L] <- tid_det[tid_det > 0L]
tracks <- res$tracks
n_tracks <- length(tracks)
n_assigned <- sum(tid_det > 0L)

# %% Against the reference tracks
metrics <- NULL
switch_events <- list()
if (!is.null(SOURCE) && !is.null(TRUTH) && sum(is_ref) > 0) {
  truth_ok <- is_ref & !is.na(df[[TRUTH]])
  if (sum(is_ref & !truth_ok) > 0) warnings <- c(warnings, sprintf("%d reference boxes have no %s and were left out of the tracking metrics.", sum(is_ref & !truth_ok), TRUTH))
  truth_all <- as.character(df[[TRUTH]])
  gi <- which(truth_ok)
  hi <- di[tid_det > 0L]
  hyp_of <- integer(nrow(df))
  hyp_of[di] <- tid_det
  seqs <- list()
  for (sq in sort(unique(c(seq_all[gi], seq_all[hi])), method = "radix")) {
    g_s <- gi[seq_all[gi] == sq]
    h_s <- hi[seq_all[hi] == sq]
    frames <- list()
    for (f in sort(unique(c(frame_all[g_s], frame_all[h_s])))) {
      g_f <- g_s[frame_all[g_s] == f]
      h_f <- h_s[frame_all[h_s] == f]
      # paste() would recycle an empty id vector into one id: frames with predictions but no reference boxes get none.
      gt_ids <- if (length(g_f)) paste(sq, truth_all[g_f], sep = "\u001f") else character(0)
      frames[[length(frames) + 1L]] <- list(frame = f, gt_ids = gt_ids, gt_boxes = box[g_f, , drop = FALSE],
                                            hyp_ids = as.character(hyp_of[h_f]), hyp_boxes = box[h_f, , drop = FALSE])
    }
    seqs[[length(seqs) + 1L]] <- frames
  }
  metrics <- cs_eval_mot(seqs, MOT_IOU)
  switch_events <- metrics$switch_events
}

# %% Assumptions
assumptions <- list(
  list(key = "frames", label = "Frames are in order", status = "info",
       detail = "Tracks follow the frame numbers within each sequence; a gap between frame numbers counts as that many frames of motion and age."),
  list(key = "motion", label = "Objects move smoothly", status = "info",
       detail = "The constant-velocity motion model expects small changes from frame to frame; fast jumps between frames break tracks.")
)
if (length(FEATURES)) assumptions[[3]] <- list(key = "appearance", label = "Embeddings describe appearance", status = "info",
  detail = "DeepSORT-style matching trusts the embedding columns to tell objects apart; embeddings of the same object should be close.")

# %% Result
f3 <- function(v) if (is.null(v) || is.na(v)) "—" else sprintf("%.3f", v)
tl <- vapply(tracks, function(t) if (is.na(t$label)) NA_character_ else t$label, character(1))
labels_seen <- sort(unique(tl[!is.na(tl)]), method = "radix")
seq_list <- sort(unique(seq_all[di]), method = "radix")
n_frames <- sum(!duplicated(paste(seq_all[di], sprintf("%.17g", frame_all[di]), sep = "\u001f")))
nz <- function(v) if (is.null(v)) NA_real_ else v
values <- list(association = MODE, n_sequences = length(seq_list), n_frames = n_frames, n_detections = length(di), n_tracks = n_tracks,
               n_assigned = n_assigned, n_unassigned = length(di) - n_assigned,
               mean_track_length = if (n_tracks) mean(vapply(tracks, function(t) t$n_detections, numeric(1))) else NA_real_,
               mota = NA_real_, motp = NA_real_, idf1 = NA_real_, idp = NA_real_, idr = NA_real_, id_switches = NA_real_, fragmentations = NA_real_,
               false_positives = NA_real_, misses = NA_real_, mostly_tracked = NA_real_, partially_tracked = NA_real_, mostly_lost = NA_real_,
               precision = NA_real_, recall = NA_real_, n_gt_tracks = NA_real_, n_gt_boxes = NA_real_, track_id = I(track_id))
for (lab in labels_seen) values[[sprintf("tracks[%s]", lab)]] <- sum(tl == lab, na.rm = TRUE)
if (!is.null(metrics)) {
  values$mota <- metrics$mota; values$motp <- metrics$motp; values$idf1 <- metrics$idf1; values$idp <- metrics$idp; values$idr <- metrics$idr
  values$id_switches <- metrics$switches; values$fragmentations <- metrics$fragmentations; values$false_positives <- metrics$false_positives
  values$misses <- metrics$misses; values$mostly_tracked <- metrics$mostly_tracked; values$partially_tracked <- metrics$partially_tracked
  values$mostly_lost <- metrics$mostly_lost; values$precision <- metrics$precision; values$recall <- metrics$recall
  values$n_gt_tracks <- metrics$n_gt_tracks; values$n_gt_boxes <- metrics$objects
}
trk_rows <- lapply(tracks, function(t) list(track_id = t$track_id, sequence = t$sequence, label = t$label, first_frame = t$first_frame,
                                            last_frame = t$last_frame, span = t$last_frame - t$first_frame + 1, n_detections = t$n_detections,
                                            mean_score = t$mean_score))
tcols <- c(list(list(key = "track_id", label = "Track", type = "integer"), list(key = "sequence", label = SEQ, type = "string")),
           if (!is.null(LABEL)) list(list(key = "label", label = LABEL, type = "string")),
           list(list(key = "first_frame", label = "First frame", type = "number"), list(key = "last_frame", label = "Last frame", type = "number"),
                list(key = "span", label = "Frames spanned", type = "number"), list(key = "n_detections", label = "Detections", type = "integer")),
           if (!is.null(SCORE)) list(list(key = "mean_score", label = "Mean score", type = "number")))
tables <- list(list(key = "tracks", title = "Tracks", columns = tcols, rows = utils::head(trk_rows, 500),
                    note = if (length(trk_rows) > 500) "First 500 tracks." else NULL))
if (!is.null(metrics)) {
  mrows <- list(list("MOTA", metrics$mota, "1 − (misses + false positives + identity switches) / reference boxes"),
                list("IDF1", metrics$idf1, "Share of boxes on the right identity (global track matching)"),
                list("MOTP (mean IoU)", metrics$motp, "Mean overlap of the paired boxes"),
                list("Identity switches", metrics$switches, "A reference object took a different track"),
                list("Fragmentations", metrics$fragmentations, "A tracked object was lost and found again"),
                list("Misses", metrics$misses, "Reference boxes with no track"), list("False positives", metrics$false_positives, "Tracked boxes with no reference object"),
                list("Mostly tracked", metrics$mostly_tracked, "Reference tracks paired in at least 80% of their frames"),
                list("Mostly lost", metrics$mostly_lost, "Reference tracks paired in under 20% of their frames"))
  tables[[length(tables) + 1L]] <- list(key = "mot", title = sprintf("Against the reference tracks (IoU ≥ %g)", MOT_IOU),
    columns = list(list(key = "metric", label = "Measure", type = "string"), list(key = "value", label = "Value", type = "number"),
                   list(key = "meaning", label = "Meaning", type = "string")),
    rows = lapply(mrows, function(r) list(metric = r[[1]], value = r[[2]], meaning = r[[3]])))
  if (length(switch_events)) {
    tables[[length(tables) + 1L]] <- list(key = "switches", title = "Identity switches",
      columns = list(list(key = "sequence", label = SEQ, type = "string"), list(key = "frame", label = "Frame", type = "number"),
                     list(key = "object", label = "Reference object", type = "string"), list(key = "from", label = "From track", type = "string"),
                     list(key = "to", label = "To track", type = "string")),
      rows = lapply(utils::head(switch_events, 200), function(e) { p <- strsplit(e$object, "\u001f", fixed = TRUE)[[1]]
        list(sequence = p[1], frame = e$frame, object = p[2], from = e$from, to = e$to) }),
      note = if (length(switch_events) > 200) "First 200 switches." else NULL)
  }
}
charts <- list()
if (n_tracks) {
  lane_of <- function(t) paste0(t$track_id, if (!is.na(t$label)) paste0(" · ", t$label) else "")
  shown <- utils::head(tracks, 60)
  color_of <- function(t) if (length(seq_list) > 1L) t$sequence else if (!is.na(t$label)) t$label else t$sequence
  ln <- character(0); s0 <- numeric(0); s1 <- numeric(0); col <- character(0); ev <- character(0)
  fr_det <- frame_all[di]
  for (t in shown) {
    fr <- sort(fr_det[tid_det == t$track_id])
    brk <- which(diff(fr) > 1)
    starts <- c(fr[1], fr[brk + 1L])
    ends <- c(fr[brk], fr[length(fr)])
    ln <- c(ln, rep(lane_of(t), length(starts))); s0 <- c(s0, starts); s1 <- c(s1, ends)
    col <- c(col, rep(color_of(t), length(starts))); ev <- c(ev, rep(NA_character_, length(starts)))
  }
  shown_ids <- vapply(shown, function(t) t$track_id, numeric(1))
  for (e in switch_events) {
    to <- as.integer(e$to)
    if (to %in% shown_ids) {
      t <- shown[[which(shown_ids == to)[1]]]
      ln <- c(ln, lane_of(t)); s0 <- c(s0, e$frame); s1 <- c(s1, e$frame); col <- c(col, color_of(t)); ev <- c(ev, "Identity switch")
    }
  }
  roles <- list(lane = cs_col("Track", ln, "categorical", levels = vapply(shown, lane_of, character(1))),
                start = cs_col(FRAME, s0, "numeric"), end = cs_col("Last frame", s1, "numeric"),
                color = cs_col(if (length(seq_list) > 1L) SEQ else if (!is.null(LABEL)) LABEL else SEQ, col, "categorical"))
  if (any(!is.na(ev))) roles$event <- cs_col("Event", ev, "categorical")
  charts[[1]] <- cs_chart("timeline", "track-timeline", "When each track was seen", roles,
                          note = paste0(if (n_tracks > 60) "The first 60 tracks. " else "", "Bars break where a track missed more than one frame."))
}
out <- cs_ml_out_dir("target/academy-parity/run-8142/track.objects/detections-only/out-r")
labels_path <- file.path(out, "labels.parquet")
nanoparquet::write_parquet(data.frame(row = as.numeric(seq_len(n_input) - 1L), cluster = as.numeric(ifelse(is.na(track_id), -1L, track_id))), labels_path)
names_mode <- c(sort = "SORT", bytetrack = "ByteTrack", deepsort = "DeepSORT-style")
summary <- sprintf("%d track%s from %d detections in %d sequence%s (%s association); %d detections joined a track.", n_tracks, if (n_tracks != 1) "s" else "",
                   length(di), length(seq_list), if (length(seq_list) != 1) "s" else "", names_mode[[MODE]], n_assigned)
if (!is.null(metrics)) summary <- paste0(summary, sprintf(" Against %d reference tracks: MOTA %s, IDF1 %s, %d identity switches.", as.integer(metrics$n_gt_tracks),
                                                          f3(metrics$mota), f3(metrics$idf1), as.integer(metrics$switches)))
cs_publish(list(
  method = "track.objects",
  methodVersion = "1.1.1",
  title = "Object tracks",
  engine = cs_engine_info("nanoparquet"),
  n = nrow(df),
  summary = summary,
  statistics = c(list(list(key = "n_tracks", label = "Tracks", value = n_tracks)),
                 if (!is.null(metrics)) list(list(key = "mota", label = "MOTA", value = metrics$mota), list(key = "idf1", label = "IDF1", value = metrics$idf1),
                                             list(key = "id_switches", label = "Identity switches", value = metrics$switches))),
  tables = tables,
  assumptions = assumptions,
  warnings = warnings,
  notes = list(paste0(sprintf("Tracks start from detections and are confirmed after %d detections; a confirmed track ends after %g frames without one. ", OPTS$min_hits, OPTS$max_age),
                      if (!is.null(LABEL) && OPTS$per_class) "Boxes pair only within the same class. " else "",
                      "Constant-velocity Kalman filter per box coordinate; assignment by the Hungarian method (clean-room implementation from the published papers).")),
  charts = charts,
  artifacts = list(list(key = "labels", path = labels_path, format = "parquet")),
  values = values
))
Python

7 tracks from 184 detections in 2 sequences (SORT association); 152 detections joined a track.

Tracks
7

To keep this page light, the plots are shown once, under the R tab.

Assumptions

  • Frames are in order — Tracks follow the frame numbers within each sequence; a gap between frame numbers counts as that many frames of motion and age.
  • Objects move smoothly — The constant-velocity motion model expects small changes from frame to frame; fast jumps between frames break tracks.

Tracks

Trackmedia_idFirst frameLast frameFrames spannedDetectionsMean score
1cam103940280.7934
2cam103940280.8313
3cam172923210.8348
4cam1183821170.8549
5cam232927190.7588
6cam232927230.8104
7cam2102516160.8254
  • 201 detections have no score and were left out.
  • Tracks start from detections and are confirmed after 3 detections; a confirmed track ends after 30 frames without one. Constant-velocity Kalman filter per box coordinate; assignment by the Hungarian method (clean-room implementation from the published papers).
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Track objects across frames (SORT, ByteTrack, DeepSORT-style)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method track.objects 1.1.1 · spec 953cbf889d3f3c76
# Dataset: img4_tracks (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.evaluate import mot  # twin: codesplashr cs_eval_mot
from codesplash.evaluate.stacked import stacked  # twin: cs_eval_stacked
from codesplash import ml as csml
from codesplash.track import objects as tr  # twin: codesplashr cs_track_objects

# %% Data
SEQ, FRAME = "media_id", "frame"
X0, Y0, X1, Y1 = "x0", "y0", "x1", "y1"
SCORE = "score"
LABEL = None
FEATURES = []
SOURCE = None
TRUTH = None
MODE = "sort"  # sort | bytetrack | deepsort
OPTS = {"iou": 0.3, "min_hits": int(3), "max_age": float(30),
        "min_score": 0.5, "high": 0.6, "low": 0.1,
        "low_iou": 0.5, "max_cosine": 0.3, "motion_weight": 0,
        "per_class": True}
MOT_IOU = 0.5
REF_LEVEL = None
SOURCE_LEVELS = None  # stored order
# Reference tracks from a second table (option reference_table): its own column for each role, or None.
REF_ROLES = None
columns = list(dict.fromkeys(c for c in [SEQ, FRAME, X0, Y0, X1, Y1, SCORE, LABEL, SOURCE, TRUTH] + FEATURES if c))
df = pd.read_parquet("tests/parity/fixtures/img4_tracks.parquet", columns=columns)
df["__row"] = np.arange(len(df))  # position in the analysis input
n_input = len(df)
if MODE == "bytetrack" and not SCORE:
    cs.cs_error("CS_E_INVALID_OPTION", option="Association", allowed="SORT or DeepSORT-style unless a confidence score column is set", value="ByteTrack")
if MODE == "deepsort" and not FEATURES:
    cs.cs_error("CS_E_INVALID_OPTION", option="Association", allowed="SORT or ByteTrack unless embedding columns are set", value="DeepSORT-style")
pre_warnings = []
if REF_ROLES is not None:
    # The reference table's rows go above the detections under an added source column (twin: cs_eval_with_reference).
    from codesplash.graph import dataset_option  # the table the host wrote for the option
    from codesplash.evaluate.stacked import with_reference
    w = with_reference(df, dataset_option("target/academy-parity/run-8142/track.objects/detections-only/out-python", "reference_table"),
                       {"sequence": SEQ, "frame": FRAME, "x0": X0, "y0": Y0, "x1": X1, "y1": Y1, "score": SCORE, "label": LABEL, "truth": TRUTH},
                       REF_ROLES, {"label": "Class"}, SOURCE, REF_LEVEL, ["sequence", "frame", "x0", "y0", "x1", "y1"] + (["label"] if LABEL else []))
    df, pre_warnings, wc = w["df"], w["warnings"], w["columns"]
    SEQ, FRAME, X0, Y0, X1, Y1 = wc["sequence"], wc["frame"], wc["x0"], wc["y0"], wc["x1"], wc["y1"]
    LABEL, TRUTH = wc["label"], wc["truth"]
    SOURCE, REF_LEVEL, SOURCE_LEVELS = w["source"], w["reference"], w["levels"]
needed = [SEQ, FRAME, X0, Y0, X1, Y1] + ([LABEL] if LABEL else [])
numeric = [c for c in [FRAME, X0, Y0, X1, Y1, SCORE] if c] + FEATURES
if SOURCE:
    st = stacked(df, needed + [SOURCE], numeric, SOURCE, REF_LEVEL, SOURCE_LEVELS)
    df, is_ref, warnings = st["df"], st["is_ref"], pre_warnings + st["warnings"]
else:
    if n_input == 0:
        cs.cs_error("CS_E_NO_ROWS")
    for c in needed:
        if df[c].isna().all():
            cs.cs_error("CS_E_ALL_MISSING", column=c)
    keep = np.ones(n_input, dtype=bool)
    for c in needed:
        keep &= df[c].notna().to_numpy()
    df = df.loc[keep].reset_index(drop=True)
    warnings = [cs.cs_warning("CS_W_ROWS_DROPPED", dropped=int(n_input - len(df)), total=n_input)] if len(df) < n_input else []
    if len(df) == 0:
        cs.cs_error("CS_E_NO_ROWS")
    for c in numeric:
        k = int(np.isinf(df[c].to_numpy(dtype=float, na_value=np.nan)).sum())
        if k:
            cs.cs_error("CS_E_NOT_FINITE", column=c, count=k)
    is_ref = np.zeros(len(df), dtype=bool)
box = df[[X0, Y0, X1, Y1]].to_numpy(dtype=float)
bad = (box[:, 2] < box[:, 0]) | (box[:, 3] < box[:, 1])
if bad.any():
    cs.cs_error("CS_E_INVALID_VALUES", column=f"{X1} and {Y1}", requirement=f"at least {X0} and {Y0}", count=int(bad.sum()))
det = ~is_ref
if SCORE:
    no_score = det & np.isnan(df[SCORE].to_numpy(dtype=float, na_value=np.nan))
    if no_score.any():
        warnings.append(f"{int(no_score.sum())} detections have no {SCORE} and were left out.")
        det &= ~no_score
if FEATURES:
    no_feat = det & df[FEATURES].isna().any(axis=1).to_numpy()
    if no_feat.any():
        warnings.append(f"{int(no_feat.sum())} detections miss an embedding value and were left out.")
        det &= ~no_feat
if int(det.sum()) < 2:
    cs.cs_error("CS_E_TOO_FEW_ROWS", what="Tracking", min=2, n=int(det.sum()))

# %% Tracks
di = np.flatnonzero(det)
seq_all = np.asarray([str(x) for x in df[SEQ].tolist()], dtype=object)
frame_all = df[FRAME].to_numpy(dtype=float)
lab_all = np.asarray([str(x) for x in df[LABEL].tolist()], dtype=object) if LABEL else None
res = tr.track(seq_all[di], frame_all[di], box[di], df[SCORE].to_numpy(dtype=float)[di] if SCORE else None,
               lab_all[di] if LABEL else None, df[FEATURES].to_numpy(dtype=float)[di] if FEATURES else None, MODE, **OPTS)
tid_det = res["track"]
track_id = [None] * n_input  # per input row; rows that weren't tracked stay empty
for k, i in enumerate(di):
    if tid_det[k] > 0:
        track_id[int(df["__row"].iloc[i])] = int(tid_det[k])
tracks = res["tracks"]
n_tracks = len(tracks)
n_assigned = int(np.sum(tid_det > 0))

# %% Against the reference tracks
metrics = None
switch_events = []
if SOURCE and TRUTH and int(is_ref.sum()):
    truth_ok = is_ref & df[TRUTH].notna().to_numpy()
    if int((is_ref & ~truth_ok).sum()):
        warnings.append(f"{int((is_ref & ~truth_ok).sum())} reference boxes have no {TRUTH} and were left out of the tracking metrics.")
    truth_all = np.asarray([str(x) for x in df[TRUTH].tolist()], dtype=object)
    gi = np.flatnonzero(truth_ok)
    hi = di[tid_det > 0]
    hyp_id = {int(i): str(int(t)) for i, t in zip(di, tid_det) if t > 0}
    seqs = []
    for sq in sorted(set(seq_all[gi].tolist()) | set(seq_all[hi].tolist())):
        g_s = gi[seq_all[gi] == sq]
        h_s = hi[seq_all[hi] == sq]
        frames = []
        for f in sorted(set(frame_all[g_s].tolist()) | set(frame_all[h_s].tolist())):
            g_f = g_s[frame_all[g_s] == f]
            h_f = h_s[frame_all[h_s] == f]
            frames.append({"frame": f, "gt_ids": [f"{sq}\x1f{truth_all[i]}" for i in g_f], "gt_boxes": box[g_f],
                           "hyp_ids": [hyp_id[int(i)] for i in h_f], "hyp_boxes": box[h_f]})
        seqs.append(frames)
    metrics = mot.clear_mot(seqs, MOT_IOU)
    switch_events = metrics["switch_events"]

# %% Assumptions
assumptions = [
    {"key": "frames", "label": "Frames are in order", "status": "info",
     "detail": "Tracks follow the frame numbers within each sequence; a gap between frame numbers counts as that many frames of motion and age."},
    {"key": "motion", "label": "Objects move smoothly", "status": "info",
     "detail": "The constant-velocity motion model expects small changes from frame to frame; fast jumps between frames break tracks."},
]
if FEATURES:
    assumptions.append({"key": "appearance", "label": "Embeddings describe appearance", "status": "info",
                        "detail": "DeepSORT-style matching trusts the embedding columns to tell objects apart; embeddings of the same object should be close."})

# %% Result
f3 = lambda v: "—" if v is None else f"{v:.3f}"
labels_seen = sorted(set(t["label"] for t in tracks if t["label"] is not None))
seq_list = sorted(set(seq_all[di].tolist()))
n_frames = len(set(zip(seq_all[di].tolist(), frame_all[di].tolist())))
values = {"association": MODE, "n_sequences": len(seq_list), "n_frames": n_frames, "n_detections": int(di.size), "n_tracks": n_tracks,
          "n_assigned": n_assigned, "n_unassigned": int(di.size - n_assigned),
          "mean_track_length": float(np.mean([t["n_detections"] for t in tracks])) if tracks else None,
          "mota": None, "motp": None, "idf1": None, "idp": None, "idr": None, "id_switches": None, "fragmentations": None,
          "false_positives": None, "misses": None, "mostly_tracked": None, "partially_tracked": None, "mostly_lost": None,
          "precision": None, "recall": None, "n_gt_tracks": None, "n_gt_boxes": None, "track_id": track_id}
for lab in labels_seen:
    values[f"tracks[{lab}]"] = sum(1 for t in tracks if t["label"] == lab)
if metrics is not None:
    values.update({"mota": metrics["mota"], "motp": metrics["motp"], "idf1": metrics["idf1"], "idp": metrics["idp"], "idr": metrics["idr"],
                   "id_switches": metrics["switches"], "fragmentations": metrics["fragmentations"], "false_positives": metrics["false_positives"],
                   "misses": metrics["misses"], "mostly_tracked": metrics["mostly_tracked"], "partially_tracked": metrics["partially_tracked"],
                   "mostly_lost": metrics["mostly_lost"], "precision": metrics["precision"], "recall": metrics["recall"],
                   "n_gt_tracks": metrics["n_gt_tracks"], "n_gt_boxes": metrics["objects"]})
trk_rows = [{"track_id": t["track_id"], "sequence": t["sequence"], "label": t["label"], "first_frame": t["first_frame"], "last_frame": t["last_frame"],
             "span": t["last_frame"] - t["first_frame"] + 1.0, "n_detections": t["n_detections"], "mean_score": t["mean_score"]} for t in tracks]
tables = [{"key": "tracks", "title": "Tracks",
           "columns": [{"key": "track_id", "label": "Track", "type": "integer"}, {"key": "sequence", "label": SEQ, "type": "string"}]
           + ([{"key": "label", "label": LABEL, "type": "string"}] if LABEL else [])
           + [{"key": "first_frame", "label": "First frame", "type": "number"}, {"key": "last_frame", "label": "Last frame", "type": "number"},
              {"key": "span", "label": "Frames spanned", "type": "number"}, {"key": "n_detections", "label": "Detections", "type": "integer"}]
           + ([{"key": "mean_score", "label": "Mean score", "type": "number"}] if SCORE else []),
           "rows": trk_rows[:500], "note": "First 500 tracks." if len(trk_rows) > 500 else None}]
if metrics is not None:
    mrows = [("MOTA", metrics["mota"], "1 − (misses + false positives + identity switches) / reference boxes"),
             ("IDF1", metrics["idf1"], "Share of boxes on the right identity (global track matching)"),
             ("MOTP (mean IoU)", metrics["motp"], "Mean overlap of the paired boxes"),
             ("Identity switches", metrics["switches"], "A reference object took a different track"),
             ("Fragmentations", metrics["fragmentations"], "A tracked object was lost and found again"),
             ("Misses", metrics["misses"], "Reference boxes with no track"), ("False positives", metrics["false_positives"], "Tracked boxes with no reference object"),
             ("Mostly tracked", metrics["mostly_tracked"], "Reference tracks paired in at least 80% of their frames"),
             ("Mostly lost", metrics["mostly_lost"], "Reference tracks paired in under 20% of their frames")]
    tables.append({"key": "mot", "title": f"Against the reference tracks (IoU ≥ {MOT_IOU:g})",
                   "columns": [{"key": "metric", "label": "Measure", "type": "string"}, {"key": "value", "label": "Value", "type": "number"},
                               {"key": "meaning", "label": "Meaning", "type": "string"}],
                   "rows": [{"metric": a, "value": b, "meaning": c} for a, b, c in mrows]})
    if switch_events:
        tables.append({"key": "switches", "title": "Identity switches",
                       "columns": [{"key": "sequence", "label": SEQ, "type": "string"}, {"key": "frame", "label": "Frame", "type": "number"},
                                   {"key": "object", "label": "Reference object", "type": "string"}, {"key": "from", "label": "From track", "type": "string"},
                                   {"key": "to", "label": "To track", "type": "string"}],
                       "rows": [{"sequence": e["object"].split("\x1f")[0], "frame": e["frame"], "object": e["object"].split("\x1f")[1],
                                 "from": e["from"], "to": e["to"]} for e in switch_events[:200]],
                       "note": "First 200 switches." if len(switch_events) > 200 else None})
charts = []
if tracks:
    lane_of = {t["track_id"]: f"{t['track_id']}" + (f" · {t['label']}" if t["label"] is not None else "") for t in tracks}
    shown = tracks[:60]
    ln, s0, s1, col, ev = [], [], [], [], []
    for t in shown:
        fr = np.sort(frame_all[di][tid_det == t["track_id"]])
        brk = np.flatnonzero(np.diff(fr) > 1.0)
        starts = np.concatenate([[fr[0]], fr[brk + 1]])
        ends = np.concatenate([fr[brk], [fr[-1]]])
        for a, b in zip(starts, ends):
            ln.append(lane_of[t["track_id"]])
            s0.append(float(a))
            s1.append(float(b))
            col.append(t["sequence"] if len(seq_list) > 1 else (t["label"] if t["label"] is not None else t["sequence"]))
            ev.append(None)
    shown_ids = {t["track_id"] for t in shown}
    for e in switch_events:
        if int(e["to"]) in shown_ids:
            t = next(x for x in shown if x["track_id"] == int(e["to"]))
            ln.append(lane_of[t["track_id"]])
            s0.append(float(e["frame"]))
            s1.append(float(e["frame"]))
            col.append(t["sequence"] if len(seq_list) > 1 else (t["label"] if t["label"] is not None else t["sequence"]))
            ev.append("Identity switch")
    roles = {"lane": cs.col("Track", ln, "categorical", levels=[lane_of[t["track_id"]] for t in shown]),
             "start": cs.col(FRAME, s0, "numeric"), "end": cs.col("Last frame", s1, "numeric"),
             "color": cs.col(SEQ if len(seq_list) > 1 else (LABEL or SEQ), col, "categorical")}
    if any(v is not None for v in ev):
        roles["event"] = cs.col("Event", ev, "categorical")
    charts.append(cs.chart("timeline", "track-timeline", "When each track was seen", roles,
                           note=("The first 60 tracks. " if len(tracks) > 60 else "") + "Bars break where a track missed more than one frame."))
out = csml.out_dir("target/academy-parity/run-8142/track.objects/detections-only/out-python")
labels_path = os.path.join(out, "labels.parquet")
pd.DataFrame({"row": np.arange(n_input, dtype=np.int64), "cluster": np.asarray([-1 if v is None else v for v in track_id], dtype=np.int64)}).to_parquet(labels_path, index=False)
summary = (f"{n_tracks} track{'s' if n_tracks != 1 else ''} from {int(di.size)} detections in {len(seq_list)} sequence{'s' if len(seq_list) != 1 else ''} "
           f"({ {'sort': 'SORT', 'bytetrack': 'ByteTrack', 'deepsort': 'DeepSORT-style'}[MODE] } association); {n_assigned} detections joined a track.")
if metrics is not None:
    summary += (f" Against {metrics['n_gt_tracks']} reference tracks: MOTA {f3(metrics['mota'])}, IDF1 {f3(metrics['idf1'])}, "
                f"{metrics['switches']} identity switches.")
cs.publish({
    "method": "track.objects",
    "methodVersion": "1.1.1",
    "title": "Object tracks",
    "engine": cs.engine_info("pandas", "numpy"),
    "n": int(len(df)),
    "summary": summary,
    "statistics": [{"key": "n_tracks", "label": "Tracks", "value": n_tracks}]
                  + ([{"key": "mota", "label": "MOTA", "value": metrics["mota"]}, {"key": "idf1", "label": "IDF1", "value": metrics["idf1"]},
                      {"key": "id_switches", "label": "Identity switches", "value": metrics["switches"]}] if metrics is not None else []),
    "tables": tables,
    "assumptions": assumptions,
    "warnings": warnings,
    "notes": [f"Tracks start from detections and are confirmed after {OPTS['min_hits']} detections; a confirmed track ends after {OPTS['max_age']:g} frames without one. "
              + ("Boxes pair only within the same class. " if (LABEL and OPTS["per_class"]) else "")
              + "Constant-velocity Kalman filter per box coordinate; assignment by the Hungarian method (clean-room implementation from the published papers)."],
    "charts": charts,
    "artifacts": [{"key": "labels", "path": labels_path, "format": "parquet"}],
    "values": values,
})

Here 184 boxes over 69 frames became 7 tracks. The Video track teaches tracking and its metrics.

07

Check: detection workflow

Checkpoint

Check yourself

You will run a detector on 4 new store cameras. Which held-out set gives an honest score?

Show the answer

Answer: b

Frames from one camera share background and angle. Holding out whole cameras tests what you'll face.

Check yourself

A detector has AP 0.55 overall but AP 0.15 on small objects. You need to count small screws in tray photos. What do you conclude?

Show the answer

Answer: a

The size split is the number that matches your task. Larger input sizes and closer crops help small objects most.

Check yourself

Class-agnostic AP is 0.70 but per-class AP is 0.35. What is the main problem?

Show the answer

Answer: c

Ignoring classes doubles AP, so localization is fine and classification is the weak part. Look at the confusion between classes.

Check yourself

How should you choose a score threshold for a deployed detector?

Show the answer

Answer: b

AP averages over all thresholds, so it can't pick one. The right threshold depends on what a miss and a false alarm cost you.

08

Recap

Recap
  • Label images like yours, split by source, detect on held-out images and score against the labels.
  • Read AP by class and by size; the size that matches your objects is the number to trust.
  • Compare scores only at the same detection limit; class-agnostic AP separates naming errors from misses.
  • Detection scores rank boxes; choose thresholds on validation data, not by treating scores as probabilities.

Concepts in this lesson