Lab: equal frame accuracy, unequal segments
Two predictions each get the same frames wrong in number, so their frame accuracy ties. One shifts a boundary; the other breaks actions into fragments. Count segments, match them by temporal IoU and watch segment F1 split them apart.
What runs in CodeSplash
- VID016Multi-Stage Temporal Convolutional Network (MS-TCN) Runs as a notebook
- VID017ActionFormer Runs as a notebook
- Segmentation quality (IoU, Dice, segment F1) Experimental
You will be able to
- Turn frame labels into segments and match them by temporal IoU
- Show that two predictions with equal frame accuracy can have very different segment F1
- State a matching protocol completely (intervals, classes, order, ties)
- Score time segments in CodeSplash at more than one threshold
The setup
ReadA 20-frame video holds two actions, ten frames each: class 0, then class 1. Two predictions each label exactly two frames wrong:
- Boundary error: the last frame of the first action is called class 1, and the last frame of the video is called class 0. The boundary is off by one, plus a one-frame blip at the end.
- Fragmentation: one frame in the middle of each action is flipped, splitting both actions in two.
Both get 18 of 20 frames right. Frame accuracy can't tell them apart.
The code
ExploreThe matching protocol is part of the result, so it is written out: half-open intervals [start, end), every class is an action (no ignored background), predictions processed in time order, each true segment matched at most once, to the unmatched same-class segment with the largest temporal IoU, counted only at IoU ≥ 0.5.
import numpy as np
def segments(labels): # (class, start, end), end exclusive
out, start = [], 0
for end in range(1, len(labels) + 1):
if end == len(labels) or labels[end] != labels[start]:
out.append((labels[start], start, end)); start = end
return out
def tiou(a, b):
inter = max(0, min(a[2], b[2]) - max(a[1], b[1]))
return inter / ((a[2] - a[1]) + (b[2] - b[1]) - inter)
def segment_f1(truth, pred, k=0.5):
gt, pr, used, tp = segments(truth), segments(pred), set(), 0
for p in pr: # time order
cand = [(tiou(p, g), j) for j, g in enumerate(gt) if j not in used and g[0] == p[0]]
if cand and max(cand)[0] >= k:
used.add(max(cand)[1]); tp += 1
fp, fn = len(pr) - tp, len(gt) - tp
return 2 * tp / (2 * tp + fp + fn), len(pr)
truth = np.array([0] * 10 + [1] * 10)
boundary = truth.copy(); boundary[9] = 1; boundary[19] = 0
fragment = truth.copy(); fragment[3] = 1; fragment[16] = 0
for name, p in [("boundary", boundary), ("fragment", fragment)]:
print(name, "frame accuracy", np.mean(p == truth), "F1, segments", segment_f1(truth, p))segments <- function(lab) { # start inclusive, end exclusive (0-based)
s <- c(1, which(diff(lab) != 0) + 1); e <- c(s[-1] - 1, length(lab))
data.frame(cls = lab[s], start = s - 1, end = e)
}
tiou <- function(a, b) {
inter <- max(0, min(a$end, b$end) - max(a$start, b$start))
inter / ((a$end - a$start) + (b$end - b$start) - inter)
}
segment_f1 <- function(truth, pred, k = 0.5) {
gt <- segments(truth); pr <- segments(pred); used <- rep(FALSE, nrow(gt)); tp <- 0
for (i in seq_len(nrow(pr))) { # time order
cand <- which(!used & gt$cls == pr$cls[i])
if (length(cand)) {
ov <- sapply(cand, function(j) tiou(pr[i, ], gt[j, ]))
if (max(ov) >= k) { used[cand[which.max(ov)]] <- TRUE; tp <- tp + 1 }
}
}
fp <- nrow(pr) - tp; fn <- nrow(gt) - tp
c(f1 = 2 * tp / (2 * tp + fp + fn), segments = nrow(pr))
}
truth <- c(rep(0, 10), rep(1, 10))
boundary <- truth; boundary[c(10, 20)] <- c(1, 0)
fragment <- truth; fragment[c(4, 17)] <- c(1, 0)
for (nm in c("boundary", "fragment")) {
p <- get(nm)
cat(nm, "frame accuracy", mean(p == truth), "F1, segments", segment_f1(truth, p), "\n")
}Notebook exercise · ~12 min
Equal frame accuracy, unequal segments
Score two action segmentations with the same frame accuracy and see segment counts and the edit score tell them apart.
- Frame accuracy
Store the frame accuracy of
shiftedand offlicker, in that order, inacc.Show a solution
Pythonacc = [np.mean(np.array(shifted) == np.array(truth)), np.mean(np.array(flicker) == np.array(truth))]Racc <- c(mean(shifted == truth), mean(flicker == truth)) - How many segments?
A segment is a run of equal labels. Store the number of segments in
shiftedand inflicker, in that order, inn_segments. The truth has three.Show a solution
Pythondef runs(x): return [v for i, v in enumerate(x) if i == 0 or v != x[i - 1]] n_segments = [len(runs(shifted)), len(runs(flicker))]Rruns <- function(x) rle(x)$values n_segments <- c(length(runs(shifted)), length(runs(flicker))) - The segmental edit score
The edit score compares the order of segments: 100 × (1 − levenshtein(predicted runs, true runs) / the larger of their two lengths). Store the edit scores of
shiftedandflicker, in that order, inedit.Show a solution
Pythonedit = [100 * (1 - levenshtein(runs(p), runs(truth)) / max(len(runs(p)), len(runs(truth)))) for p in (shifted, flicker)]Redit <- sapply(list(shifted, flicker), function(p) 100 * (1 - levenshtein(runs(p), runs(truth)) / max(length(runs(p)), length(runs(truth)))))
In the app this opens as a Python or R notebook with the sample data, and its checks mark your progress.
Predict, then run
PredictPredict first
Both predictions have the same frame accuracy. Which has the higher segment F1 at temporal IoU 0.5?
Reveal
The boundary error. It produces three segments: two match the truth well and one short blip is a false positive. The fragmentation produces six: two pieces match, and four fragments are false positives. Same frames wrong, very different segments. Run the code to see the numbers.
DExplorable · Frames versus segments: equal accuracy, unequal segmentations
Two action segmenters get the same share of frames right. Are they equally good?
Both predictions get the same share of frames right. How will their segmental F1 compare?
Both predictions get exactly this share of the 120 frames wrong.
Second prediction's errors
The first prediction is late at every boundary. The second scatters single wrong frames, or misses the short Lift action.
IoU for a segment hit (k)
A predicted segment matches a true one of the same action when their overlap (IoU) is at least k: F1@k.
Each frame of the second prediction takes the most common action in a window this wide. 1 means no smoothing.
- Reach
- Grasp
- Lift
- wrong frame
Segments: truth 5, late boundaries 5, second prediction 21. Both predictions have 10 wrong frames.
Commit your prediction above to see the result
Make your prediction to see the result.
Why systems report segment scores
ReadThis is the failure MS-TCN's smoothing stages target: a frame classifier that is right most of the time can still flicker, and each flicker is a new segment. Segment F1 counts them; so does the edit scoreSegmental edit scoreHow few segment insertions, deletions and swaps turn the predicted order of actions into the true order, scaled to 0–100., which compares the order of segments regardless of timing.
Reference · VID016 · Runs as a notebookMulti-Stage Temporal Convolutional Network (MS-TCN)Assigns an action label to every video time step and refines predictions through several temporal-convolution stages.Localization models like ActionFormer face the same issue in interval form: a correct action split into two predicted intervals yields one match and one false positive.
Reference · VID017 · Runs as a notebookActionFormerFinds action intervals in untrimmed video using a transformer-based temporal feature pyramid and per-location predictions.Two thresholds in CodeSplash
ExploreAcross 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.3, 0.622 at IoU 0.7.
- 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.3 | F1 | 0.7297 |
| IoU 0.3 | Precision | 0.6923 |
| IoU 0.3 | Recall | 0.7714 |
| IoU 0.7 | F1 | 0.6216 |
| IoU 0.7 | Precision | 0.5897 |
| IoU 0.7 | Recall | 0.6571 |
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 |
|---|---|---|---|---|---|
| music | 41.700 | 47 | 29.540 | 0.4993 | 0.6661 |
| noise | 71.760 | 71.900 | 62.110 | 0.7616 | 0.8647 |
| speech | 71.280 | 53.120 | 45.410 | 0.5749 | 0.7301 |
Segments matched at each IoU threshold
| IoU threshold | Matched | False alarms | Missed | Precision | Recall | F1 |
|---|---|---|---|---|---|---|
| 0.3000 | 27 | 12 | 8 | 0.6923 | 0.7714 | 0.7297 |
| 0.7000 | 23 | 16 | 12 | 0.5897 | 0.6571 | 0.6216 |
- Reference rows: source = annotation; predictions: source = prediction. Segments match within a recording and class, earliest 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 80c3b6f2f0a2fd85
# 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 <- NULL
KIND <- "intervals" # masks | intervals
BACKGROUND <- TRUE
THRESHOLDS <- as.numeric(unlist(c(0.3, 0.7)))
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-unscored-thresholds/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.3, 0.622 at IoU 0.7.
- 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 |
|---|---|---|---|---|---|
| music | 41.700 | 47 | 29.540 | 0.4993 | 0.6661 |
| noise | 71.760 | 71.900 | 62.110 | 0.7616 | 0.8647 |
| speech | 71.280 | 53.120 | 45.410 | 0.5749 | 0.7301 |
Segments matched at each IoU threshold
| IoU threshold | Matched | False alarms | Missed | Precision | Recall | F1 |
|---|---|---|---|---|---|---|
| 0.3000 | 27 | 12 | 8 | 0.6923 | 0.7714 | 0.7297 |
| 0.7000 | 23 | 16 | 12 | 0.5897 | 0.6571 | 0.6216 |
- Reference rows: source = annotation; predictions: source = prediction. Segments match within a recording and class, earliest 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 80c3b6f2f0a2fd85
# 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 = None
KIND = "intervals" # masks | intervals
BACKGROUND = True
THRESHOLDS = [float(t) for t in [0.3, 0.7]] 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-unscored-thresholds/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,
})
The same matching, run on a table of time segments at thresholds 0.3 and 0.7. Segment F1 is 0.730 at the looser one and 0.622 at the stricter one; recall falls from 0.771 to 0.657. Meanwhile time-weighted accuracy, the frame accuracy of intervals, is 0.742 at both, because it doesn't depend on a threshold.
Push the lab further
Read- Vary the threshold from 0.1 to 0.9 and plot F1 for both predictions.
- Make the blip longer and see when it becomes a "real" segment.
- Weight a short, critical action (say, a fall) and ask whether F1 treats missing it as seriously as you would.
- Change the tie rule. This fixture has no ties; others do, and the rule changes the score.
For real evaluation, use a documented benchmark implementation, keep whole videos (or subjects) in one split, and report uncertainty across independent videos.
What runs here
Read| Entry | In CodeSplash |
|---|---|
| VID016 · Multi-Stage Temporal Convolutional Network | Runs as a notebook (the reference program; no method) |
| VID017 · ActionFormer | Runs as a notebook (the reference program; no method) |
Check: the segments lab
CheckpointCheck yourself
Two segmentations each label two of twenty frames wrong. What can you conclude about their segment quality?
Show the answer
Answer: b
Frame accuracy ignores arrangement. Scattered errors create fragments; boundary errors don't.
Check yourself
Why does the fragmented prediction get a low segment F1?
Show the answer
Answer: a
Extra segments are false positives; F1 counts them even though they cover few frames.
Check yourself
Which details must a segment-F1 result state to be reproducible?
Show the answer
Answer: b
Changing any of these can change the score for the same predictions.
Check yourself
A localization model predicts one true action as two back-to-back intervals. How does segment matching at IoU 0.5 count it?
Show the answer
Answer: b
Each true segment can match once. The second piece has nothing left to match.
Check yourself
In the CodeSplash run, segment F1 changes with the threshold but time-weighted accuracy doesn't. Why?
Show the answer
Answer: b
Frame-style accuracy has no notion of a segment match; that's exactly why it can't see fragments.
Recap
Recap- Equal frame accuracy can hide very different segmentations.
- Segment F1 matches predicted to true segments by temporal IoU and counts fragments as false positives.
- The matching protocol is part of the score: write it down.
- CodeSplash scores time segments at any thresholds; the lab code runs as a notebook.
Concepts in this lesson