Video as data: frames, time and honest splits
A video is frames plus the times they were taken. Learn what a clip really covers, how segment sampling sees a whole video cheaply, why frames from one video must stay in one split, and when a model may look at the future.
What runs in CodeSplash
- VID005Temporal Segment Networks (TSN) Explained here
- VID014MoViNets Explained here
- Object detection quality (COCO average precision) Experimental
- Track objects across frames (SORT, ByteTrack, DeepSORT-style) Experimental
You will be able to
- Say what a clip covers from its frame count, stride and frame rate
- Describe segment sampling and score averaging (TSN) and what averaging loses
- Split video data by source video, not by frame or clip
- Tell a causal (streaming) model from an offline one, and reset streaming state between videos
Frames and the clock
ReadA video reaches a model as a stack of frames: time × height × width × color channels. The stack alone is not the whole input. Each frame also has a timestamp, and the video data contractData contract: videoFrames over time with timestamps: record the frame rate and sampling, and keep every clip from a source video in the same split. asks you to record the source frame rate, which frames you kept and how far apart they were.
That matters because frame samplingFrame samplingWhich frames a model sees and how far apart they are in time. Sixteen frames can span half a second or a minute. decides what the model can see. Sixteen consecutive frames at thirty per second cover about half a second: enough for a hand wave, not for "making coffee". The same sixteen frames taken every eighth frame cover four seconds. Same tensor shape, different task.
Three ways to pick sixteen frames
ReadRun this and compare how much time each sample spans. Dense sampling sees a short moment in detail; strided sampling sees longer but can skip a brief event; segment sampling spreads a few frames over the whole video.
import numpy as np
fps, n_frames = 30, 300 # a 10-second video
t = np.arange(n_frames) / fps # timestamp of every frame (s)
dense = np.arange(16) # 16 frames in a row
strided = np.arange(16) * 8 # 16 frames, every 8th
edges = np.linspace(0, n_frames, 5) # 4 equal segments
segments = ((edges[:-1] + edges[1:]) / 2).astype(int)
for name, idx in [("dense", dense), ("strided", strided), ("segments", segments)]:
print(name, idx[:4], "spans", round(t[idx[-1]] - t[idx[0]], 2), "s")fps <- 30; n_frames <- 300 # a 10-second video
t <- (0:(n_frames - 1)) / fps # timestamp of every frame (s)
idx <- list(dense = 0:15, # 16 frames in a row
strided = (0:15) * 8, # 16 frames, every 8th
segments = {e <- seq(0, n_frames, length.out = 5)
as.integer((head(e, -1) + tail(e, -1)) / 2)})
for (nm in names(idx)) {
i <- idx[[nm]]
cat(nm, head(i, 4), "spans", round(t[i[length(i)] + 1] - t[i[1] + 1], 2), "s\n")
}Segment sampling and consensus
ReadTemporal segment networksSegment sampling and consensusSplit a video into equal segments, score one short snippet from each, and average the scores into one video prediction. (TSN) cut a video into equal segments, run one shared encoder on a short snippet from each, and average the snippet scores before the softmax:
The loss is computed on that video-level prediction, so no single snippet has to show the action. In the reference's example, three snippets average to class probabilities 0.661 and 0.339; the cross-entropy for the true first class is 0.414.
What averaging forgets
PredictPredict first
A TSN model averages snippet scores. You feed it a clip of a door opening, then the same clip played backward (a door closing). What happens to the video score?
Reveal
The same score. An average doesn't care about order, so "open" and "close" built from the same snippets look identical. Order-sensitive actions need an order-aware consensus or a temporal model, and a test set that checks them separately.
Frames are not independent examples
ReadNeighboring frames are nearly identical, and every frame of a video shares its place, light and people. If frames or clips of one video land in both training and test sets, the test set grades memory, not recognition.
So the unit is the video, or the person, camera or scene behind it, whichever your claim is about. Split by that sourceSplit by source (images)Keeping every image from one camera, scene, subject or burst in the same fold, so near-copies can't leak into the test set. before cutting clips, and compute uncertainty over videos, not frames.
BExplorable · When observations come in clusters
What happens to a t test when students come in classrooms and you ignore it?
There is no true effect. How often does the naive t test reject?
Commit your prediction above to see the result
Make your prediction to see the result.
Seventy pictures, two videos
ExploreAcross 70 images and 2 classes, AP (IoU 0.50:0.95) = 0.689, AP50 = 0.876 and AP75 = 0.857; average recall with up to 100 detections per image = 0.730. At IoU 0.50: 178 true positives, 6 false positives, 23 missed objects.
- AP (0.50:0.95)
- 0.6891
- AP50
- 0.8759
- AP75
- 0.8574
- AR@100
- 0.7297
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 177 rows.
View data
| label | Measure | Average precision |
|---|---|---|
| car | AP | 0.7207 |
| car | AP50 | 0.8713 |
| car | AP75 | 0.8713 |
| person | AP | 0.6575 |
| person | AP50 | 0.8806 |
| person | AP75 | 0.8435 |
Assumptions
- Every object is labeled — Predictions of objects that the reference doesn't list count as false positives.
- Predicted classes are in the reference — Every predicted class appears in the reference.
- Enough objects per class — Every class has at least 10 reference objects.
COCO summary (boxes)
| Metric | IoU | Object size | Detections per image | Value |
|---|---|---|---|---|
| AP | 0.50:0.95 | all | 100 | 0.6891 |
| AP | 0.50 | all | 100 | 0.8759 |
| AP | 0.75 | all | 100 | 0.8574 |
| AP | 0.50:0.95 | small | 100 | 0.6218 |
| AP | 0.50:0.95 | medium | 100 | 0.6943 |
| AP | 0.50:0.95 | large | 100 | — |
| AR | 0.50:0.95 | all | 1 | 0.5563 |
| AR | 0.50:0.95 | all | 10 | 0.7297 |
| AR | 0.50:0.95 | all | 100 | 0.7297 |
| AR | 0.50:0.95 | small | 100 | 0.6455 |
| AR | 0.50:0.95 | medium | 100 | 0.7350 |
| AR | 0.50:0.95 | large | 100 | — |
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 |
|---|---|---|---|---|---|---|---|---|---|---|
| car | 56 | 0 | 49 | 0.7207 | 0.8713 | 0.8713 | 0.7554 | 49 | 0 | 7 |
| person | 145 | 0 | 135 | 0.6575 | 0.8806 | 0.8435 | 0.7041 | 129 | 6 | 16 |
Per image at IoU 0.50
| media_id | frame | Reference objects | Predictions | True positives | False positives | Missed |
|---|---|---|---|---|---|---|
| cam1 | 0 | 2 | 2 | 2 | 0 | 0 |
| cam1 | 1 | 2 | 2 | 2 | 0 | 0 |
| cam1 | 2 | 2 | 2 | 2 | 0 | 0 |
| cam1 | 3 | 2 | 2 | 2 | 0 | 0 |
| cam1 | 4 | 2 | 1 | 1 | 0 | 1 |
| cam1 | 5 | 3 | 3 | 3 | 0 | 0 |
| cam1 | 6 | 3 | 2 | 2 | 0 | 1 |
| cam1 | 7 | 3 | 2 | 2 | 0 | 1 |
| cam1 | 8 | 3 | 3 | 3 | 0 | 0 |
| cam1 | 9 | 3 | 3 | 3 | 0 | 0 |
| cam1 | 10 | 3 | 3 | 3 | 0 | 0 |
| cam1 | 11 | 3 | 3 | 3 | 0 | 0 |
| cam1 | 12 | 3 | 2 | 2 | 0 | 1 |
| cam1 | 13 | 3 | 2 | 2 | 0 | 1 |
| cam1 | 14 | 3 | 4 | 3 | 1 | 0 |
| cam1 | 15 | 3 | 3 | 3 | 0 | 0 |
| cam1 | 16 | 3 | 2 | 2 | 0 | 1 |
| cam1 | 17 | 3 | 3 | 3 | 0 | 0 |
| cam1 | 18 | 4 | 4 | 4 | 0 | 0 |
| cam1 | 19 | 4 | 4 | 4 | 0 | 0 |
| cam1 | 20 | 4 | 4 | 4 | 0 | 0 |
| cam1 | 21 | 4 | 4 | 4 | 0 | 0 |
| cam1 | 22 | 4 | 3 | 3 | 0 | 1 |
| cam1 | 23 | 4 | 3 | 2 | 1 | 2 |
| cam1 | 24 | 4 | 4 | 4 | 0 | 0 |
| cam1 | 25 | 4 | 4 | 4 | 0 | 0 |
| cam1 | 26 | 4 | 3 | 3 | 0 | 1 |
| cam1 | 27 | 4 | 3 | 3 | 0 | 1 |
| cam1 | 28 | 4 | 5 | 4 | 1 | 0 |
| cam1 | 29 | 4 | 4 | 4 | 0 | 0 |
| cam1 | 30 | 4 | 3 | 3 | 0 | 1 |
| cam1 | 31 | 3 | 2 | 2 | 0 | 1 |
| cam1 | 32 | 3 | 3 | 3 | 0 | 0 |
| cam1 | 33 | 3 | 3 | 3 | 0 | 0 |
| cam1 | 34 | 3 | 4 | 3 | 1 | 0 |
| cam1 | 35 | 3 | 2 | 2 | 0 | 1 |
| cam1 | 36 | 3 | 3 | 3 | 0 | 0 |
| cam1 | 37 | 3 | 2 | 2 | 0 | 1 |
| cam1 | 38 | 3 | 3 | 3 | 0 | 0 |
| cam1 | 39 | 3 | 3 | 3 | 0 | 0 |
First 40 of 70 rows.
- Reference rows: source = annotation; predictions: source = prediction. COCO conventions: IoU 0.50:0.05:0.95, 101 recall points, greedy matching by score within each image and class.
The exact R script · R R version 4.5.1 (2025-06-13)
# Object detection quality (COCO average precision)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method evaluate.detections 1.1.0 · spec b0d1d3d1ebbc0175
# Dataset: img4_tracks (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr) # cs_eval_det_* (COCO evaluation), cs_eval_stacked, cs_rle_* (COCO RLE strings)
# %% Data
IMG <- "media_id"
FRAME <- "frame"
X0 <- "x0"; Y0 <- "y0"; X1 <- "x1"; Y1 <- "y1"
LABEL <- "label"; SCORE <- "score"
SOURCE <- "source"
CROWD <- NULL
AREA <- NULL
MASK <- NULL
WIDTH <- NULL
HEIGHT <- NULL
IOU_TYPE <- "bbox" # bbox | segm
MAX_DETS <- as.integer(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_tracks.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/video-frames/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 70 images and 2 classes, AP (IoU 0.50:0.95) = 0.689, AP50 = 0.876 and AP75 = 0.857; average recall with up to 100 detections per image = 0.730. At IoU 0.50: 178 true positives, 6 false positives, 23 missed objects.
- AP (0.50:0.95)
- 0.6891
- AP50
- 0.8759
- AP75
- 0.8574
- AR@100
- 0.7297
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 — Every predicted class appears in the reference.
- Enough objects per class — Every class has at least 10 reference objects.
COCO summary (boxes)
| Metric | IoU | Object size | Detections per image | Value |
|---|---|---|---|---|
| AP | 0.50:0.95 | all | 100 | 0.6891 |
| AP | 0.50 | all | 100 | 0.8759 |
| AP | 0.75 | all | 100 | 0.8574 |
| AP | 0.50:0.95 | small | 100 | 0.6218 |
| AP | 0.50:0.95 | medium | 100 | 0.6943 |
| AP | 0.50:0.95 | large | 100 | — |
| AR | 0.50:0.95 | all | 1 | 0.5563 |
| AR | 0.50:0.95 | all | 10 | 0.7297 |
| AR | 0.50:0.95 | all | 100 | 0.7297 |
| AR | 0.50:0.95 | small | 100 | 0.6455 |
| AR | 0.50:0.95 | medium | 100 | 0.7350 |
| AR | 0.50:0.95 | large | 100 | — |
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 |
|---|---|---|---|---|---|---|---|---|---|---|
| car | 56 | 0 | 49 | 0.7207 | 0.8713 | 0.8713 | 0.7554 | 49 | 0 | 7 |
| person | 145 | 0 | 135 | 0.6575 | 0.8806 | 0.8435 | 0.7041 | 129 | 6 | 16 |
Per image at IoU 0.50
| media_id | frame | Reference objects | Predictions | True positives | False positives | Missed |
|---|---|---|---|---|---|---|
| cam1 | 0 | 2 | 2 | 2 | 0 | 0 |
| cam1 | 1 | 2 | 2 | 2 | 0 | 0 |
| cam1 | 2 | 2 | 2 | 2 | 0 | 0 |
| cam1 | 3 | 2 | 2 | 2 | 0 | 0 |
| cam1 | 4 | 2 | 1 | 1 | 0 | 1 |
| cam1 | 5 | 3 | 3 | 3 | 0 | 0 |
| cam1 | 6 | 3 | 2 | 2 | 0 | 1 |
| cam1 | 7 | 3 | 2 | 2 | 0 | 1 |
| cam1 | 8 | 3 | 3 | 3 | 0 | 0 |
| cam1 | 9 | 3 | 3 | 3 | 0 | 0 |
| cam1 | 10 | 3 | 3 | 3 | 0 | 0 |
| cam1 | 11 | 3 | 3 | 3 | 0 | 0 |
| cam1 | 12 | 3 | 2 | 2 | 0 | 1 |
| cam1 | 13 | 3 | 2 | 2 | 0 | 1 |
| cam1 | 14 | 3 | 4 | 3 | 1 | 0 |
| cam1 | 15 | 3 | 3 | 3 | 0 | 0 |
| cam1 | 16 | 3 | 2 | 2 | 0 | 1 |
| cam1 | 17 | 3 | 3 | 3 | 0 | 0 |
| cam1 | 18 | 4 | 4 | 4 | 0 | 0 |
| cam1 | 19 | 4 | 4 | 4 | 0 | 0 |
| cam1 | 20 | 4 | 4 | 4 | 0 | 0 |
| cam1 | 21 | 4 | 4 | 4 | 0 | 0 |
| cam1 | 22 | 4 | 3 | 3 | 0 | 1 |
| cam1 | 23 | 4 | 3 | 2 | 1 | 2 |
| cam1 | 24 | 4 | 4 | 4 | 0 | 0 |
| cam1 | 25 | 4 | 4 | 4 | 0 | 0 |
| cam1 | 26 | 4 | 3 | 3 | 0 | 1 |
| cam1 | 27 | 4 | 3 | 3 | 0 | 1 |
| cam1 | 28 | 4 | 5 | 4 | 1 | 0 |
| cam1 | 29 | 4 | 4 | 4 | 0 | 0 |
| cam1 | 30 | 4 | 3 | 3 | 0 | 1 |
| cam1 | 31 | 3 | 2 | 2 | 0 | 1 |
| cam1 | 32 | 3 | 3 | 3 | 0 | 0 |
| cam1 | 33 | 3 | 3 | 3 | 0 | 0 |
| cam1 | 34 | 3 | 4 | 3 | 1 | 0 |
| cam1 | 35 | 3 | 2 | 2 | 0 | 1 |
| cam1 | 36 | 3 | 3 | 3 | 0 | 0 |
| cam1 | 37 | 3 | 2 | 2 | 0 | 1 |
| cam1 | 38 | 3 | 3 | 3 | 0 | 0 |
| cam1 | 39 | 3 | 3 | 3 | 0 | 0 |
First 40 of 70 rows.
- Reference rows: source = annotation; predictions: source = prediction. COCO conventions: IoU 0.50:0.05:0.95, 101 recall points, greedy matching by score within each image and class.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Object detection quality (COCO average precision)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method evaluate.detections 1.1.0 · spec b0d1d3d1ebbc0175
# Dataset: img4_tracks (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import 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 = "frame"
X0, Y0, X1, Y1 = "x0", "y0", "x1", "y1"
LABEL, SCORE = "label", "score"
SOURCE = "source"
CROWD = None
AREA = None
MASK = None
WIDTH = None
HEIGHT = None
IOU_TYPE = "bbox" # bbox | segm
MAX_DETS = int(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_tracks.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/video-frames/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,
})
This detection score treats each frame as a picture: it scored 70 frames against 201 reference boxes. The same table, read by the tracker, holds only 2 videos.
The average precision of 0.876 at IoU 0.5 describes these two videos well. As evidence about new cameras it rests on two sources, however many frames it counts.
May the model see the future?
ReadAn offline model may read the whole video: future frames, two-way attention, flow computed from the next frame. A live system can't. An onlineOnline inferenceProcessing observations as they arrive, without seeing the future. It doesn't have to update the model's weights. model sees only the past, so report offline and causal results as different conditions.
Reference · VID014 · Explained hereMoViNetsDesigns mobile-oriented video networks with efficient operations and streaming buffers. Causal processing can reuse recent state instead of repeatedly recomputing overlapping clips, making the family relevant to…MoViNets stream: each new frame is combined with a stream bufferStream bufferState a streaming video model carries from one chunk to the next, so it doesn't recompute overlapping clips. kept from earlier frames. In the reference's toy version the buffer starts empty, so the first output, 0.333, is pulled down by warm-up; later outputs are 1.0, 2.0 and 3.0. The buffer must be reset at every new video, or one video leaks into the next.
import numpy as np
buffer, outputs = np.zeros(2), []
for frame in [1., 2., 3., 4.]:
window = np.r_[buffer, frame] # past frames + this frame
outputs.append(window.mean())
buffer = window[-2:] # keep the last two
print(outputs)
buffer[:] = 0 # new video: reset the statebuffer <- c(0, 0); outputs <- c()
for (frame in c(1, 2, 3, 4)) {
window <- c(buffer, frame) # past frames + this frame
outputs <- c(outputs, mean(window))
buffer <- tail(window, 2) # keep the last two
}
print(outputs)
buffer[] <- 0 # new video: reset the stateWhat runs here
Read| Entry | In CodeSplash |
|---|---|
| VID005 · Temporal Segment Networks (TSN) | Explained here |
| VID014 · MoViNets | Explained here |
Check: frames, time and splits
CheckpointCheck yourself
Two clips both have 16 frames from 30-frames-per-second video. One takes consecutive frames, the other every eighth frame. What differs?
Show the answer
Answer: b
Shape hides time. The stride and the frame rate decide how long a clip lasts, so record them with the data.
Check yourself
What does a temporal segment network supervise?
Show the answer
Answer: b
The loss sits on the video-level consensus, so the video label need not apply to every sampled snippet.
Check yourself
Why does segment sampling suit long videos with scattered evidence?
Show the answer
Answer: a
K snippets cost the same however long the video is, and they reach every part of it. The price: a brief event can fall between snippets, and averaging drops order.
Check yourself
A rare action lasts under a second inside ten-minute videos. What should you check before trusting a TSN-style model on it?
Show the answer
Answer: b
A short event can fall between the sampled snippets. Compare uniform, random and dense sampling at the same compute, and report short events separately.
Check yourself
You have 200 videos cut into 20,000 clips. How should you split them for a test set?
Show the answer
Answer: c
Clips from one video are near-copies. Split by the unit your claim is about, then cut clips inside each split.
Check yourself
A streaming video model keeps a buffer of features from earlier frames. What must happen when a new video starts?
Show the answer
Answer: a
State carried across a video boundary mixes two unrelated videos. Reset it, and count warm-up frames when you measure latency and accuracy.
Check yourself
A model reaches higher accuracy when it is allowed to read frames after the moment it labels. How should you report that?
Show the answer
Answer: b
Seeing the future is legitimate offline but impossible live. They are different conditions; report both, labeled.
Recap
Recap- A clip is frames plus timestamps; frame count, stride and frame rate decide what it covers.
- TSN scores a few snippets spread across a video and averages them; averaging is cheap and forgets order.
- Split by source video (or person, camera, scene), never by frame or clip.
- Offline models may read the future; streaming models can't, carry state and must reset it between videos.
- CodeSplash doesn't load video; it scores and tracks tables made from it.
Concepts in this lesson