Scoring boxes, masks and time segments
Score boxes with COCO average precision, masks with IoU and Dice, and time segments with segment F1 and mAP, and know which convention each number hides.
What runs in CodeSplash
- Object detection quality (COCO average precision) Experimental
- Segmentation quality (IoU, Dice, segment F1) Experimental
You will be able to
- Explain intersection over union and why the threshold decides what counts as found
- Read COCO AP, AP50, AP75, AP by object size and average recall at k detections
- Tell mean IoU, Dice and pixel accuracy apart, and why background inflates accuracy
- Score time segments with segment F1 at IoU thresholds and average precision
One table, two sources
ReadDetections and their labels usually live in the same boxes table: one row per box (or mask, or segment) with a source column that says annotation for the reference and prediction for what the model found. When the labels sit in a table of their own, choose it under Reference table: every row you analyze then counts as a prediction, and the numbers are the same. Scoring compares the two within each image and class.
When does a box count as found?
ReadTwo boxes overlap by their intersection over unionIntersection over union (IoU) of boxesThe area two boxes share divided by the area they cover together: 1 for the same box, 0 when they don't touch.: shared area divided by covered area. A prediction finds an object when its IoU reaches a threshold. At 0.5 a box can be quite loose; at 0.9 it has to be nearly exact.
Predict first
Two boxes of equal size overlap by half of each one's area. What is their IoU?
Reveal
About a third. The shared part is half a box, and together the two cover one and a half boxes: a half over one and a half is a third. IoU falls faster than intuition suggests.
COCO average precision
ReadWithin each class, predictions are sorted by confidence and matched greedily to the unmatched labeled box with the largest IoU. Walking down the list gives a precision–recall curve; APCOCO average precision (AP)Area under the precision–recall curve of a detector, averaged over classes and over IoU thresholds 0.50 to 0.95. is the area under it (read at 101 recall points), averaged over classes and over ten IoU thresholds from 0.5 to 0.95.
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
COCO's interpolated precision at 101 recall points, up to the recall each class reaches.
View data
| label | Precision (interpolated) | Recall |
|---|---|---|
| person | 1 | 0 |
| person | 1 | 0.0100 |
| person | 1 | 0.0200 |
| person | 1 | 0.0300 |
| person | 1 | 0.0400 |
| person | 1 | 0.0500 |
| person | 1 | 0.0600 |
| person | 1 | 0.0700 |
| person | 1 | 0.0800 |
| person | 1 | 0.0900 |
| person | 1 | 0.1000 |
| person | 1 | 0.1100 |
| person | 1 | 0.1200 |
| person | 1 | 0.1300 |
| person | 1 | 0.1400 |
| person | 1 | 0.1500 |
| person | 1 | 0.1600 |
| person | 1 | 0.1700 |
| person | 1 | 0.1800 |
| person | 1 | 0.1900 |
| person | 1 | 0.2000 |
| person | 1 | 0.2100 |
| person | 1 | 0.2200 |
| person | 1 | 0.2300 |
| person | 1 | 0.2400 |
| person | 1 | 0.2500 |
| person | 1 | 0.2600 |
| person | 1 | 0.2700 |
| person | 1 | 0.2800 |
| person | 1 | 0.2900 |
| person | 1 | 0.3000 |
| person | 1 | 0.3100 |
| person | 1 | 0.3200 |
| person | 1 | 0.3300 |
| person | 1 | 0.3400 |
| person | 1 | 0.3500 |
| person | 1 | 0.3600 |
| person | 1 | 0.3700 |
| person | 1 | 0.3800 |
| person | 1 | 0.3900 |
| person | 1 | 0.4000 |
| person | 1 | 0.4100 |
| person | 1 | 0.4200 |
| person | 1 | 0.4300 |
| person | 1 | 0.4400 |
| person | 1 | 0.4500 |
| person | 1 | 0.4600 |
| person | 1 | 0.4700 |
| person | 1 | 0.4800 |
| person | 1 | 0.4900 |
| person | 1 | 0.5000 |
| person | 1 | 0.5100 |
| person | 1 | 0.5200 |
| person | 1 | 0.5300 |
| person | 1 | 0.5400 |
| person | 1 | 0.5500 |
| person | 1 | 0.5600 |
| person | 1 | 0.5700 |
| person | 1 | 0.5800 |
| person | 1 | 0.5900 |
First 60 of 184 rows.
View data
| label | Measure | Average precision |
|---|---|---|
| bicycle | AP | 0.3373 |
| bicycle | AP50 | 0.4323 |
| bicycle | AP75 | 0.4323 |
| car | AP | 0.5007 |
| car | AP50 | 0.5545 |
| car | AP75 | 0.5545 |
| person | AP | 0.5799 |
| person | AP50 | 0.6931 |
| person | AP75 | 0.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)
| Metric | IoU | Object size | Detections per image | Value |
|---|---|---|---|---|
| AP | 0.50:0.95 | all | 100 | 0.4726 |
| AP | 0.50 | all | 100 | 0.5600 |
| AP | 0.75 | all | 100 | 0.5600 |
| AP | 0.50:0.95 | small | 100 | 0.2472 |
| AP | 0.50:0.95 | medium | 100 | 0.7396 |
| AP | 0.50:0.95 | large | 100 | 0.4713 |
| AR | 0.50:0.95 | all | 1 | 0.3971 |
| AR | 0.50:0.95 | all | 10 | 0.5342 |
| AR | 0.50:0.95 | all | 100 | 0.5342 |
| AR | 0.50:0.95 | small | 100 | 0.2667 |
| AR | 0.50:0.95 | medium | 100 | 0.7619 |
| AR | 0.50:0.95 | large | 100 | 0.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)
| label | Reference objects | Crowd regions | Predictions | AP | AP50 | AP75 | AR@100 | True positives | False positives | Missed |
|---|---|---|---|---|---|---|---|---|---|---|
| bicycle | 7 | 0 | 10 | 0.3373 | 0.4323 | 0.4323 | 0.4714 | 4 | 6 | 3 |
| car | 9 | 0 | 9 | 0.5007 | 0.5545 | 0.5545 | 0.5111 | 5 | 4 | 4 |
| person | 10 | 1 | 15 | 0.5799 | 0.6931 | 0.6931 | 0.6200 | 7 | 6 | 3 |
Per image at IoU 0.50
| media_id | Reference objects | Predictions | True positives | False positives | Missed |
|---|---|---|---|---|---|
| img01 | 2 | 2 | 1 | 1 | 1 |
| img02 | 3 | 4 | 3 | 1 | 0 |
| img03 | 5 | 7 | 2 | 3 | 3 |
| img04 | 2 | 3 | 1 | 2 | 1 |
| img05 | 4 | 7 | 4 | 3 | 0 |
| img06 | 2 | 5 | 2 | 3 | 0 |
| img07 | 2 | 3 | 1 | 2 | 1 |
| img08 | 3 | 2 | 2 | 0 | 1 |
| img09 | 0 | 1 | 0 | 1 | 0 |
| img10 | 3 | 0 | 0 | 0 | 3 |
- 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
))
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)
| Metric | IoU | Object size | Detections per image | Value |
|---|---|---|---|---|
| AP | 0.50:0.95 | all | 100 | 0.4726 |
| AP | 0.50 | all | 100 | 0.5600 |
| AP | 0.75 | all | 100 | 0.5600 |
| AP | 0.50:0.95 | small | 100 | 0.2472 |
| AP | 0.50:0.95 | medium | 100 | 0.7396 |
| AP | 0.50:0.95 | large | 100 | 0.4713 |
| AR | 0.50:0.95 | all | 1 | 0.3971 |
| AR | 0.50:0.95 | all | 10 | 0.5342 |
| AR | 0.50:0.95 | all | 100 | 0.5342 |
| AR | 0.50:0.95 | small | 100 | 0.2667 |
| AR | 0.50:0.95 | medium | 100 | 0.7619 |
| AR | 0.50:0.95 | large | 100 | 0.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)
| label | Reference objects | Crowd regions | Predictions | AP | AP50 | AP75 | AR@100 | True positives | False positives | Missed |
|---|---|---|---|---|---|---|---|---|---|---|
| bicycle | 7 | 0 | 10 | 0.3373 | 0.4323 | 0.4323 | 0.4714 | 4 | 6 | 3 |
| car | 9 | 0 | 9 | 0.5007 | 0.5545 | 0.5545 | 0.5111 | 5 | 4 | 4 |
| person | 10 | 1 | 15 | 0.5799 | 0.6931 | 0.6931 | 0.6200 | 7 | 6 | 3 |
Per image at IoU 0.50
| media_id | Reference objects | Predictions | True positives | False positives | Missed |
|---|---|---|---|---|---|
| img01 | 2 | 2 | 1 | 1 | 1 |
| img02 | 3 | 4 | 3 | 1 | 0 |
| img03 | 5 | 7 | 2 | 3 | 3 |
| img04 | 2 | 3 | 1 | 2 | 1 |
| img05 | 4 | 7 | 4 | 3 | 0 |
| img06 | 2 | 5 | 2 | 3 | 0 |
| img07 | 2 | 3 | 1 | 2 | 1 |
| img08 | 3 | 2 | 2 | 0 | 1 |
| img09 | 0 | 1 | 0 | 1 | 0 |
| img10 | 3 | 0 | 0 | 0 | 3 |
- 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,
})
Here AP = 0.473, with AP50 and AP75AP50 and AP75Average precision when a box must overlap its object by at least 50% (AP50) or 75% (AP75) IoU. of 0.560 and 0.560. At IoU 0.5 the model had 16 true positives, 16 false positives and missed 10 objects.
Size, recall and crowds
Read- AP by size splits objects into small (under 32 × 32 px), medium and large. Small objects are nearly always the weak spot.
- Average recallAverage recall at k detections (AR)Share of labeled objects found when only each image's top k detections count, averaged over IoU 0.50 to 0.95. at 1, 10 and 100 detections per image asks: if only the top k boxes per image count, how many objects are found?
- A crowd regionCrowd regionA labeled area that holds many objects at once; predictions inside it are neither rewarded nor counted as false positives. marks a dense group labeled as one area; boxes inside it are neither rewarded nor penalized.
Masks: the same idea on pixels
ReadFor instance masks, IoU counts pixels instead of box area, and the same AP machinery applies:
Across 10 images and 3 classes, AP (IoU 0.50:0.95) = 0.469, AP50 = 0.560 and AP75 = 0.560; average recall with up to 100 detections per image = 0.528. At IoU 0.50: 16 true positives, 16 false positives, 10 missed objects.
- AP (0.50:0.95)
- 0.4689
- AP50
- 0.5600
- AP75
- 0.5600
- AR@100
- 0.5280
Plots
COCO's interpolated precision at 101 recall points, up to the recall each class reaches.
View data
| label | Precision (interpolated) | Recall |
|---|---|---|
| person | 1 | 0 |
| person | 1 | 0.0100 |
| person | 1 | 0.0200 |
| person | 1 | 0.0300 |
| person | 1 | 0.0400 |
| person | 1 | 0.0500 |
| person | 1 | 0.0600 |
| person | 1 | 0.0700 |
| person | 1 | 0.0800 |
| person | 1 | 0.0900 |
| person | 1 | 0.1000 |
| person | 1 | 0.1100 |
| person | 1 | 0.1200 |
| person | 1 | 0.1300 |
| person | 1 | 0.1400 |
| person | 1 | 0.1500 |
| person | 1 | 0.1600 |
| person | 1 | 0.1700 |
| person | 1 | 0.1800 |
| person | 1 | 0.1900 |
| person | 1 | 0.2000 |
| person | 1 | 0.2100 |
| person | 1 | 0.2200 |
| person | 1 | 0.2300 |
| person | 1 | 0.2400 |
| person | 1 | 0.2500 |
| person | 1 | 0.2600 |
| person | 1 | 0.2700 |
| person | 1 | 0.2800 |
| person | 1 | 0.2900 |
| person | 1 | 0.3000 |
| person | 1 | 0.3100 |
| person | 1 | 0.3200 |
| person | 1 | 0.3300 |
| person | 1 | 0.3400 |
| person | 1 | 0.3500 |
| person | 1 | 0.3600 |
| person | 1 | 0.3700 |
| person | 1 | 0.3800 |
| person | 1 | 0.3900 |
| person | 1 | 0.4000 |
| person | 1 | 0.4100 |
| person | 1 | 0.4200 |
| person | 1 | 0.4300 |
| person | 1 | 0.4400 |
| person | 1 | 0.4500 |
| person | 1 | 0.4600 |
| person | 1 | 0.4700 |
| person | 1 | 0.4800 |
| person | 1 | 0.4900 |
| person | 1 | 0.5000 |
| person | 1 | 0.5100 |
| person | 1 | 0.5200 |
| person | 1 | 0.5300 |
| person | 1 | 0.5400 |
| person | 1 | 0.5500 |
| person | 1 | 0.5600 |
| person | 1 | 0.5700 |
| person | 1 | 0.5800 |
| person | 1 | 0.5900 |
First 60 of 184 rows.
View data
| label | Measure | Average precision |
|---|---|---|
| bicycle | AP | 0.3198 |
| bicycle | AP50 | 0.4323 |
| bicycle | AP75 | 0.4323 |
| car | AP | 0.5007 |
| car | AP50 | 0.5545 |
| car | AP75 | 0.5545 |
| person | AP | 0.5861 |
| person | AP50 | 0.6931 |
| person | AP75 | 0.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 (masks)
| Metric | IoU | Object size | Detections per image | Value |
|---|---|---|---|---|
| AP | 0.50:0.95 | all | 100 | 0.4689 |
| AP | 0.50 | all | 100 | 0.5600 |
| AP | 0.75 | all | 100 | 0.5600 |
| AP | 0.50:0.95 | small | 100 | 0.2406 |
| AP | 0.50:0.95 | medium | 100 | 0.6283 |
| AP | 0.50:0.95 | large | 100 | 0.4713 |
| AR | 0.50:0.95 | all | 1 | 0.3910 |
| AR | 0.50:0.95 | all | 10 | 0.5280 |
| AR | 0.50:0.95 | all | 100 | 0.5280 |
| AR | 0.50:0.95 | small | 100 | 0.2567 |
| AR | 0.50:0.95 | medium | 100 | 0.7500 |
| AR | 0.50:0.95 | large | 100 | 0.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)
| label | Reference objects | Crowd regions | Predictions | AP | AP50 | AP75 | AR@100 | True positives | False positives | Missed |
|---|---|---|---|---|---|---|---|---|---|---|
| bicycle | 7 | 0 | 10 | 0.3198 | 0.4323 | 0.4323 | 0.4429 | 4 | 6 | 3 |
| car | 9 | 0 | 9 | 0.5007 | 0.5545 | 0.5545 | 0.5111 | 5 | 4 | 4 |
| person | 10 | 1 | 15 | 0.5861 | 0.6931 | 0.6931 | 0.6300 | 7 | 6 | 3 |
Per image at IoU 0.50
| media_id | Reference objects | Predictions | True positives | False positives | Missed |
|---|---|---|---|---|---|
| img01 | 2 | 2 | 1 | 1 | 1 |
| img02 | 3 | 4 | 3 | 1 | 0 |
| img03 | 5 | 7 | 2 | 3 | 3 |
| img04 | 2 | 3 | 1 | 2 | 1 |
| img05 | 4 | 7 | 4 | 3 | 0 |
| img06 | 2 | 5 | 2 | 3 | 0 |
| img07 | 2 | 3 | 1 | 2 | 1 |
| img08 | 3 | 2 | 2 | 0 | 1 |
| img09 | 0 | 1 | 0 | 1 | 0 |
| img10 | 3 | 0 | 0 | 0 | 3 |
- 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 def6d2850e007c67
# 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 <- "mask_rle"
WIDTH <- "image_width"
HEIGHT <- "image_height"
IOU_TYPE <- "segm" # 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/masks-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
))
Across 10 images and 3 classes, AP (IoU 0.50:0.95) = 0.469, AP50 = 0.560 and AP75 = 0.560; average recall with up to 100 detections per image = 0.528. At IoU 0.50: 16 true positives, 16 false positives, 10 missed objects.
- AP (0.50:0.95)
- 0.4689
- AP50
- 0.5600
- AP75
- 0.5600
- AR@100
- 0.5280
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 (masks)
| Metric | IoU | Object size | Detections per image | Value |
|---|---|---|---|---|
| AP | 0.50:0.95 | all | 100 | 0.4689 |
| AP | 0.50 | all | 100 | 0.5600 |
| AP | 0.75 | all | 100 | 0.5600 |
| AP | 0.50:0.95 | small | 100 | 0.2406 |
| AP | 0.50:0.95 | medium | 100 | 0.6283 |
| AP | 0.50:0.95 | large | 100 | 0.4713 |
| AR | 0.50:0.95 | all | 1 | 0.3910 |
| AR | 0.50:0.95 | all | 10 | 0.5280 |
| AR | 0.50:0.95 | all | 100 | 0.5280 |
| AR | 0.50:0.95 | small | 100 | 0.2567 |
| AR | 0.50:0.95 | medium | 100 | 0.7500 |
| AR | 0.50:0.95 | large | 100 | 0.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)
| label | Reference objects | Crowd regions | Predictions | AP | AP50 | AP75 | AR@100 | True positives | False positives | Missed |
|---|---|---|---|---|---|---|---|---|---|---|
| bicycle | 7 | 0 | 10 | 0.3198 | 0.4323 | 0.4323 | 0.4429 | 4 | 6 | 3 |
| car | 9 | 0 | 9 | 0.5007 | 0.5545 | 0.5545 | 0.5111 | 5 | 4 | 4 |
| person | 10 | 1 | 15 | 0.5861 | 0.6931 | 0.6931 | 0.6300 | 7 | 6 | 3 |
Per image at IoU 0.50
| media_id | Reference objects | Predictions | True positives | False positives | Missed |
|---|---|---|---|---|---|
| img01 | 2 | 2 | 1 | 1 | 1 |
| img02 | 3 | 4 | 3 | 1 | 0 |
| img03 | 5 | 7 | 2 | 3 | 3 |
| img04 | 2 | 3 | 1 | 2 | 1 |
| img05 | 4 | 7 | 4 | 3 | 0 |
| img06 | 2 | 5 | 2 | 3 | 0 |
| img07 | 2 | 3 | 1 | 2 | 1 |
| img08 | 3 | 2 | 2 | 0 | 1 |
| img09 | 0 | 1 | 0 | 1 | 0 |
| img10 | 3 | 0 | 0 | 0 | 3 |
- 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 def6d2850e007c67
# 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 = "mask_rle"
WIDTH = "image_width"
HEIGHT = "image_height"
IOU_TYPE = "segm" # 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/masks-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,
})
Mask AP = 0.469 here. For semantic segmentation, where every pixel gets a class and there are no confidence scores, score pixel overlap per class instead:
Across 10 images and 5 classes, mean IoU = 0.495, mean Dice = 0.598 and pixel accuracy = 0.773.
- Mean IoU
- 0.4946
- Mean Dice
- 0.5977
- Pixel accuracy
- 0.7735
Plots
View data
| label | Measure | Overlap |
|---|---|---|
| bicycle | IoU | 0.4855 |
| bicycle | Dice | 0.6537 |
| car | IoU | 0.3877 |
| car | Dice | 0.5588 |
| dog | IoU | 0 |
| dog | Dice | 0 |
| person | IoU | 0.8472 |
| person | Dice | 0.9173 |
| (background) | IoU | 0.7525 |
| (background) | Dice | 0.8588 |
Assumptions
- The reference is complete — Regions or segments missing from the reference turn correct predictions into errors.
- Reference classes don't overlap — Where reference regions of two classes overlap, the shared part counts for both; accuracy then divides by more than the scored area.
Per class (pixels summed over images)
| label | Reference pixels | Predicted pixels | Overlap (pixels) | IoU | Dice |
|---|---|---|---|---|---|
| bicycle | 9,844 | 14,196 | 7,857 | 0.4855 | 0.6537 |
| car | 59,682 | 26,067 | 23,959 | 0.3877 | 0.5588 |
| dog | 0 | 3,012 | 0 | 0 | 0 |
| person | 33,581 | 30,231 | 29,266 | 0.8472 | 0.9173 |
| (background) | 102,433 | 125,542 | 97,893 | 0.7525 | 0.8588 |
Mean IoU per image
| media_id | Mean IoU |
|---|---|
| img01 | 0.5896 |
| img02 | 0.6133 |
| img03 | 0.3908 |
| img04 | 0.3639 |
| img05 | 0.6776 |
| img06 | 0.6747 |
| img07 | 0.4281 |
| img08 | 0.8811 |
| img09 | 0.4880 |
| img10 | 0.1023 |
- Reference rows: source = annotation; predictions: source = prediction. Masks are compared on their run lengths (no pixels decoded); unlabeled pixels form a background class; crowd regions are left out of scoring.
The exact R script · R R version 4.5.1 (2025-06-13)
# Segmentation quality (IoU, Dice, segment F1)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method evaluate.segments 1.1.0 · spec a232974b1dc8e926
# 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_seg_* (segmentation scores), cs_eval_det_runs, cs_eval_stacked, cs_rle_* (COCO RLE)
# %% Data
GROUP <- "media_id"
FRAME <- NULL
LABEL <- "label"
SOURCE <- "source"
MASK <- "mask_rle"
WIDTH <- "image_width"
HEIGHT <- "image_height"
CROWD <- "iscrowd"
START <- NULL
END <- NULL
SCORE <- NULL
KIND <- "masks" # masks | intervals
BACKGROUND <- TRUE
THRESHOLDS <- as.numeric(unlist(c(0.1, 0.25, 0.5)))
if (!length(THRESHOLDS)) THRESHOLDS <- 0.5
THRESHOLDS <- sort(unique(THRESHOLDS))
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(GROUP, FRAME, LABEL, SOURCE, MASK, WIDTH, HEIGHT, CROWD, START, END, SCORE))
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/img4_boxes.parquet", col_select = columns))
if (KIND == "masks" && (is.null(MASK) || is.null(WIDTH) || is.null(HEIGHT))) {
cs_error("CS_E_INVALID_OPTION", option = "Segments are", allowed = "time intervals unless the mask, width and height columns are set", value = "masks")
}
if (KIND == "intervals" && (is.null(START) || is.null(END))) {
cs_error("CS_E_INVALID_OPTION", option = "Segments are", allowed = "masks unless the start and end columns are set", value = "time intervals")
}
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.segments/masks-background-crowd/out-r", "reference_table"),
list(group = GROUP, frame = FRAME, label = LABEL, mask = MASK, width = WIDTH, height = HEIGHT, crowd = CROWD,
start = START, end = END, score = SCORE), REF_ROLES,
c(list(frame = "Frame"), if (KIND == "masks") list(mask = "Mask", width = "Image width", height = "Image height") else list(start = "Start", end = "End")),
SOURCE, REF_LEVEL, c("group", "label", if (KIND == "masks") c("mask", "width", "height") else c("start", "end")))
df <- w$df
pre_warnings <- w$warnings
wc <- w$columns
GROUP <- wc$group; FRAME <- wc$frame; LABEL <- wc$label; MASK <- wc$mask; WIDTH <- wc$width; HEIGHT <- wc$height
CROWD <- wc$crowd; START <- wc$start; END <- wc$end
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(GROUP, LABEL, SOURCE, if (KIND == "masks") c(MASK, WIDTH, HEIGHT) else c(START, END))
numeric_cols <- if (KIND == "masks") c(WIDTH, HEIGHT) else c(START, END, SCORE)
st <- cs_eval_stacked(df, needed, numeric_cols, SOURCE, REF_LEVEL, SOURCE_LEVELS)
df <- st$df
is_ref <- st$is_ref
warnings <- c(pre_warnings, st$warnings)
if (sum(is_ref) == 0L || sum(!is_ref) == 0L) cs_error("CS_E_GROUP_COUNT", column = SOURCE, expected = 2, k = 1)
labels_all <- as.character(df[[LABEL]])
crowd <- if (!is.null(CROWD) && KIND == "masks") cs_eval_flags(df[[CROWD]]) else logical(nrow(df))
crowd[!is_ref] <- FALSE
classes <- sort(unique(labels_all[!crowd]), method = "radix")
if (KIND == "masks") {
# %% Masks -> runs, per image
ik <- cs_eval_image_keys(df[[GROUP]], if (!is.null(FRAME)) df[[FRAME]] else NULL)
img_idx <- ik$index
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)
ims <- lapply(seq_along(ik$media), function(i) list(n = NULL, size = NULL, ref = list(), pred = list(), void = list()))
for (i in seq_along(runs)) {
q <- img_idx[i] + 1L
r <- runs[[i]]
if (is.null(ims[[q]]$n)) {
ims[[q]]$n <- as.numeric(r$size[1]) * as.numeric(r$size[2])
ims[[q]]$size <- r$size
} else if (!identical(ims[[q]]$size, r$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)
}
rr <- list(s = r$s, e = r$e)
if (crowd[i]) {
ims[[q]]$void[[length(ims[[q]]$void) + 1L]] <- rr
} else if (is_ref[i]) {
lab <- labels_all[i]
ims[[q]]$ref[[lab]] <- c(if (is.null(ims[[q]]$ref[[lab]])) list() else ims[[q]]$ref[[lab]], list(rr))
} else {
lab <- labels_all[i]
ims[[q]]$pred[[lab]] <- c(if (is.null(ims[[q]]$pred[[lab]])) list() else ims[[q]]$pred[[lab]], list(rr))
}
}
res <- cs_eval_seg_masks(ims, classes, BACKGROUND)
names_ <- res$classes
n_ref <- sum(is_ref & !crowd)
n_pred <- sum(!is_ref)
unit <- "pixels"
group_rows <- lapply(seq_along(ik$media), function(i) list(group = ik$media[i], frame = if (is.infinite(ik$frame[i])) NA_real_ else ik$frame[i],
miou = if (is.null(res$per_image[[i]])) NA_real_ else res$per_image[[i]]))
n_groups <- length(ik$media)
has_score <- FALSE
} else {
# %% Intervals per recording
s_all <- as.numeric(df[[START]])
e_all <- as.numeric(df[[END]])
bad <- e_all < s_all
if (any(bad)) cs_error("CS_E_INVALID_VALUES", column = END, requirement = sprintf("at least %s", START), count = sum(bad))
sc_all <- if (!is.null(SCORE)) as.numeric(df[[SCORE]]) else rep(NA_real_, nrow(df))
has_score <- !is.null(SCORE)
if (has_score) {
miss <- !is_ref & is.na(sc_all)
if (any(miss)) {
warnings <- c(warnings, sprintf("%d predicted segments have no %s and were left out.", sum(miss), SCORE))
keep <- !miss
df <- df[keep, , drop = FALSE]; is_ref <- is_ref[keep]; labels_all <- labels_all[keep]
s_all <- s_all[keep]; e_all <- e_all[keep]; sc_all <- sc_all[keep]
classes <- sort(unique(labels_all), method = "radix")
}
}
grp <- as.character(df[[GROUP]])
groups <- sort(unique(grp), method = "radix")
recs <- lapply(groups, function(g) {
rows <- which(grp == g)
rr <- rows[is_ref[rows]]
pr <- rows[!is_ref[rows]]
list(ref = data.frame(start = s_all[rr], end = e_all[rr], label = labels_all[rr], stringsAsFactors = FALSE),
pred = data.frame(start = s_all[pr], end = e_all[pr], label = labels_all[pr], score = if (has_score) sc_all[pr] else rep(0, length(pr)),
row = pr - 1L, stringsAsFactors = FALSE))
})
res <- cs_eval_seg_intervals(recs, classes, THRESHOLDS, has_score)
names_ <- res$classes
n_ref <- res$n_ref
n_pred <- res$n_pred
unit <- "seconds"
n_groups <- length(groups)
}
# %% Assumptions
assumptions <- list(
list(key = "complete", label = "The reference is complete", status = "info",
detail = "Regions or segments missing from the reference turn correct predictions into errors."),
list(key = "overlap", label = "Reference classes don't overlap", status = "info",
detail = "Where reference regions of two classes overlap, the shared part counts for both; accuracy then divides by more than the scored area.")
)
# %% Result
f3 <- function(v) if (is.null(v) || is.na(v)) "—" else sprintf("%.3f", v)
tkey <- function(t) sprintf("%g", t)
values <- list(kind = KIND, n_groups = n_groups, n_classes = length(names_), n_reference = n_ref, n_predictions = n_pred,
accuracy = res$accuracy, miou = res$miou, mean_dice = res$mean_dice, fw_iou = res$fw_iou,
scored = if (!is.null(res$scored)) res$scored else sum(res$gsum), ignored = if (!is.null(res$ignored)) res$ignored else NA_real_,
map = NA_real_)
for (j in seq_along(names_)) {
values[[sprintf("iou[%s]", names_[j])]] <- res$iou[j]
values[[sprintf("dice[%s]", names_[j])]] <- res$dice[j]
}
cls_cols <- list(list(key = "class", label = LABEL, type = "string"), list(key = "ref", label = sprintf("Reference %s", unit), type = "number"),
list(key = "pred", label = sprintf("Predicted %s", unit), type = "number"), list(key = "inter", label = sprintf("Overlap (%s)", unit), type = "number"),
list(key = "iou", label = "IoU", type = "number"), list(key = "dice", label = "Dice", type = "number"))
cls_rows <- lapply(seq_along(names_), function(j) list(class = names_[j], ref = res$gsum[j], pred = res$psum[j], inter = res$inter[j],
iou = res$iou[j], dice = res$dice[j]))
tables <- list()
charts <- list()
if (KIND == "intervals") {
m_rows <- res$matching
for (r in m_rows) {
values[[sprintf("f1[%s]", tkey(r$threshold))]] <- r$f1
values[[sprintf("precision[%s]", tkey(r$threshold))]] <- r$precision
values[[sprintf("recall[%s]", tkey(r$threshold))]] <- r$recall
if (has_score) values[[sprintf("ap[%s]", tkey(r$threshold))]] <- r$map
}
if (has_score) {
maps <- vapply(m_rows, function(r) r$map, numeric(1))
maps <- maps[!is.na(maps)]
values$map <- if (length(maps)) mean(maps) else NA_real_
for (r in m_rows) {
key <- sprintf("ap_%s", tkey(r$threshold))
cls_cols[[length(cls_cols) + 1L]] <- list(key = key, label = sprintf("AP@%s", tkey(r$threshold)), type = "number")
for (j in seq_along(cls_rows)) cls_rows[[j]][[key]] <- if (is.null(r$ap[[cls_rows[[j]]$class]])) NA_real_ else r$ap[[cls_rows[[j]]$class]]
}
}
tables[[length(tables) + 1L]] <- list(key = "classes", title = "Per class (time overlap)", columns = cls_cols, rows = cls_rows)
mcols <- list(list(key = "threshold", label = "IoU threshold", type = "number"), list(key = "tp", label = "Matched", type = "integer"),
list(key = "fp", label = "False alarms", type = "integer"), list(key = "fn", label = "Missed", type = "integer"),
list(key = "precision", label = "Precision", type = "number"), list(key = "recall", label = "Recall", type = "number"),
list(key = "f1", label = "F1", type = "number"))
if (has_score) mcols[[length(mcols) + 1L]] <- list(key = "map", label = "mAP", type = "number")
tables[[length(tables) + 1L]] <- list(key = "matching", title = "Segments matched at each IoU threshold", columns = mcols,
rows = lapply(m_rows, function(r) r[c("threshold", "tp", "fp", "fn", "precision", "recall", "f1", "map")]))
pc <- character(0); pm <- character(0); pv <- numeric(0)
for (r in m_rows) for (km in list(c("f1", "F1"), c("precision", "Precision"), c("recall", "Recall"))) if (!is.na(r[[km[1]]])) {
pc <- c(pc, sprintf("IoU %s", tkey(r$threshold))); pm <- c(pm, km[2]); pv <- c(pv, r[[km[1]]])
}
if (length(pv)) {
charts[[length(charts) + 1L]] <- cs_chart("f1-at-iou", "cleveland-dot", "Segment F1, precision and recall by IoU threshold", list(
category = cs_col("IoU threshold", pc, "categorical", levels = vapply(m_rows, function(r) sprintf("IoU %s", tkey(r$threshold)), character(1))),
value = cs_col("Share", pv, "numeric"),
group = cs_col("Measure", pm, "categorical", levels = c("F1", "Precision", "Recall"))))
}
} else {
tables[[length(tables) + 1L]] <- list(key = "classes", title = "Per class (pixels summed over images)", columns = cls_cols, rows = cls_rows)
tables[[length(tables) + 1L]] <- list(key = "images", title = "Mean IoU per image", rows = utils::head(group_rows, 500),
columns = c(list(list(key = "group", label = GROUP, type = "string")), if (!is.null(FRAME)) list(list(key = "frame", label = FRAME, type = "number")),
list(list(key = "miou", label = "Mean IoU", type = "number"))),
note = if (length(group_rows) > 500) "First 500 images." else NULL)
}
dc <- character(0); dm <- character(0); dv <- numeric(0)
for (j in seq_along(names_)) for (km in list(c("iou", "IoU"), c("dice", "Dice"))) if (!is.na(res[[km[1]]][j])) {
dc <- c(dc, names_[j]); dm <- c(dm, km[2]); dv <- c(dv, res[[km[1]]][j])
}
if (length(dv)) {
charts <- c(list(cs_chart("by-class", "cleveland-dot", "IoU and Dice by class", list(
category = cs_col(LABEL, dc, "categorical", levels = names_), value = cs_col("Overlap", dv, "numeric"),
group = cs_col("Measure", dm, "categorical", levels = c("IoU", "Dice"))))), charts)
}
what <- if (KIND == "masks") "pixel accuracy" else "time-weighted accuracy"
summary <- sprintf("Across %d %s and %d classes, mean IoU = %s, mean Dice = %s and %s = %s.", n_groups, if (KIND == "masks") "images" else "recordings",
length(names_), f3(res$miou), f3(res$mean_dice), what, f3(res$accuracy))
if (KIND == "intervals") {
summary <- paste0(summary, " Segment F1: ", paste(vapply(res$matching, function(r) sprintf("%s at IoU %s", f3(r$f1), tkey(r$threshold)), character(1)), collapse = ", "), ".")
if (has_score && !is.na(values$map)) summary <- paste0(summary, sprintf(" mAP over the thresholds = %s.", f3(values$map)))
}
cs_publish(list(
method = "evaluate.segments",
methodVersion = "1.1.0",
title = "Segmentation quality",
engine = cs_engine_info("nanoparquet"),
n = nrow(df),
summary = summary,
statistics = list(list(key = "miou", label = "Mean IoU", value = res$miou), list(key = "mean_dice", label = "Mean Dice", value = res$mean_dice),
list(key = "accuracy", label = if (KIND == "masks") "Pixel accuracy" else "Time-weighted accuracy", value = res$accuracy)),
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 (KIND == "masks") paste0("Masks are compared on their run lengths (no pixels decoded)", if (BACKGROUND) "; unlabeled pixels form a background class" else "",
if (!is.null(CROWD)) "; crowd regions are left out of scoring" else "", ".")
else paste0("Segments match within a recording and class, ", if (!is.null(SCORE)) "highest score first." else "earliest first."))),
charts = charts,
values = values
))
Across 10 images and 5 classes, mean IoU = 0.495, mean Dice = 0.598 and pixel accuracy = 0.773.
- Mean IoU
- 0.4946
- Mean Dice
- 0.5977
- Pixel accuracy
- 0.7735
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- The reference is complete — Regions or segments missing from the reference turn correct predictions into errors.
- Reference classes don't overlap — Where reference regions of two classes overlap, the shared part counts for both; accuracy then divides by more than the scored area.
Per class (pixels summed over images)
| label | Reference pixels | Predicted pixels | Overlap (pixels) | IoU | Dice |
|---|---|---|---|---|---|
| bicycle | 9,844 | 14,196 | 7,857 | 0.4855 | 0.6537 |
| car | 59,682 | 26,067 | 23,959 | 0.3877 | 0.5588 |
| dog | 0 | 3,012 | 0 | 0 | 0 |
| person | 33,581 | 30,231 | 29,266 | 0.8472 | 0.9173 |
| (background) | 102,433 | 125,542 | 97,893 | 0.7525 | 0.8588 |
Mean IoU per image
| media_id | Mean IoU |
|---|---|
| img01 | 0.5896 |
| img02 | 0.6133 |
| img03 | 0.3908 |
| img04 | 0.3639 |
| img05 | 0.6776 |
| img06 | 0.6747 |
| img07 | 0.4281 |
| img08 | 0.8811 |
| img09 | 0.4880 |
| img10 | 0.1023 |
- Reference rows: source = annotation; predictions: source = prediction. Masks are compared on their run lengths (no pixels decoded); unlabeled pixels form a background class; crowd regions are left out of scoring.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Segmentation quality (IoU, Dice, segment F1)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method evaluate.segments 1.1.0 · spec a232974b1dc8e926
# 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 # RLE runs (twin: cs_eval_det_runs)
from codesplash.evaluate import segmentation as seg # twin: codesplashr cs_eval_seg_*
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
GROUP = "media_id"
FRAME = None
LABEL = "label"
SOURCE = "source"
MASK = "mask_rle"
WIDTH = "image_width"
HEIGHT = "image_height"
CROWD = "iscrowd"
START = None
END = None
SCORE = None
KIND = "masks" # masks | intervals
BACKGROUND = True
THRESHOLDS = [float(t) for t in [0.1, 0.25, 0.5]] or [0.5]
THRESHOLDS = sorted(set(THRESHOLDS))
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 [GROUP, FRAME, LABEL, SOURCE, MASK, WIDTH, HEIGHT, CROWD, START, END, SCORE] if c))
df = pd.read_parquet("tests/parity/fixtures/img4_boxes.parquet", columns=columns)
if KIND == "masks" and not (MASK and WIDTH and HEIGHT):
cs.cs_error("CS_E_INVALID_OPTION", option="Segments are", allowed="time intervals unless the mask, width and height columns are set", value="masks")
if KIND == "intervals" and not (START and END):
cs.cs_error("CS_E_INVALID_OPTION", option="Segments are", allowed="masks unless the start and end columns are set", value="time intervals")
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.segments/masks-background-crowd/out-python", "reference_table"),
{"group": GROUP, "frame": FRAME, "label": LABEL, "mask": MASK, "width": WIDTH, "height": HEIGHT, "crowd": CROWD,
"start": START, "end": END, "score": SCORE}, REF_ROLES,
{"frame": "Frame", **({"mask": "Mask", "width": "Image width", "height": "Image height"} if KIND == "masks" else {"start": "Start", "end": "End"})},
SOURCE, REF_LEVEL, ["group", "label"] + (["mask", "width", "height"] if KIND == "masks" else ["start", "end"]))
df, pre_warnings, wc = w["df"], w["warnings"], w["columns"]
GROUP, FRAME, LABEL, MASK, WIDTH, HEIGHT = wc["group"], wc["frame"], wc["label"], wc["mask"], wc["width"], wc["height"]
CROWD, START, END = wc["crowd"], wc["start"], wc["end"]
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 = [GROUP, LABEL, SOURCE] + ([MASK, WIDTH, HEIGHT] if KIND == "masks" else [START, END])
numeric = [WIDTH, HEIGHT] if KIND == "masks" else [c for c in [START, END, SCORE] if c]
st = stacked(df, needed, numeric, SOURCE, REF_LEVEL, SOURCE_LEVELS)
df, is_ref, warnings = st["df"], st["is_ref"], pre_warnings + st["warnings"]
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)
labels_all = np.asarray([str(x) for x in df[LABEL].tolist()], dtype=object)
crowd = flags(df[CROWD]) if (CROWD and KIND == "masks") else np.zeros(len(df), dtype=bool)
crowd[~is_ref] = False
classes = sorted(set(labels_all[~crowd].tolist()))
if KIND == "masks":
# %% Masks → runs, per image
img_idx, images = image_keys(df[GROUP], df[FRAME] if FRAME else None)
ws, hs = df[WIDTH].to_numpy(dtype=float), df[HEIGHT].to_numpy(dtype=float)
runs, n_bad = [], 0
for s, w, h in zip(df[MASK].tolist(), ws, hs):
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)
ims = [{"n": None, "ref": {}, "pred": {}, "void": []} for _ in images]
for i, r in enumerate(runs):
im = ims[int(img_idx[i])]
n = float(r[2][0]) * float(r[2][1])
if im["n"] is None:
im["n"], im["size"] = n, r[2]
elif im["size"] != 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)
if crowd[i]:
im["void"].append(r[:2])
else:
side = im["ref"] if is_ref[i] else im["pred"]
side.setdefault(labels_all[i], []).append(r[:2])
res = seg.mask_scores(ims, classes, BACKGROUND)
names = res["classes"]
n_ref = int(np.sum(is_ref & ~crowd))
n_pred = int(np.sum(~is_ref))
unit = "pixels"
group_rows = [{"group": m, "frame": None if f == float("-inf") else f, "miou": res["per_image"][i]} for i, (m, f) in enumerate(images)]
n_groups = len(images)
else:
# %% Intervals per recording
s_all, e_all = df[START].to_numpy(dtype=float), df[END].to_numpy(dtype=float)
bad = e_all < s_all
if bad.any():
cs.cs_error("CS_E_INVALID_VALUES", column=END, requirement=f"at least {START}", count=int(bad.sum()))
sc_all = df[SCORE].to_numpy(dtype=float, na_value=np.nan) if SCORE else np.full(len(df), np.nan)
has_score = SCORE is not None
if has_score:
miss = ~is_ref & np.isnan(sc_all)
if miss.any():
warnings.append(f"{int(miss.sum())} predicted segments have no {SCORE} and were left out.")
keep = ~miss
df, is_ref, labels_all, s_all, e_all, sc_all = df.loc[keep].reset_index(drop=True), is_ref[keep], labels_all[keep], s_all[keep], e_all[keep], sc_all[keep]
classes = sorted(set(labels_all.tolist()))
grp = np.asarray([str(x) for x in df[GROUP].tolist()], dtype=object)
groups = sorted(set(grp.tolist()))
recs = []
for g in groups:
rows = np.flatnonzero(grp == g)
recs.append({"ref": [(s_all[i], e_all[i], labels_all[i]) for i in rows if is_ref[i]],
"pred": [(s_all[i], e_all[i], labels_all[i], float(sc_all[i]) if has_score else 0.0, int(i)) for i in rows if not is_ref[i]]})
res = seg.interval_scores(recs, classes, THRESHOLDS, has_score)
names = res["classes"]
n_ref, n_pred = res["n_ref"], res["n_pred"]
unit = "seconds"
n_groups = len(groups)
# %% Assumptions
assumptions = [
{"key": "complete", "label": "The reference is complete", "status": "info",
"detail": "Regions or segments missing from the reference turn correct predictions into errors."},
{"key": "overlap", "label": "Reference classes don't overlap", "status": "info",
"detail": "Where reference regions of two classes overlap, the shared part counts for both; accuracy then divides by more than the scored area."},
]
# %% Result
f3 = lambda v: "—" if v is None else f"{v:.3f}"
tkey = lambda t: "%g" % t
values = {"kind": KIND, "n_groups": n_groups, "n_classes": len(names), "n_reference": n_ref, "n_predictions": n_pred,
"accuracy": res["accuracy"], "miou": res["miou"], "mean_dice": res["mean_dice"], "fw_iou": res["fw_iou"],
"scored": res.get("scored", float(np.sum(res["gsum"]))), "ignored": res.get("ignored"), "map": None}
for j, c in enumerate(names):
values[f"iou[{c}]"] = res["iou"][j]
values[f"dice[{c}]"] = res["dice"][j]
cls_cols = [{"key": "class", "label": LABEL, "type": "string"}, {"key": "ref", "label": f"Reference {unit}", "type": "number"},
{"key": "pred", "label": f"Predicted {unit}", "type": "number"}, {"key": "inter", "label": f"Overlap ({unit})", "type": "number"},
{"key": "iou", "label": "IoU", "type": "number"}, {"key": "dice", "label": "Dice", "type": "number"}]
cls_rows = [{"class": c, "ref": float(res["gsum"][j]), "pred": float(res["psum"][j]), "inter": float(res["inter"][j]),
"iou": res["iou"][j], "dice": res["dice"][j]} for j, c in enumerate(names)]
tables = []
charts = []
if KIND == "intervals":
m_rows = res["matching"]
for r in m_rows:
values[f"f1[{tkey(r['threshold'])}]"] = r["f1"]
values[f"precision[{tkey(r['threshold'])}]"] = r["precision"]
values[f"recall[{tkey(r['threshold'])}]"] = r["recall"]
if has_score:
values[f"ap[{tkey(r['threshold'])}]"] = r["map"]
if has_score:
maps = [r["map"] for r in m_rows if r["map"] is not None]
values["map"] = float(np.mean(maps)) if maps else None
for r in m_rows:
cls_cols.append({"key": f"ap_{tkey(r['threshold'])}", "label": f"AP@{tkey(r['threshold'])}", "type": "number"})
for row in cls_rows:
row[f"ap_{tkey(r['threshold'])}"] = r["ap"].get(row["class"])
tables.append({"key": "classes", "title": "Per class (time overlap)", "columns": cls_cols, "rows": cls_rows})
tables.append({"key": "matching", "title": "Segments matched at each IoU threshold",
"columns": [{"key": "threshold", "label": "IoU threshold", "type": "number"}, {"key": "tp", "label": "Matched", "type": "integer"},
{"key": "fp", "label": "False alarms", "type": "integer"}, {"key": "fn", "label": "Missed", "type": "integer"},
{"key": "precision", "label": "Precision", "type": "number"}, {"key": "recall", "label": "Recall", "type": "number"},
{"key": "f1", "label": "F1", "type": "number"}] + ([{"key": "map", "label": "mAP", "type": "number"}] if has_score else []),
"rows": [{k: r[k] for k in ("threshold", "tp", "fp", "fn", "precision", "recall", "f1", "map")} for r in m_rows]})
pts = [(f"IoU {tkey(r['threshold'])}", lab, r[key]) for r in m_rows for key, lab in (("f1", "F1"), ("precision", "Precision"), ("recall", "Recall")) if r[key] is not None]
if pts:
charts.append(cs.chart("f1-at-iou", "cleveland-dot", "Segment F1, precision and recall by IoU threshold", {
"category": cs.col("IoU threshold", [p[0] for p in pts], "categorical", levels=[f"IoU {tkey(r['threshold'])}" for r in m_rows]),
"value": cs.col("Share", [p[2] for p in pts], "numeric"),
"group": cs.col("Measure", [p[1] for p in pts], "categorical", levels=["F1", "Precision", "Recall"])}))
else:
tables.append({"key": "classes", "title": "Per class (pixels summed over images)", "columns": cls_cols, "rows": cls_rows})
tables.append({"key": "images", "title": "Mean IoU per image", "rows": group_rows[:500],
"columns": [{"key": "group", "label": GROUP, "type": "string"}] + ([{"key": "frame", "label": FRAME, "type": "number"}] if FRAME else [])
+ [{"key": "miou", "label": "Mean IoU", "type": "number"}], "note": "First 500 images." if len(group_rows) > 500 else None})
dots = [(c, m, res[key][j]) for j, c in enumerate(names) for key, m in (("iou", "IoU"), ("dice", "Dice")) if res[key][j] is not None]
if dots:
charts.insert(0, cs.chart("by-class", "cleveland-dot", "IoU and Dice by class", {
"category": cs.col(LABEL, [d[0] for d in dots], "categorical", levels=names),
"value": cs.col("Overlap", [d[2] for d in dots], "numeric"),
"group": cs.col("Measure", [d[1] for d in dots], "categorical", levels=["IoU", "Dice"])}))
what = "pixel accuracy" if KIND == "masks" else "time-weighted accuracy"
summary = (f"Across {n_groups} {'images' if KIND == 'masks' else 'recordings'} and {len(names)} classes, mean IoU = {f3(res['miou'])}, "
f"mean Dice = {f3(res['mean_dice'])} and {what} = {f3(res['accuracy'])}.")
if KIND == "intervals":
summary += " Segment F1: " + ", ".join(f"{f3(r['f1'])} at IoU {tkey(r['threshold'])}" for r in res["matching"]) + "."
if has_score and values["map"] is not None:
summary += f" mAP over the thresholds = {f3(values['map'])}."
cs.publish({
"method": "evaluate.segments",
"methodVersion": "1.1.0",
"title": "Segmentation quality",
"engine": cs.engine_info("pandas", "numpy"),
"n": int(len(df)),
"summary": summary,
"statistics": [{"key": "miou", "label": "Mean IoU", "value": res["miou"]}, {"key": "mean_dice", "label": "Mean Dice", "value": res["mean_dice"]},
{"key": "accuracy", "label": "Pixel accuracy" if KIND == "masks" else "Time-weighted accuracy", "value": res["accuracy"]}],
"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. ")
+ ("Masks are compared on their run lengths (no pixels decoded)" + ("; unlabeled pixels form a background class" if BACKGROUND else "")
+ ("; crowd regions are left out of scoring" if CROWD else "") + "." if KIND == "masks"
else "Segments match within a recording and class, " + ("highest score first." if SCORE else "earliest first."))],
"charts": charts,
"values": values,
})
- Mean IoUMean IoU (mIoU)Per class, the pixels (or time) predicted and labeled alike divided by those either one covers; mIoU averages the classes. = 0.495 averages each class's IoU, so a small class counts as much as a large one.
- DiceDice coefficientTwice the overlap divided by the sum of the predicted and labeled areas; always at least the IoU of the same class. = 2·overlap / (predicted + labeled area); for the same class it is always at least the IoU.
- Pixel accuracyPixel accuracyShare of the labeled pixels (or labeled time) given the right class; large classes such as background dominate it. = 0.773 is dominated by large classes, especially the background.
Time segments
ReadSound events, speaker turns and actions in a video are intervals of time. The same overlap applies in one dimension:
Across 4 recordings and 3 classes, mean IoU = 0.612, mean Dice = 0.754 and time-weighted accuracy = 0.742. Segment F1: 0.730 at IoU 0.1, 0.730 at IoU 0.25, 0.676 at IoU 0.5. mAP over the thresholds = 0.684.
- Mean IoU
- 0.6119
- Mean Dice
- 0.7536
- Time-weighted accuracy
- 0.7419
Plots
View data
| label | Measure | Overlap |
|---|---|---|
| music | IoU | 0.4993 |
| music | Dice | 0.6661 |
| noise | IoU | 0.7616 |
| noise | Dice | 0.8647 |
| speech | IoU | 0.5749 |
| speech | Dice | 0.7301 |
View data
| IoU threshold | Measure | Share |
|---|---|---|
| IoU 0.1 | F1 | 0.7297 |
| IoU 0.1 | Precision | 0.6923 |
| IoU 0.1 | Recall | 0.7714 |
| IoU 0.25 | F1 | 0.7297 |
| IoU 0.25 | Precision | 0.6923 |
| IoU 0.25 | Recall | 0.7714 |
| IoU 0.5 | F1 | 0.6757 |
| IoU 0.5 | Precision | 0.6410 |
| IoU 0.5 | Recall | 0.7143 |
Assumptions
- The reference is complete — Regions or segments missing from the reference turn correct predictions into errors.
- Reference classes don't overlap — Where reference regions of two classes overlap, the shared part counts for both; accuracy then divides by more than the scored area.
Per class (time overlap)
| label | Reference seconds | Predicted seconds | Overlap (seconds) | IoU | Dice | AP@0.1 | AP@0.25 | AP@0.5 |
|---|---|---|---|---|---|---|---|---|
| music | 41.700 | 47 | 29.540 | 0.4993 | 0.6661 | 0.5556 | 0.5556 | 0.5556 |
| noise | 71.760 | 71.900 | 62.110 | 0.7616 | 0.8647 | 0.8321 | 0.8321 | 0.6448 |
| speech | 71.280 | 53.120 | 45.410 | 0.5749 | 0.7301 | 0.7273 | 0.7273 | 0.7273 |
Segments matched at each IoU threshold
| IoU threshold | Matched | False alarms | Missed | Precision | Recall | F1 | mAP |
|---|---|---|---|---|---|---|---|
| 0.1000 | 27 | 12 | 8 | 0.6923 | 0.7714 | 0.7297 | 0.7050 |
| 0.2500 | 27 | 12 | 8 | 0.6923 | 0.7714 | 0.7297 | 0.7050 |
| 0.5000 | 25 | 14 | 10 | 0.6410 | 0.7143 | 0.6757 | 0.6425 |
- Reference rows: source = annotation; predictions: source = prediction. Segments match within a recording and class, highest score first.
The exact R script · R R version 4.5.1 (2025-06-13)
# Segmentation quality (IoU, Dice, segment F1)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method evaluate.segments 1.1.0 · spec c2ef3c414cd4e641
# Dataset: img4_intervals (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_seg_* (segmentation scores), cs_eval_det_runs, cs_eval_stacked, cs_rle_* (COCO RLE)
# %% Data
GROUP <- "recording"
FRAME <- NULL
LABEL <- "label"
SOURCE <- "source"
MASK <- NULL
WIDTH <- NULL
HEIGHT <- NULL
CROWD <- NULL
START <- "start"
END <- "end"
SCORE <- "score"
KIND <- "intervals" # masks | intervals
BACKGROUND <- TRUE
THRESHOLDS <- as.numeric(unlist(c(0.1, 0.25, 0.5)))
if (!length(THRESHOLDS)) THRESHOLDS <- 0.5
THRESHOLDS <- sort(unique(THRESHOLDS))
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(GROUP, FRAME, LABEL, SOURCE, MASK, WIDTH, HEIGHT, CROWD, START, END, SCORE))
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/img4_intervals.parquet", col_select = columns))
if (KIND == "masks" && (is.null(MASK) || is.null(WIDTH) || is.null(HEIGHT))) {
cs_error("CS_E_INVALID_OPTION", option = "Segments are", allowed = "time intervals unless the mask, width and height columns are set", value = "masks")
}
if (KIND == "intervals" && (is.null(START) || is.null(END))) {
cs_error("CS_E_INVALID_OPTION", option = "Segments are", allowed = "masks unless the start and end columns are set", value = "time intervals")
}
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.segments/intervals-scored/out-r", "reference_table"),
list(group = GROUP, frame = FRAME, label = LABEL, mask = MASK, width = WIDTH, height = HEIGHT, crowd = CROWD,
start = START, end = END, score = SCORE), REF_ROLES,
c(list(frame = "Frame"), if (KIND == "masks") list(mask = "Mask", width = "Image width", height = "Image height") else list(start = "Start", end = "End")),
SOURCE, REF_LEVEL, c("group", "label", if (KIND == "masks") c("mask", "width", "height") else c("start", "end")))
df <- w$df
pre_warnings <- w$warnings
wc <- w$columns
GROUP <- wc$group; FRAME <- wc$frame; LABEL <- wc$label; MASK <- wc$mask; WIDTH <- wc$width; HEIGHT <- wc$height
CROWD <- wc$crowd; START <- wc$start; END <- wc$end
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(GROUP, LABEL, SOURCE, if (KIND == "masks") c(MASK, WIDTH, HEIGHT) else c(START, END))
numeric_cols <- if (KIND == "masks") c(WIDTH, HEIGHT) else c(START, END, SCORE)
st <- cs_eval_stacked(df, needed, numeric_cols, SOURCE, REF_LEVEL, SOURCE_LEVELS)
df <- st$df
is_ref <- st$is_ref
warnings <- c(pre_warnings, st$warnings)
if (sum(is_ref) == 0L || sum(!is_ref) == 0L) cs_error("CS_E_GROUP_COUNT", column = SOURCE, expected = 2, k = 1)
labels_all <- as.character(df[[LABEL]])
crowd <- if (!is.null(CROWD) && KIND == "masks") cs_eval_flags(df[[CROWD]]) else logical(nrow(df))
crowd[!is_ref] <- FALSE
classes <- sort(unique(labels_all[!crowd]), method = "radix")
if (KIND == "masks") {
# %% Masks -> runs, per image
ik <- cs_eval_image_keys(df[[GROUP]], if (!is.null(FRAME)) df[[FRAME]] else NULL)
img_idx <- ik$index
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)
ims <- lapply(seq_along(ik$media), function(i) list(n = NULL, size = NULL, ref = list(), pred = list(), void = list()))
for (i in seq_along(runs)) {
q <- img_idx[i] + 1L
r <- runs[[i]]
if (is.null(ims[[q]]$n)) {
ims[[q]]$n <- as.numeric(r$size[1]) * as.numeric(r$size[2])
ims[[q]]$size <- r$size
} else if (!identical(ims[[q]]$size, r$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)
}
rr <- list(s = r$s, e = r$e)
if (crowd[i]) {
ims[[q]]$void[[length(ims[[q]]$void) + 1L]] <- rr
} else if (is_ref[i]) {
lab <- labels_all[i]
ims[[q]]$ref[[lab]] <- c(if (is.null(ims[[q]]$ref[[lab]])) list() else ims[[q]]$ref[[lab]], list(rr))
} else {
lab <- labels_all[i]
ims[[q]]$pred[[lab]] <- c(if (is.null(ims[[q]]$pred[[lab]])) list() else ims[[q]]$pred[[lab]], list(rr))
}
}
res <- cs_eval_seg_masks(ims, classes, BACKGROUND)
names_ <- res$classes
n_ref <- sum(is_ref & !crowd)
n_pred <- sum(!is_ref)
unit <- "pixels"
group_rows <- lapply(seq_along(ik$media), function(i) list(group = ik$media[i], frame = if (is.infinite(ik$frame[i])) NA_real_ else ik$frame[i],
miou = if (is.null(res$per_image[[i]])) NA_real_ else res$per_image[[i]]))
n_groups <- length(ik$media)
has_score <- FALSE
} else {
# %% Intervals per recording
s_all <- as.numeric(df[[START]])
e_all <- as.numeric(df[[END]])
bad <- e_all < s_all
if (any(bad)) cs_error("CS_E_INVALID_VALUES", column = END, requirement = sprintf("at least %s", START), count = sum(bad))
sc_all <- if (!is.null(SCORE)) as.numeric(df[[SCORE]]) else rep(NA_real_, nrow(df))
has_score <- !is.null(SCORE)
if (has_score) {
miss <- !is_ref & is.na(sc_all)
if (any(miss)) {
warnings <- c(warnings, sprintf("%d predicted segments have no %s and were left out.", sum(miss), SCORE))
keep <- !miss
df <- df[keep, , drop = FALSE]; is_ref <- is_ref[keep]; labels_all <- labels_all[keep]
s_all <- s_all[keep]; e_all <- e_all[keep]; sc_all <- sc_all[keep]
classes <- sort(unique(labels_all), method = "radix")
}
}
grp <- as.character(df[[GROUP]])
groups <- sort(unique(grp), method = "radix")
recs <- lapply(groups, function(g) {
rows <- which(grp == g)
rr <- rows[is_ref[rows]]
pr <- rows[!is_ref[rows]]
list(ref = data.frame(start = s_all[rr], end = e_all[rr], label = labels_all[rr], stringsAsFactors = FALSE),
pred = data.frame(start = s_all[pr], end = e_all[pr], label = labels_all[pr], score = if (has_score) sc_all[pr] else rep(0, length(pr)),
row = pr - 1L, stringsAsFactors = FALSE))
})
res <- cs_eval_seg_intervals(recs, classes, THRESHOLDS, has_score)
names_ <- res$classes
n_ref <- res$n_ref
n_pred <- res$n_pred
unit <- "seconds"
n_groups <- length(groups)
}
# %% Assumptions
assumptions <- list(
list(key = "complete", label = "The reference is complete", status = "info",
detail = "Regions or segments missing from the reference turn correct predictions into errors."),
list(key = "overlap", label = "Reference classes don't overlap", status = "info",
detail = "Where reference regions of two classes overlap, the shared part counts for both; accuracy then divides by more than the scored area.")
)
# %% Result
f3 <- function(v) if (is.null(v) || is.na(v)) "—" else sprintf("%.3f", v)
tkey <- function(t) sprintf("%g", t)
values <- list(kind = KIND, n_groups = n_groups, n_classes = length(names_), n_reference = n_ref, n_predictions = n_pred,
accuracy = res$accuracy, miou = res$miou, mean_dice = res$mean_dice, fw_iou = res$fw_iou,
scored = if (!is.null(res$scored)) res$scored else sum(res$gsum), ignored = if (!is.null(res$ignored)) res$ignored else NA_real_,
map = NA_real_)
for (j in seq_along(names_)) {
values[[sprintf("iou[%s]", names_[j])]] <- res$iou[j]
values[[sprintf("dice[%s]", names_[j])]] <- res$dice[j]
}
cls_cols <- list(list(key = "class", label = LABEL, type = "string"), list(key = "ref", label = sprintf("Reference %s", unit), type = "number"),
list(key = "pred", label = sprintf("Predicted %s", unit), type = "number"), list(key = "inter", label = sprintf("Overlap (%s)", unit), type = "number"),
list(key = "iou", label = "IoU", type = "number"), list(key = "dice", label = "Dice", type = "number"))
cls_rows <- lapply(seq_along(names_), function(j) list(class = names_[j], ref = res$gsum[j], pred = res$psum[j], inter = res$inter[j],
iou = res$iou[j], dice = res$dice[j]))
tables <- list()
charts <- list()
if (KIND == "intervals") {
m_rows <- res$matching
for (r in m_rows) {
values[[sprintf("f1[%s]", tkey(r$threshold))]] <- r$f1
values[[sprintf("precision[%s]", tkey(r$threshold))]] <- r$precision
values[[sprintf("recall[%s]", tkey(r$threshold))]] <- r$recall
if (has_score) values[[sprintf("ap[%s]", tkey(r$threshold))]] <- r$map
}
if (has_score) {
maps <- vapply(m_rows, function(r) r$map, numeric(1))
maps <- maps[!is.na(maps)]
values$map <- if (length(maps)) mean(maps) else NA_real_
for (r in m_rows) {
key <- sprintf("ap_%s", tkey(r$threshold))
cls_cols[[length(cls_cols) + 1L]] <- list(key = key, label = sprintf("AP@%s", tkey(r$threshold)), type = "number")
for (j in seq_along(cls_rows)) cls_rows[[j]][[key]] <- if (is.null(r$ap[[cls_rows[[j]]$class]])) NA_real_ else r$ap[[cls_rows[[j]]$class]]
}
}
tables[[length(tables) + 1L]] <- list(key = "classes", title = "Per class (time overlap)", columns = cls_cols, rows = cls_rows)
mcols <- list(list(key = "threshold", label = "IoU threshold", type = "number"), list(key = "tp", label = "Matched", type = "integer"),
list(key = "fp", label = "False alarms", type = "integer"), list(key = "fn", label = "Missed", type = "integer"),
list(key = "precision", label = "Precision", type = "number"), list(key = "recall", label = "Recall", type = "number"),
list(key = "f1", label = "F1", type = "number"))
if (has_score) mcols[[length(mcols) + 1L]] <- list(key = "map", label = "mAP", type = "number")
tables[[length(tables) + 1L]] <- list(key = "matching", title = "Segments matched at each IoU threshold", columns = mcols,
rows = lapply(m_rows, function(r) r[c("threshold", "tp", "fp", "fn", "precision", "recall", "f1", "map")]))
pc <- character(0); pm <- character(0); pv <- numeric(0)
for (r in m_rows) for (km in list(c("f1", "F1"), c("precision", "Precision"), c("recall", "Recall"))) if (!is.na(r[[km[1]]])) {
pc <- c(pc, sprintf("IoU %s", tkey(r$threshold))); pm <- c(pm, km[2]); pv <- c(pv, r[[km[1]]])
}
if (length(pv)) {
charts[[length(charts) + 1L]] <- cs_chart("f1-at-iou", "cleveland-dot", "Segment F1, precision and recall by IoU threshold", list(
category = cs_col("IoU threshold", pc, "categorical", levels = vapply(m_rows, function(r) sprintf("IoU %s", tkey(r$threshold)), character(1))),
value = cs_col("Share", pv, "numeric"),
group = cs_col("Measure", pm, "categorical", levels = c("F1", "Precision", "Recall"))))
}
} else {
tables[[length(tables) + 1L]] <- list(key = "classes", title = "Per class (pixels summed over images)", columns = cls_cols, rows = cls_rows)
tables[[length(tables) + 1L]] <- list(key = "images", title = "Mean IoU per image", rows = utils::head(group_rows, 500),
columns = c(list(list(key = "group", label = GROUP, type = "string")), if (!is.null(FRAME)) list(list(key = "frame", label = FRAME, type = "number")),
list(list(key = "miou", label = "Mean IoU", type = "number"))),
note = if (length(group_rows) > 500) "First 500 images." else NULL)
}
dc <- character(0); dm <- character(0); dv <- numeric(0)
for (j in seq_along(names_)) for (km in list(c("iou", "IoU"), c("dice", "Dice"))) if (!is.na(res[[km[1]]][j])) {
dc <- c(dc, names_[j]); dm <- c(dm, km[2]); dv <- c(dv, res[[km[1]]][j])
}
if (length(dv)) {
charts <- c(list(cs_chart("by-class", "cleveland-dot", "IoU and Dice by class", list(
category = cs_col(LABEL, dc, "categorical", levels = names_), value = cs_col("Overlap", dv, "numeric"),
group = cs_col("Measure", dm, "categorical", levels = c("IoU", "Dice"))))), charts)
}
what <- if (KIND == "masks") "pixel accuracy" else "time-weighted accuracy"
summary <- sprintf("Across %d %s and %d classes, mean IoU = %s, mean Dice = %s and %s = %s.", n_groups, if (KIND == "masks") "images" else "recordings",
length(names_), f3(res$miou), f3(res$mean_dice), what, f3(res$accuracy))
if (KIND == "intervals") {
summary <- paste0(summary, " Segment F1: ", paste(vapply(res$matching, function(r) sprintf("%s at IoU %s", f3(r$f1), tkey(r$threshold)), character(1)), collapse = ", "), ".")
if (has_score && !is.na(values$map)) summary <- paste0(summary, sprintf(" mAP over the thresholds = %s.", f3(values$map)))
}
cs_publish(list(
method = "evaluate.segments",
methodVersion = "1.1.0",
title = "Segmentation quality",
engine = cs_engine_info("nanoparquet"),
n = nrow(df),
summary = summary,
statistics = list(list(key = "miou", label = "Mean IoU", value = res$miou), list(key = "mean_dice", label = "Mean Dice", value = res$mean_dice),
list(key = "accuracy", label = if (KIND == "masks") "Pixel accuracy" else "Time-weighted accuracy", value = res$accuracy)),
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 (KIND == "masks") paste0("Masks are compared on their run lengths (no pixels decoded)", if (BACKGROUND) "; unlabeled pixels form a background class" else "",
if (!is.null(CROWD)) "; crowd regions are left out of scoring" else "", ".")
else paste0("Segments match within a recording and class, ", if (!is.null(SCORE)) "highest score first." else "earliest first."))),
charts = charts,
values = values
))
Across 4 recordings and 3 classes, mean IoU = 0.612, mean Dice = 0.754 and time-weighted accuracy = 0.742. Segment F1: 0.730 at IoU 0.1, 0.730 at IoU 0.25, 0.676 at IoU 0.5. mAP over the thresholds = 0.684.
- Mean IoU
- 0.6119
- Mean Dice
- 0.7536
- Time-weighted accuracy
- 0.7419
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- The reference is complete — Regions or segments missing from the reference turn correct predictions into errors.
- Reference classes don't overlap — Where reference regions of two classes overlap, the shared part counts for both; accuracy then divides by more than the scored area.
Per class (time overlap)
| label | Reference seconds | Predicted seconds | Overlap (seconds) | IoU | Dice | AP@0.1 | AP@0.25 | AP@0.5 |
|---|---|---|---|---|---|---|---|---|
| music | 41.700 | 47 | 29.540 | 0.4993 | 0.6661 | 0.5556 | 0.5556 | 0.5556 |
| noise | 71.760 | 71.900 | 62.110 | 0.7616 | 0.8647 | 0.8321 | 0.8321 | 0.6448 |
| speech | 71.280 | 53.120 | 45.410 | 0.5749 | 0.7301 | 0.7273 | 0.7273 | 0.7273 |
Segments matched at each IoU threshold
| IoU threshold | Matched | False alarms | Missed | Precision | Recall | F1 | mAP |
|---|---|---|---|---|---|---|---|
| 0.1000 | 27 | 12 | 8 | 0.6923 | 0.7714 | 0.7297 | 0.7050 |
| 0.2500 | 27 | 12 | 8 | 0.6923 | 0.7714 | 0.7297 | 0.7050 |
| 0.5000 | 25 | 14 | 10 | 0.6410 | 0.7143 | 0.6757 | 0.6425 |
- Reference rows: source = annotation; predictions: source = prediction. Segments match within a recording and class, highest score first.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Segmentation quality (IoU, Dice, segment F1)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method evaluate.segments 1.1.0 · spec c2ef3c414cd4e641
# Dataset: img4_intervals (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 # RLE runs (twin: cs_eval_det_runs)
from codesplash.evaluate import segmentation as seg # twin: codesplashr cs_eval_seg_*
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
GROUP = "recording"
FRAME = None
LABEL = "label"
SOURCE = "source"
MASK = None
WIDTH = None
HEIGHT = None
CROWD = None
START = "start"
END = "end"
SCORE = "score"
KIND = "intervals" # masks | intervals
BACKGROUND = True
THRESHOLDS = [float(t) for t in [0.1, 0.25, 0.5]] or [0.5]
THRESHOLDS = sorted(set(THRESHOLDS))
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 [GROUP, FRAME, LABEL, SOURCE, MASK, WIDTH, HEIGHT, CROWD, START, END, SCORE] if c))
df = pd.read_parquet("tests/parity/fixtures/img4_intervals.parquet", columns=columns)
if KIND == "masks" and not (MASK and WIDTH and HEIGHT):
cs.cs_error("CS_E_INVALID_OPTION", option="Segments are", allowed="time intervals unless the mask, width and height columns are set", value="masks")
if KIND == "intervals" and not (START and END):
cs.cs_error("CS_E_INVALID_OPTION", option="Segments are", allowed="masks unless the start and end columns are set", value="time intervals")
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.segments/intervals-scored/out-python", "reference_table"),
{"group": GROUP, "frame": FRAME, "label": LABEL, "mask": MASK, "width": WIDTH, "height": HEIGHT, "crowd": CROWD,
"start": START, "end": END, "score": SCORE}, REF_ROLES,
{"frame": "Frame", **({"mask": "Mask", "width": "Image width", "height": "Image height"} if KIND == "masks" else {"start": "Start", "end": "End"})},
SOURCE, REF_LEVEL, ["group", "label"] + (["mask", "width", "height"] if KIND == "masks" else ["start", "end"]))
df, pre_warnings, wc = w["df"], w["warnings"], w["columns"]
GROUP, FRAME, LABEL, MASK, WIDTH, HEIGHT = wc["group"], wc["frame"], wc["label"], wc["mask"], wc["width"], wc["height"]
CROWD, START, END = wc["crowd"], wc["start"], wc["end"]
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 = [GROUP, LABEL, SOURCE] + ([MASK, WIDTH, HEIGHT] if KIND == "masks" else [START, END])
numeric = [WIDTH, HEIGHT] if KIND == "masks" else [c for c in [START, END, SCORE] if c]
st = stacked(df, needed, numeric, SOURCE, REF_LEVEL, SOURCE_LEVELS)
df, is_ref, warnings = st["df"], st["is_ref"], pre_warnings + st["warnings"]
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)
labels_all = np.asarray([str(x) for x in df[LABEL].tolist()], dtype=object)
crowd = flags(df[CROWD]) if (CROWD and KIND == "masks") else np.zeros(len(df), dtype=bool)
crowd[~is_ref] = False
classes = sorted(set(labels_all[~crowd].tolist()))
if KIND == "masks":
# %% Masks → runs, per image
img_idx, images = image_keys(df[GROUP], df[FRAME] if FRAME else None)
ws, hs = df[WIDTH].to_numpy(dtype=float), df[HEIGHT].to_numpy(dtype=float)
runs, n_bad = [], 0
for s, w, h in zip(df[MASK].tolist(), ws, hs):
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)
ims = [{"n": None, "ref": {}, "pred": {}, "void": []} for _ in images]
for i, r in enumerate(runs):
im = ims[int(img_idx[i])]
n = float(r[2][0]) * float(r[2][1])
if im["n"] is None:
im["n"], im["size"] = n, r[2]
elif im["size"] != 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)
if crowd[i]:
im["void"].append(r[:2])
else:
side = im["ref"] if is_ref[i] else im["pred"]
side.setdefault(labels_all[i], []).append(r[:2])
res = seg.mask_scores(ims, classes, BACKGROUND)
names = res["classes"]
n_ref = int(np.sum(is_ref & ~crowd))
n_pred = int(np.sum(~is_ref))
unit = "pixels"
group_rows = [{"group": m, "frame": None if f == float("-inf") else f, "miou": res["per_image"][i]} for i, (m, f) in enumerate(images)]
n_groups = len(images)
else:
# %% Intervals per recording
s_all, e_all = df[START].to_numpy(dtype=float), df[END].to_numpy(dtype=float)
bad = e_all < s_all
if bad.any():
cs.cs_error("CS_E_INVALID_VALUES", column=END, requirement=f"at least {START}", count=int(bad.sum()))
sc_all = df[SCORE].to_numpy(dtype=float, na_value=np.nan) if SCORE else np.full(len(df), np.nan)
has_score = SCORE is not None
if has_score:
miss = ~is_ref & np.isnan(sc_all)
if miss.any():
warnings.append(f"{int(miss.sum())} predicted segments have no {SCORE} and were left out.")
keep = ~miss
df, is_ref, labels_all, s_all, e_all, sc_all = df.loc[keep].reset_index(drop=True), is_ref[keep], labels_all[keep], s_all[keep], e_all[keep], sc_all[keep]
classes = sorted(set(labels_all.tolist()))
grp = np.asarray([str(x) for x in df[GROUP].tolist()], dtype=object)
groups = sorted(set(grp.tolist()))
recs = []
for g in groups:
rows = np.flatnonzero(grp == g)
recs.append({"ref": [(s_all[i], e_all[i], labels_all[i]) for i in rows if is_ref[i]],
"pred": [(s_all[i], e_all[i], labels_all[i], float(sc_all[i]) if has_score else 0.0, int(i)) for i in rows if not is_ref[i]]})
res = seg.interval_scores(recs, classes, THRESHOLDS, has_score)
names = res["classes"]
n_ref, n_pred = res["n_ref"], res["n_pred"]
unit = "seconds"
n_groups = len(groups)
# %% Assumptions
assumptions = [
{"key": "complete", "label": "The reference is complete", "status": "info",
"detail": "Regions or segments missing from the reference turn correct predictions into errors."},
{"key": "overlap", "label": "Reference classes don't overlap", "status": "info",
"detail": "Where reference regions of two classes overlap, the shared part counts for both; accuracy then divides by more than the scored area."},
]
# %% Result
f3 = lambda v: "—" if v is None else f"{v:.3f}"
tkey = lambda t: "%g" % t
values = {"kind": KIND, "n_groups": n_groups, "n_classes": len(names), "n_reference": n_ref, "n_predictions": n_pred,
"accuracy": res["accuracy"], "miou": res["miou"], "mean_dice": res["mean_dice"], "fw_iou": res["fw_iou"],
"scored": res.get("scored", float(np.sum(res["gsum"]))), "ignored": res.get("ignored"), "map": None}
for j, c in enumerate(names):
values[f"iou[{c}]"] = res["iou"][j]
values[f"dice[{c}]"] = res["dice"][j]
cls_cols = [{"key": "class", "label": LABEL, "type": "string"}, {"key": "ref", "label": f"Reference {unit}", "type": "number"},
{"key": "pred", "label": f"Predicted {unit}", "type": "number"}, {"key": "inter", "label": f"Overlap ({unit})", "type": "number"},
{"key": "iou", "label": "IoU", "type": "number"}, {"key": "dice", "label": "Dice", "type": "number"}]
cls_rows = [{"class": c, "ref": float(res["gsum"][j]), "pred": float(res["psum"][j]), "inter": float(res["inter"][j]),
"iou": res["iou"][j], "dice": res["dice"][j]} for j, c in enumerate(names)]
tables = []
charts = []
if KIND == "intervals":
m_rows = res["matching"]
for r in m_rows:
values[f"f1[{tkey(r['threshold'])}]"] = r["f1"]
values[f"precision[{tkey(r['threshold'])}]"] = r["precision"]
values[f"recall[{tkey(r['threshold'])}]"] = r["recall"]
if has_score:
values[f"ap[{tkey(r['threshold'])}]"] = r["map"]
if has_score:
maps = [r["map"] for r in m_rows if r["map"] is not None]
values["map"] = float(np.mean(maps)) if maps else None
for r in m_rows:
cls_cols.append({"key": f"ap_{tkey(r['threshold'])}", "label": f"AP@{tkey(r['threshold'])}", "type": "number"})
for row in cls_rows:
row[f"ap_{tkey(r['threshold'])}"] = r["ap"].get(row["class"])
tables.append({"key": "classes", "title": "Per class (time overlap)", "columns": cls_cols, "rows": cls_rows})
tables.append({"key": "matching", "title": "Segments matched at each IoU threshold",
"columns": [{"key": "threshold", "label": "IoU threshold", "type": "number"}, {"key": "tp", "label": "Matched", "type": "integer"},
{"key": "fp", "label": "False alarms", "type": "integer"}, {"key": "fn", "label": "Missed", "type": "integer"},
{"key": "precision", "label": "Precision", "type": "number"}, {"key": "recall", "label": "Recall", "type": "number"},
{"key": "f1", "label": "F1", "type": "number"}] + ([{"key": "map", "label": "mAP", "type": "number"}] if has_score else []),
"rows": [{k: r[k] for k in ("threshold", "tp", "fp", "fn", "precision", "recall", "f1", "map")} for r in m_rows]})
pts = [(f"IoU {tkey(r['threshold'])}", lab, r[key]) for r in m_rows for key, lab in (("f1", "F1"), ("precision", "Precision"), ("recall", "Recall")) if r[key] is not None]
if pts:
charts.append(cs.chart("f1-at-iou", "cleveland-dot", "Segment F1, precision and recall by IoU threshold", {
"category": cs.col("IoU threshold", [p[0] for p in pts], "categorical", levels=[f"IoU {tkey(r['threshold'])}" for r in m_rows]),
"value": cs.col("Share", [p[2] for p in pts], "numeric"),
"group": cs.col("Measure", [p[1] for p in pts], "categorical", levels=["F1", "Precision", "Recall"])}))
else:
tables.append({"key": "classes", "title": "Per class (pixels summed over images)", "columns": cls_cols, "rows": cls_rows})
tables.append({"key": "images", "title": "Mean IoU per image", "rows": group_rows[:500],
"columns": [{"key": "group", "label": GROUP, "type": "string"}] + ([{"key": "frame", "label": FRAME, "type": "number"}] if FRAME else [])
+ [{"key": "miou", "label": "Mean IoU", "type": "number"}], "note": "First 500 images." if len(group_rows) > 500 else None})
dots = [(c, m, res[key][j]) for j, c in enumerate(names) for key, m in (("iou", "IoU"), ("dice", "Dice")) if res[key][j] is not None]
if dots:
charts.insert(0, cs.chart("by-class", "cleveland-dot", "IoU and Dice by class", {
"category": cs.col(LABEL, [d[0] for d in dots], "categorical", levels=names),
"value": cs.col("Overlap", [d[2] for d in dots], "numeric"),
"group": cs.col("Measure", [d[1] for d in dots], "categorical", levels=["IoU", "Dice"])}))
what = "pixel accuracy" if KIND == "masks" else "time-weighted accuracy"
summary = (f"Across {n_groups} {'images' if KIND == 'masks' else 'recordings'} and {len(names)} classes, mean IoU = {f3(res['miou'])}, "
f"mean Dice = {f3(res['mean_dice'])} and {what} = {f3(res['accuracy'])}.")
if KIND == "intervals":
summary += " Segment F1: " + ", ".join(f"{f3(r['f1'])} at IoU {tkey(r['threshold'])}" for r in res["matching"]) + "."
if has_score and values["map"] is not None:
summary += f" mAP over the thresholds = {f3(values['map'])}."
cs.publish({
"method": "evaluate.segments",
"methodVersion": "1.1.0",
"title": "Segmentation quality",
"engine": cs.engine_info("pandas", "numpy"),
"n": int(len(df)),
"summary": summary,
"statistics": [{"key": "miou", "label": "Mean IoU", "value": res["miou"]}, {"key": "mean_dice", "label": "Mean Dice", "value": res["mean_dice"]},
{"key": "accuracy", "label": "Pixel accuracy" if KIND == "masks" else "Time-weighted accuracy", "value": res["accuracy"]}],
"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. ")
+ ("Masks are compared on their run lengths (no pixels decoded)" + ("; unlabeled pixels form a background class" if BACKGROUND else "")
+ ("; crowd regions are left out of scoring" if CROWD else "") + "." if KIND == "masks"
else "Segments match within a recording and class, " + ("highest score first." if SCORE else "earliest first."))],
"charts": charts,
"values": values,
})
- Time IoU per class compares the total time labeled and predicted as that class.
- Segment F1Segment F1 at an IoU thresholdPrecision and recall of whole segments: a predicted segment counts when its time IoU with a labeled one reaches the threshold. at a threshold counts whole segments: F1 at IoU 0.5 is 0.676 here, higher at looser thresholds.
- With confidence scores, average precisionAverage precision of time segments (mAP@tIoU)Average precision of scored segments matched at a time IoU threshold, averaged over classes (the ActivityNet convention). per threshold ranks the segments like detections: mAP = 0.684.
Check yourself
ReadCheck yourself
A detector has AP50 = 0.82 and AP75 = 0.41. What does the gap say?
Show the answer
Answer: b
At IoU 0.5 most objects count as found; at 0.75 half of those boxes no longer overlap tightly enough. Localization, not detection, is the weak spot.
Check yourself
AR@1 = 0.30 but AR@100 = 0.85 in images that hold one object each. What is happening?
Show the answer
Answer: b
With one object per image, the top box alone finds only 30% of them, but the right box is usually somewhere in the top 100: the confidence ranking within an image is off.
Check yourself
Road images are 90% background. A segmenter labels every pixel background. Roughly what pixel accuracy does it get, counting the background?
Show the answer
Answer: c
Pixel accuracy counts pixels, so the background alone gives 90%. Mean IoU averages classes and would show the failure: every other class has IoU 0.
Check yourself
A class has IoU 0.5. What is its Dice coefficient? (Dice = 2·IoU / (1 + IoU).)
Show the answer
Answer: 0.6667
2 × 0.5 / 1.5 = 0.667. Dice is never below IoU for the same masks.
Check yourself
Segment F1 is 0.80 at IoU 0.1 and 0.45 at IoU 0.5. What does that suggest?
Show the answer
Answer: a
At a loose threshold most segments match; at a strict one many no longer overlap enough. The model knows that something happens, less precisely when.
Concepts in this lesson