Scoring trackers: MOTA, IDF1 and HOTA
A tracker has to find objects and keep their identities. MOTA weighs mostly the first, IDF1 the second, and HOTA balances both across overlap thresholds. Learn to read all three, and why counting track ids miscounts objects.
What runs in CodeSplash
- EVA050HOTA multi-object tracking evaluation Runs as a notebook
- VID034Simple Online and Realtime Tracking (SORT) Runs in CodeSplash (Experimental)
- VID036ByteTrack Runs in CodeSplash (Experimental)
- Track objects across frames (SORT, ByteTrack, DeepSORT-style) Experimental
You will be able to
- Separate detection errors, identity errors and localization in a tracking result
- Read MOTA, IDF1, identity switches and fragmentations from a run
- Compute HOTA from detection and association accuracy and say what the geometric mean rewards
- Explain why the number of track ids overstates the number of objects
Three questions
ReadAgainst reference tracks, a tracking result answers three questions:
- Detection. Were the objects found in each frame, without false boxes?
- Association. Did each object keep one identity from start to end?
- Localization. How tightly do the tracked boxes fit?
No single number answers all three well, and the popular scores weigh them differently. Read at least two side by side.
MOTA and IDF1 on one run
Explore7 tracks from 184 detections in 2 sequences (SORT association); 178 detections joined a track. Against 7 reference tracks: MOTA 0.886, IDF1 0.939, 0 identity switches.
- Tracks
- 7
- MOTA
- 0.8856
- IDF1
- 0.9393
- Identity switches
- 0
Plots
Bars break where a track missed more than one frame.
View data
| media_id | Last frame | Track | frame |
|---|---|---|---|
| cam1 | 5 | 1 · person | 0 |
| cam1 | 11 | 1 · person | 7 |
| cam1 | 15 | 1 · person | 14 |
| cam1 | 22 | 1 · person | 17 |
| cam1 | 34 | 1 · person | 24 |
| cam1 | 39 | 1 · person | 36 |
| cam1 | 3 | 2 · person | 0 |
| cam1 | 6 | 2 · person | 5 |
| cam1 | 22 | 2 · person | 8 |
| cam1 | 26 | 2 · person | 24 |
| cam1 | 36 | 2 · person | 28 |
| cam1 | 39 | 2 · person | 38 |
| cam1 | 29 | 3 · car | 5 |
| cam1 | 21 | 4 · person | 18 |
| cam1 | 25 | 4 · person | 23 |
| cam1 | 30 | 4 · person | 27 |
| cam1 | 39 | 4 · person | 32 |
| cam2 | 10 | 5 · car | 0 |
| cam2 | 13 | 5 · car | 12 |
| cam2 | 17 | 5 · car | 15 |
| cam2 | 23 | 5 · car | 20 |
| cam2 | 25 | 5 · car | 25 |
| cam2 | 29 | 5 · car | 27 |
| cam2 | 23 | 6 · person | 3 |
| cam2 | 25 | 6 · person | 25 |
| cam2 | 29 | 6 · person | 27 |
| cam2 | 25 | 7 · person | 10 |
Assumptions
- Frames are in order — Tracks follow the frame numbers within each sequence; a gap between frame numbers counts as that many frames of motion and age.
- Objects move smoothly — The constant-velocity motion model expects small changes from frame to frame; fast jumps between frames break tracks.
Tracks
| Track | media_id | label | First frame | Last frame | Frames spanned | Detections | Mean score |
|---|---|---|---|---|---|---|---|
| 1 | cam1 | person | 0 | 39 | 40 | 34 | 0.7038 |
| 2 | cam1 | person | 0 | 39 | 40 | 35 | 0.7367 |
| 3 | cam1 | car | 5 | 29 | 25 | 25 | 0.7794 |
| 4 | cam1 | person | 18 | 39 | 22 | 19 | 0.8095 |
| 5 | cam2 | car | 0 | 29 | 30 | 24 | 0.7069 |
| 6 | cam2 | person | 3 | 29 | 27 | 25 | 0.7759 |
| 7 | cam2 | person | 10 | 25 | 16 | 16 | 0.8254 |
Against the reference tracks (IoU ≥ 0.5)
| Measure | Value | Meaning |
|---|---|---|
| MOTA | 0.8856 | 1 − (misses + false positives + identity switches) / reference boxes |
| IDF1 | 0.9393 | Share of boxes on the right identity (global track matching) |
| MOTP (mean IoU) | 0.8794 | Mean overlap of the paired boxes |
| Identity switches | 0 | A reference object took a different track |
| Fragmentations | 20 | A tracked object was lost and found again |
| Misses | 23 | Reference boxes with no track |
| False positives | 0 | Tracked boxes with no reference object |
| Mostly tracked | 7 | Reference tracks paired in at least 80% of their frames |
| Mostly lost | 0 | Reference tracks paired in under 20% of their frames |
- Tracks start from detections and are confirmed after 3 detections; a confirmed track ends after 30 frames without one. Boxes pair only within the same class. Constant-velocity Kalman filter per box coordinate; assignment by the Hungarian method (clean-room implementation from the published papers).
The exact R script · R R version 4.5.1 (2025-06-13)
# Track objects across frames (SORT, ByteTrack, DeepSORT-style)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method track.objects 1.1.1 · spec 6e6158204937fdf6
# Dataset: img4_tracks (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr) # cs_track_objects (tracker), cs_eval_mot (tracking metrics), cs_eval_stacked
# %% Data
SEQ <- "media_id"; FRAME <- "frame"
X0 <- "x0"; Y0 <- "y0"; X1 <- "x1"; Y1 <- "y1"
SCORE <- "score"
LABEL <- "label"
FEATURES <- c()
SOURCE <- "source"
TRUTH <- "track_id"
MODE <- "sort" # sort | bytetrack | deepsort
OPTS <- list(iou = 0.3, min_hits = as.integer(3), max_age = as.numeric(30),
min_score = 0, high = 0.6, low = 0.1,
low_iou = 0.5, max_cosine = 0.3, motion_weight = 0,
per_class = TRUE)
MOT_IOU <- 0.5
REF_LEVEL <- NULL
SOURCE_LEVELS <- c("annotation", "prediction") # stored order
# Reference tracks from a second table (option reference_table): its own column for each role, or NULL.
REF_ROLES <- NULL
FEATURES <- if (length(FEATURES)) as.character(FEATURES) else character(0)
columns <- unique(c(SEQ, FRAME, X0, Y0, X1, Y1, SCORE, LABEL, SOURCE, TRUTH, FEATURES))
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/img4_tracks.parquet", col_select = columns))
df$`__row` <- seq_len(nrow(df)) - 1L # position in the analysis input
n_input <- nrow(df)
if (MODE == "bytetrack" && is.null(SCORE)) cs_error("CS_E_INVALID_OPTION", option = "Association", allowed = "SORT or DeepSORT-style unless a confidence score column is set", value = "ByteTrack")
if (MODE == "deepsort" && !length(FEATURES)) cs_error("CS_E_INVALID_OPTION", option = "Association", allowed = "SORT or ByteTrack unless embedding columns are set", value = "DeepSORT-style")
pre_warnings <- list()
if (!is.null(REF_ROLES)) {
# The reference table's rows go above the detections under an added source column (twin: with_reference).
w <- cs_eval_with_reference(df, cs_graph_dataset_option("target/academy-parity/run-8142/track.objects/sort-with-reference/out-r", "reference_table"),
list(sequence = SEQ, frame = FRAME, x0 = X0, y0 = Y0, x1 = X1, y1 = Y1, score = SCORE, label = LABEL, truth = TRUTH),
REF_ROLES, list(label = "Class"), SOURCE, REF_LEVEL, c("sequence", "frame", "x0", "y0", "x1", "y1", if (!is.null(LABEL)) "label"))
df <- w$df
pre_warnings <- w$warnings
wc <- w$columns
SEQ <- wc$sequence; FRAME <- wc$frame; X0 <- wc$x0; Y0 <- wc$y0; X1 <- wc$x1; Y1 <- wc$y1
LABEL <- wc$label; TRUTH <- wc$truth
SOURCE <- w$source; REF_LEVEL <- w$reference; SOURCE_LEVELS <- w$levels
}
needed <- c(SEQ, FRAME, X0, Y0, X1, Y1, LABEL)
numeric_cols <- c(FRAME, X0, Y0, X1, Y1, SCORE, FEATURES)
if (!is.null(SOURCE)) {
st <- cs_eval_stacked(df, c(needed, SOURCE), numeric_cols, SOURCE, REF_LEVEL, SOURCE_LEVELS)
df <- st$df
is_ref <- st$is_ref
warnings <- c(pre_warnings, st$warnings)
} else {
if (n_input == 0L) cs_error("CS_E_NO_ROWS")
for (c in needed) if (all(is.na(df[[c]]))) cs_error("CS_E_ALL_MISSING", column = c)
keep <- rep(TRUE, n_input)
for (c in needed) keep <- keep & !is.na(df[[c]])
df <- df[keep, , drop = FALSE]
warnings <- if (nrow(df) < n_input) list(cs_warning("CS_W_ROWS_DROPPED", dropped = n_input - nrow(df), total = n_input)) else list()
if (nrow(df) == 0L) cs_error("CS_E_NO_ROWS")
for (c in numeric_cols) {
k <- sum(is.infinite(as.numeric(df[[c]])))
if (k > 0) cs_error("CS_E_NOT_FINITE", column = c, count = k)
}
is_ref <- logical(nrow(df))
}
box <- cbind(as.numeric(df[[X0]]), as.numeric(df[[Y0]]), as.numeric(df[[X1]]), as.numeric(df[[Y1]]))
bad <- (box[, 3] < box[, 1]) | (box[, 4] < box[, 2])
if (any(bad)) cs_error("CS_E_INVALID_VALUES", column = sprintf("%s and %s", X1, Y1), requirement = sprintf("at least %s and %s", X0, Y0), count = sum(bad))
det <- !is_ref
if (!is.null(SCORE)) {
no_score <- det & is.na(as.numeric(df[[SCORE]]))
if (any(no_score)) {
warnings <- c(warnings, sprintf("%d detections have no %s and were left out.", sum(no_score), SCORE))
det <- det & !no_score
}
}
if (length(FEATURES)) {
no_feat <- det & !stats::complete.cases(df[FEATURES])
if (any(no_feat)) {
warnings <- c(warnings, sprintf("%d detections miss an embedding value and were left out.", sum(no_feat)))
det <- det & !no_feat
}
}
if (sum(det) < 2L) cs_error("CS_E_TOO_FEW_ROWS", what = "Tracking", min = 2, n = sum(det))
# %% Tracks
di <- which(det)
seq_all <- as.character(df[[SEQ]])
frame_all <- as.numeric(df[[FRAME]])
lab_all <- if (!is.null(LABEL)) as.character(df[[LABEL]]) else NULL
feats <- if (length(FEATURES)) as.matrix(df[di, FEATURES, drop = FALSE]) else NULL
if (!is.null(feats)) storage.mode(feats) <- "double"
res <- cs_track_objects(seq_all[di], frame_all[di], box[di, , drop = FALSE], if (!is.null(SCORE)) as.numeric(df[[SCORE]])[di] else NULL,
if (!is.null(LABEL)) lab_all[di] else NULL, feats, MODE, OPTS)
tid_det <- res$track
track_id <- rep(NA_integer_, n_input) # per input row; rows that weren't tracked stay empty
track_id[df$`__row`[di][tid_det > 0L] + 1L] <- tid_det[tid_det > 0L]
tracks <- res$tracks
n_tracks <- length(tracks)
n_assigned <- sum(tid_det > 0L)
# %% Against the reference tracks
metrics <- NULL
switch_events <- list()
if (!is.null(SOURCE) && !is.null(TRUTH) && sum(is_ref) > 0) {
truth_ok <- is_ref & !is.na(df[[TRUTH]])
if (sum(is_ref & !truth_ok) > 0) warnings <- c(warnings, sprintf("%d reference boxes have no %s and were left out of the tracking metrics.", sum(is_ref & !truth_ok), TRUTH))
truth_all <- as.character(df[[TRUTH]])
gi <- which(truth_ok)
hi <- di[tid_det > 0L]
hyp_of <- integer(nrow(df))
hyp_of[di] <- tid_det
seqs <- list()
for (sq in sort(unique(c(seq_all[gi], seq_all[hi])), method = "radix")) {
g_s <- gi[seq_all[gi] == sq]
h_s <- hi[seq_all[hi] == sq]
frames <- list()
for (f in sort(unique(c(frame_all[g_s], frame_all[h_s])))) {
g_f <- g_s[frame_all[g_s] == f]
h_f <- h_s[frame_all[h_s] == f]
# paste() would recycle an empty id vector into one id: frames with predictions but no reference boxes get none.
gt_ids <- if (length(g_f)) paste(sq, truth_all[g_f], sep = "\u001f") else character(0)
frames[[length(frames) + 1L]] <- list(frame = f, gt_ids = gt_ids, gt_boxes = box[g_f, , drop = FALSE],
hyp_ids = as.character(hyp_of[h_f]), hyp_boxes = box[h_f, , drop = FALSE])
}
seqs[[length(seqs) + 1L]] <- frames
}
metrics <- cs_eval_mot(seqs, MOT_IOU)
switch_events <- metrics$switch_events
}
# %% Assumptions
assumptions <- list(
list(key = "frames", label = "Frames are in order", status = "info",
detail = "Tracks follow the frame numbers within each sequence; a gap between frame numbers counts as that many frames of motion and age."),
list(key = "motion", label = "Objects move smoothly", status = "info",
detail = "The constant-velocity motion model expects small changes from frame to frame; fast jumps between frames break tracks.")
)
if (length(FEATURES)) assumptions[[3]] <- list(key = "appearance", label = "Embeddings describe appearance", status = "info",
detail = "DeepSORT-style matching trusts the embedding columns to tell objects apart; embeddings of the same object should be close.")
# %% Result
f3 <- function(v) if (is.null(v) || is.na(v)) "—" else sprintf("%.3f", v)
tl <- vapply(tracks, function(t) if (is.na(t$label)) NA_character_ else t$label, character(1))
labels_seen <- sort(unique(tl[!is.na(tl)]), method = "radix")
seq_list <- sort(unique(seq_all[di]), method = "radix")
n_frames <- sum(!duplicated(paste(seq_all[di], sprintf("%.17g", frame_all[di]), sep = "\u001f")))
nz <- function(v) if (is.null(v)) NA_real_ else v
values <- list(association = MODE, n_sequences = length(seq_list), n_frames = n_frames, n_detections = length(di), n_tracks = n_tracks,
n_assigned = n_assigned, n_unassigned = length(di) - n_assigned,
mean_track_length = if (n_tracks) mean(vapply(tracks, function(t) t$n_detections, numeric(1))) else NA_real_,
mota = NA_real_, motp = NA_real_, idf1 = NA_real_, idp = NA_real_, idr = NA_real_, id_switches = NA_real_, fragmentations = NA_real_,
false_positives = NA_real_, misses = NA_real_, mostly_tracked = NA_real_, partially_tracked = NA_real_, mostly_lost = NA_real_,
precision = NA_real_, recall = NA_real_, n_gt_tracks = NA_real_, n_gt_boxes = NA_real_, track_id = I(track_id))
for (lab in labels_seen) values[[sprintf("tracks[%s]", lab)]] <- sum(tl == lab, na.rm = TRUE)
if (!is.null(metrics)) {
values$mota <- metrics$mota; values$motp <- metrics$motp; values$idf1 <- metrics$idf1; values$idp <- metrics$idp; values$idr <- metrics$idr
values$id_switches <- metrics$switches; values$fragmentations <- metrics$fragmentations; values$false_positives <- metrics$false_positives
values$misses <- metrics$misses; values$mostly_tracked <- metrics$mostly_tracked; values$partially_tracked <- metrics$partially_tracked
values$mostly_lost <- metrics$mostly_lost; values$precision <- metrics$precision; values$recall <- metrics$recall
values$n_gt_tracks <- metrics$n_gt_tracks; values$n_gt_boxes <- metrics$objects
}
trk_rows <- lapply(tracks, function(t) list(track_id = t$track_id, sequence = t$sequence, label = t$label, first_frame = t$first_frame,
last_frame = t$last_frame, span = t$last_frame - t$first_frame + 1, n_detections = t$n_detections,
mean_score = t$mean_score))
tcols <- c(list(list(key = "track_id", label = "Track", type = "integer"), list(key = "sequence", label = SEQ, type = "string")),
if (!is.null(LABEL)) list(list(key = "label", label = LABEL, type = "string")),
list(list(key = "first_frame", label = "First frame", type = "number"), list(key = "last_frame", label = "Last frame", type = "number"),
list(key = "span", label = "Frames spanned", type = "number"), list(key = "n_detections", label = "Detections", type = "integer")),
if (!is.null(SCORE)) list(list(key = "mean_score", label = "Mean score", type = "number")))
tables <- list(list(key = "tracks", title = "Tracks", columns = tcols, rows = utils::head(trk_rows, 500),
note = if (length(trk_rows) > 500) "First 500 tracks." else NULL))
if (!is.null(metrics)) {
mrows <- list(list("MOTA", metrics$mota, "1 − (misses + false positives + identity switches) / reference boxes"),
list("IDF1", metrics$idf1, "Share of boxes on the right identity (global track matching)"),
list("MOTP (mean IoU)", metrics$motp, "Mean overlap of the paired boxes"),
list("Identity switches", metrics$switches, "A reference object took a different track"),
list("Fragmentations", metrics$fragmentations, "A tracked object was lost and found again"),
list("Misses", metrics$misses, "Reference boxes with no track"), list("False positives", metrics$false_positives, "Tracked boxes with no reference object"),
list("Mostly tracked", metrics$mostly_tracked, "Reference tracks paired in at least 80% of their frames"),
list("Mostly lost", metrics$mostly_lost, "Reference tracks paired in under 20% of their frames"))
tables[[length(tables) + 1L]] <- list(key = "mot", title = sprintf("Against the reference tracks (IoU ≥ %g)", MOT_IOU),
columns = list(list(key = "metric", label = "Measure", type = "string"), list(key = "value", label = "Value", type = "number"),
list(key = "meaning", label = "Meaning", type = "string")),
rows = lapply(mrows, function(r) list(metric = r[[1]], value = r[[2]], meaning = r[[3]])))
if (length(switch_events)) {
tables[[length(tables) + 1L]] <- list(key = "switches", title = "Identity switches",
columns = list(list(key = "sequence", label = SEQ, type = "string"), list(key = "frame", label = "Frame", type = "number"),
list(key = "object", label = "Reference object", type = "string"), list(key = "from", label = "From track", type = "string"),
list(key = "to", label = "To track", type = "string")),
rows = lapply(utils::head(switch_events, 200), function(e) { p <- strsplit(e$object, "\u001f", fixed = TRUE)[[1]]
list(sequence = p[1], frame = e$frame, object = p[2], from = e$from, to = e$to) }),
note = if (length(switch_events) > 200) "First 200 switches." else NULL)
}
}
charts <- list()
if (n_tracks) {
lane_of <- function(t) paste0(t$track_id, if (!is.na(t$label)) paste0(" · ", t$label) else "")
shown <- utils::head(tracks, 60)
color_of <- function(t) if (length(seq_list) > 1L) t$sequence else if (!is.na(t$label)) t$label else t$sequence
ln <- character(0); s0 <- numeric(0); s1 <- numeric(0); col <- character(0); ev <- character(0)
fr_det <- frame_all[di]
for (t in shown) {
fr <- sort(fr_det[tid_det == t$track_id])
brk <- which(diff(fr) > 1)
starts <- c(fr[1], fr[brk + 1L])
ends <- c(fr[brk], fr[length(fr)])
ln <- c(ln, rep(lane_of(t), length(starts))); s0 <- c(s0, starts); s1 <- c(s1, ends)
col <- c(col, rep(color_of(t), length(starts))); ev <- c(ev, rep(NA_character_, length(starts)))
}
shown_ids <- vapply(shown, function(t) t$track_id, numeric(1))
for (e in switch_events) {
to <- as.integer(e$to)
if (to %in% shown_ids) {
t <- shown[[which(shown_ids == to)[1]]]
ln <- c(ln, lane_of(t)); s0 <- c(s0, e$frame); s1 <- c(s1, e$frame); col <- c(col, color_of(t)); ev <- c(ev, "Identity switch")
}
}
roles <- list(lane = cs_col("Track", ln, "categorical", levels = vapply(shown, lane_of, character(1))),
start = cs_col(FRAME, s0, "numeric"), end = cs_col("Last frame", s1, "numeric"),
color = cs_col(if (length(seq_list) > 1L) SEQ else if (!is.null(LABEL)) LABEL else SEQ, col, "categorical"))
if (any(!is.na(ev))) roles$event <- cs_col("Event", ev, "categorical")
charts[[1]] <- cs_chart("timeline", "track-timeline", "When each track was seen", roles,
note = paste0(if (n_tracks > 60) "The first 60 tracks. " else "", "Bars break where a track missed more than one frame."))
}
out <- cs_ml_out_dir("target/academy-parity/run-8142/track.objects/sort-with-reference/out-r")
labels_path <- file.path(out, "labels.parquet")
nanoparquet::write_parquet(data.frame(row = as.numeric(seq_len(n_input) - 1L), cluster = as.numeric(ifelse(is.na(track_id), -1L, track_id))), labels_path)
names_mode <- c(sort = "SORT", bytetrack = "ByteTrack", deepsort = "DeepSORT-style")
summary <- sprintf("%d track%s from %d detections in %d sequence%s (%s association); %d detections joined a track.", n_tracks, if (n_tracks != 1) "s" else "",
length(di), length(seq_list), if (length(seq_list) != 1) "s" else "", names_mode[[MODE]], n_assigned)
if (!is.null(metrics)) summary <- paste0(summary, sprintf(" Against %d reference tracks: MOTA %s, IDF1 %s, %d identity switches.", as.integer(metrics$n_gt_tracks),
f3(metrics$mota), f3(metrics$idf1), as.integer(metrics$switches)))
cs_publish(list(
method = "track.objects",
methodVersion = "1.1.1",
title = "Object tracks",
engine = cs_engine_info("nanoparquet"),
n = nrow(df),
summary = summary,
statistics = c(list(list(key = "n_tracks", label = "Tracks", value = n_tracks)),
if (!is.null(metrics)) list(list(key = "mota", label = "MOTA", value = metrics$mota), list(key = "idf1", label = "IDF1", value = metrics$idf1),
list(key = "id_switches", label = "Identity switches", value = metrics$switches))),
tables = tables,
assumptions = assumptions,
warnings = warnings,
notes = list(paste0(sprintf("Tracks start from detections and are confirmed after %d detections; a confirmed track ends after %g frames without one. ", OPTS$min_hits, OPTS$max_age),
if (!is.null(LABEL) && OPTS$per_class) "Boxes pair only within the same class. " else "",
"Constant-velocity Kalman filter per box coordinate; assignment by the Hungarian method (clean-room implementation from the published papers).")),
charts = charts,
artifacts = list(list(key = "labels", path = labels_path, format = "parquet")),
values = values
))
7 tracks from 184 detections in 2 sequences (SORT association); 178 detections joined a track. Against 7 reference tracks: MOTA 0.886, IDF1 0.939, 0 identity switches.
- Tracks
- 7
- MOTA
- 0.8856
- IDF1
- 0.9393
- Identity switches
- 0
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Frames are in order — Tracks follow the frame numbers within each sequence; a gap between frame numbers counts as that many frames of motion and age.
- Objects move smoothly — The constant-velocity motion model expects small changes from frame to frame; fast jumps between frames break tracks.
Tracks
| Track | media_id | label | First frame | Last frame | Frames spanned | Detections | Mean score |
|---|---|---|---|---|---|---|---|
| 1 | cam1 | person | 0 | 39 | 40 | 34 | 0.7038 |
| 2 | cam1 | person | 0 | 39 | 40 | 35 | 0.7367 |
| 3 | cam1 | car | 5 | 29 | 25 | 25 | 0.7794 |
| 4 | cam1 | person | 18 | 39 | 22 | 19 | 0.8095 |
| 5 | cam2 | car | 0 | 29 | 30 | 24 | 0.7069 |
| 6 | cam2 | person | 3 | 29 | 27 | 25 | 0.7759 |
| 7 | cam2 | person | 10 | 25 | 16 | 16 | 0.8254 |
Against the reference tracks (IoU ≥ 0.5)
| Measure | Value | Meaning |
|---|---|---|
| MOTA | 0.8856 | 1 − (misses + false positives + identity switches) / reference boxes |
| IDF1 | 0.9393 | Share of boxes on the right identity (global track matching) |
| MOTP (mean IoU) | 0.8794 | Mean overlap of the paired boxes |
| Identity switches | 0 | A reference object took a different track |
| Fragmentations | 20 | A tracked object was lost and found again |
| Misses | 23 | Reference boxes with no track |
| False positives | 0 | Tracked boxes with no reference object |
| Mostly tracked | 7 | Reference tracks paired in at least 80% of their frames |
| Mostly lost | 0 | Reference tracks paired in under 20% of their frames |
- Tracks start from detections and are confirmed after 3 detections; a confirmed track ends after 30 frames without one. Boxes pair only within the same class. Constant-velocity Kalman filter per box coordinate; assignment by the Hungarian method (clean-room implementation from the published papers).
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Track objects across frames (SORT, ByteTrack, DeepSORT-style)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method track.objects 1.1.1 · spec 6e6158204937fdf6
# Dataset: img4_tracks (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import os
import numpy as np
import pandas as pd
import codesplash as cs
from codesplash.evaluate import mot # twin: codesplashr cs_eval_mot
from codesplash.evaluate.stacked import stacked # twin: cs_eval_stacked
from codesplash import ml as csml
from codesplash.track import objects as tr # twin: codesplashr cs_track_objects
# %% Data
SEQ, FRAME = "media_id", "frame"
X0, Y0, X1, Y1 = "x0", "y0", "x1", "y1"
SCORE = "score"
LABEL = "label"
FEATURES = []
SOURCE = "source"
TRUTH = "track_id"
MODE = "sort" # sort | bytetrack | deepsort
OPTS = {"iou": 0.3, "min_hits": int(3), "max_age": float(30),
"min_score": 0, "high": 0.6, "low": 0.1,
"low_iou": 0.5, "max_cosine": 0.3, "motion_weight": 0,
"per_class": True}
MOT_IOU = 0.5
REF_LEVEL = None
SOURCE_LEVELS = ["annotation", "prediction"] # stored order
# Reference tracks from a second table (option reference_table): its own column for each role, or None.
REF_ROLES = None
columns = list(dict.fromkeys(c for c in [SEQ, FRAME, X0, Y0, X1, Y1, SCORE, LABEL, SOURCE, TRUTH] + FEATURES if c))
df = pd.read_parquet("tests/parity/fixtures/img4_tracks.parquet", columns=columns)
df["__row"] = np.arange(len(df)) # position in the analysis input
n_input = len(df)
if MODE == "bytetrack" and not SCORE:
cs.cs_error("CS_E_INVALID_OPTION", option="Association", allowed="SORT or DeepSORT-style unless a confidence score column is set", value="ByteTrack")
if MODE == "deepsort" and not FEATURES:
cs.cs_error("CS_E_INVALID_OPTION", option="Association", allowed="SORT or ByteTrack unless embedding columns are set", value="DeepSORT-style")
pre_warnings = []
if REF_ROLES is not None:
# The reference table's rows go above the detections under an added source column (twin: cs_eval_with_reference).
from codesplash.graph import dataset_option # the table the host wrote for the option
from codesplash.evaluate.stacked import with_reference
w = with_reference(df, dataset_option("target/academy-parity/run-8142/track.objects/sort-with-reference/out-python", "reference_table"),
{"sequence": SEQ, "frame": FRAME, "x0": X0, "y0": Y0, "x1": X1, "y1": Y1, "score": SCORE, "label": LABEL, "truth": TRUTH},
REF_ROLES, {"label": "Class"}, SOURCE, REF_LEVEL, ["sequence", "frame", "x0", "y0", "x1", "y1"] + (["label"] if LABEL else []))
df, pre_warnings, wc = w["df"], w["warnings"], w["columns"]
SEQ, FRAME, X0, Y0, X1, Y1 = wc["sequence"], wc["frame"], wc["x0"], wc["y0"], wc["x1"], wc["y1"]
LABEL, TRUTH = wc["label"], wc["truth"]
SOURCE, REF_LEVEL, SOURCE_LEVELS = w["source"], w["reference"], w["levels"]
needed = [SEQ, FRAME, X0, Y0, X1, Y1] + ([LABEL] if LABEL else [])
numeric = [c for c in [FRAME, X0, Y0, X1, Y1, SCORE] if c] + FEATURES
if SOURCE:
st = stacked(df, needed + [SOURCE], numeric, SOURCE, REF_LEVEL, SOURCE_LEVELS)
df, is_ref, warnings = st["df"], st["is_ref"], pre_warnings + st["warnings"]
else:
if n_input == 0:
cs.cs_error("CS_E_NO_ROWS")
for c in needed:
if df[c].isna().all():
cs.cs_error("CS_E_ALL_MISSING", column=c)
keep = np.ones(n_input, dtype=bool)
for c in needed:
keep &= df[c].notna().to_numpy()
df = df.loc[keep].reset_index(drop=True)
warnings = [cs.cs_warning("CS_W_ROWS_DROPPED", dropped=int(n_input - len(df)), total=n_input)] if len(df) < n_input else []
if len(df) == 0:
cs.cs_error("CS_E_NO_ROWS")
for c in numeric:
k = int(np.isinf(df[c].to_numpy(dtype=float, na_value=np.nan)).sum())
if k:
cs.cs_error("CS_E_NOT_FINITE", column=c, count=k)
is_ref = np.zeros(len(df), dtype=bool)
box = df[[X0, Y0, X1, Y1]].to_numpy(dtype=float)
bad = (box[:, 2] < box[:, 0]) | (box[:, 3] < box[:, 1])
if bad.any():
cs.cs_error("CS_E_INVALID_VALUES", column=f"{X1} and {Y1}", requirement=f"at least {X0} and {Y0}", count=int(bad.sum()))
det = ~is_ref
if SCORE:
no_score = det & np.isnan(df[SCORE].to_numpy(dtype=float, na_value=np.nan))
if no_score.any():
warnings.append(f"{int(no_score.sum())} detections have no {SCORE} and were left out.")
det &= ~no_score
if FEATURES:
no_feat = det & df[FEATURES].isna().any(axis=1).to_numpy()
if no_feat.any():
warnings.append(f"{int(no_feat.sum())} detections miss an embedding value and were left out.")
det &= ~no_feat
if int(det.sum()) < 2:
cs.cs_error("CS_E_TOO_FEW_ROWS", what="Tracking", min=2, n=int(det.sum()))
# %% Tracks
di = np.flatnonzero(det)
seq_all = np.asarray([str(x) for x in df[SEQ].tolist()], dtype=object)
frame_all = df[FRAME].to_numpy(dtype=float)
lab_all = np.asarray([str(x) for x in df[LABEL].tolist()], dtype=object) if LABEL else None
res = tr.track(seq_all[di], frame_all[di], box[di], df[SCORE].to_numpy(dtype=float)[di] if SCORE else None,
lab_all[di] if LABEL else None, df[FEATURES].to_numpy(dtype=float)[di] if FEATURES else None, MODE, **OPTS)
tid_det = res["track"]
track_id = [None] * n_input # per input row; rows that weren't tracked stay empty
for k, i in enumerate(di):
if tid_det[k] > 0:
track_id[int(df["__row"].iloc[i])] = int(tid_det[k])
tracks = res["tracks"]
n_tracks = len(tracks)
n_assigned = int(np.sum(tid_det > 0))
# %% Against the reference tracks
metrics = None
switch_events = []
if SOURCE and TRUTH and int(is_ref.sum()):
truth_ok = is_ref & df[TRUTH].notna().to_numpy()
if int((is_ref & ~truth_ok).sum()):
warnings.append(f"{int((is_ref & ~truth_ok).sum())} reference boxes have no {TRUTH} and were left out of the tracking metrics.")
truth_all = np.asarray([str(x) for x in df[TRUTH].tolist()], dtype=object)
gi = np.flatnonzero(truth_ok)
hi = di[tid_det > 0]
hyp_id = {int(i): str(int(t)) for i, t in zip(di, tid_det) if t > 0}
seqs = []
for sq in sorted(set(seq_all[gi].tolist()) | set(seq_all[hi].tolist())):
g_s = gi[seq_all[gi] == sq]
h_s = hi[seq_all[hi] == sq]
frames = []
for f in sorted(set(frame_all[g_s].tolist()) | set(frame_all[h_s].tolist())):
g_f = g_s[frame_all[g_s] == f]
h_f = h_s[frame_all[h_s] == f]
frames.append({"frame": f, "gt_ids": [f"{sq}\x1f{truth_all[i]}" for i in g_f], "gt_boxes": box[g_f],
"hyp_ids": [hyp_id[int(i)] for i in h_f], "hyp_boxes": box[h_f]})
seqs.append(frames)
metrics = mot.clear_mot(seqs, MOT_IOU)
switch_events = metrics["switch_events"]
# %% Assumptions
assumptions = [
{"key": "frames", "label": "Frames are in order", "status": "info",
"detail": "Tracks follow the frame numbers within each sequence; a gap between frame numbers counts as that many frames of motion and age."},
{"key": "motion", "label": "Objects move smoothly", "status": "info",
"detail": "The constant-velocity motion model expects small changes from frame to frame; fast jumps between frames break tracks."},
]
if FEATURES:
assumptions.append({"key": "appearance", "label": "Embeddings describe appearance", "status": "info",
"detail": "DeepSORT-style matching trusts the embedding columns to tell objects apart; embeddings of the same object should be close."})
# %% Result
f3 = lambda v: "—" if v is None else f"{v:.3f}"
labels_seen = sorted(set(t["label"] for t in tracks if t["label"] is not None))
seq_list = sorted(set(seq_all[di].tolist()))
n_frames = len(set(zip(seq_all[di].tolist(), frame_all[di].tolist())))
values = {"association": MODE, "n_sequences": len(seq_list), "n_frames": n_frames, "n_detections": int(di.size), "n_tracks": n_tracks,
"n_assigned": n_assigned, "n_unassigned": int(di.size - n_assigned),
"mean_track_length": float(np.mean([t["n_detections"] for t in tracks])) if tracks else None,
"mota": None, "motp": None, "idf1": None, "idp": None, "idr": None, "id_switches": None, "fragmentations": None,
"false_positives": None, "misses": None, "mostly_tracked": None, "partially_tracked": None, "mostly_lost": None,
"precision": None, "recall": None, "n_gt_tracks": None, "n_gt_boxes": None, "track_id": track_id}
for lab in labels_seen:
values[f"tracks[{lab}]"] = sum(1 for t in tracks if t["label"] == lab)
if metrics is not None:
values.update({"mota": metrics["mota"], "motp": metrics["motp"], "idf1": metrics["idf1"], "idp": metrics["idp"], "idr": metrics["idr"],
"id_switches": metrics["switches"], "fragmentations": metrics["fragmentations"], "false_positives": metrics["false_positives"],
"misses": metrics["misses"], "mostly_tracked": metrics["mostly_tracked"], "partially_tracked": metrics["partially_tracked"],
"mostly_lost": metrics["mostly_lost"], "precision": metrics["precision"], "recall": metrics["recall"],
"n_gt_tracks": metrics["n_gt_tracks"], "n_gt_boxes": metrics["objects"]})
trk_rows = [{"track_id": t["track_id"], "sequence": t["sequence"], "label": t["label"], "first_frame": t["first_frame"], "last_frame": t["last_frame"],
"span": t["last_frame"] - t["first_frame"] + 1.0, "n_detections": t["n_detections"], "mean_score": t["mean_score"]} for t in tracks]
tables = [{"key": "tracks", "title": "Tracks",
"columns": [{"key": "track_id", "label": "Track", "type": "integer"}, {"key": "sequence", "label": SEQ, "type": "string"}]
+ ([{"key": "label", "label": LABEL, "type": "string"}] if LABEL else [])
+ [{"key": "first_frame", "label": "First frame", "type": "number"}, {"key": "last_frame", "label": "Last frame", "type": "number"},
{"key": "span", "label": "Frames spanned", "type": "number"}, {"key": "n_detections", "label": "Detections", "type": "integer"}]
+ ([{"key": "mean_score", "label": "Mean score", "type": "number"}] if SCORE else []),
"rows": trk_rows[:500], "note": "First 500 tracks." if len(trk_rows) > 500 else None}]
if metrics is not None:
mrows = [("MOTA", metrics["mota"], "1 − (misses + false positives + identity switches) / reference boxes"),
("IDF1", metrics["idf1"], "Share of boxes on the right identity (global track matching)"),
("MOTP (mean IoU)", metrics["motp"], "Mean overlap of the paired boxes"),
("Identity switches", metrics["switches"], "A reference object took a different track"),
("Fragmentations", metrics["fragmentations"], "A tracked object was lost and found again"),
("Misses", metrics["misses"], "Reference boxes with no track"), ("False positives", metrics["false_positives"], "Tracked boxes with no reference object"),
("Mostly tracked", metrics["mostly_tracked"], "Reference tracks paired in at least 80% of their frames"),
("Mostly lost", metrics["mostly_lost"], "Reference tracks paired in under 20% of their frames")]
tables.append({"key": "mot", "title": f"Against the reference tracks (IoU ≥ {MOT_IOU:g})",
"columns": [{"key": "metric", "label": "Measure", "type": "string"}, {"key": "value", "label": "Value", "type": "number"},
{"key": "meaning", "label": "Meaning", "type": "string"}],
"rows": [{"metric": a, "value": b, "meaning": c} for a, b, c in mrows]})
if switch_events:
tables.append({"key": "switches", "title": "Identity switches",
"columns": [{"key": "sequence", "label": SEQ, "type": "string"}, {"key": "frame", "label": "Frame", "type": "number"},
{"key": "object", "label": "Reference object", "type": "string"}, {"key": "from", "label": "From track", "type": "string"},
{"key": "to", "label": "To track", "type": "string"}],
"rows": [{"sequence": e["object"].split("\x1f")[0], "frame": e["frame"], "object": e["object"].split("\x1f")[1],
"from": e["from"], "to": e["to"]} for e in switch_events[:200]],
"note": "First 200 switches." if len(switch_events) > 200 else None})
charts = []
if tracks:
lane_of = {t["track_id"]: f"{t['track_id']}" + (f" · {t['label']}" if t["label"] is not None else "") for t in tracks}
shown = tracks[:60]
ln, s0, s1, col, ev = [], [], [], [], []
for t in shown:
fr = np.sort(frame_all[di][tid_det == t["track_id"]])
brk = np.flatnonzero(np.diff(fr) > 1.0)
starts = np.concatenate([[fr[0]], fr[brk + 1]])
ends = np.concatenate([fr[brk], [fr[-1]]])
for a, b in zip(starts, ends):
ln.append(lane_of[t["track_id"]])
s0.append(float(a))
s1.append(float(b))
col.append(t["sequence"] if len(seq_list) > 1 else (t["label"] if t["label"] is not None else t["sequence"]))
ev.append(None)
shown_ids = {t["track_id"] for t in shown}
for e in switch_events:
if int(e["to"]) in shown_ids:
t = next(x for x in shown if x["track_id"] == int(e["to"]))
ln.append(lane_of[t["track_id"]])
s0.append(float(e["frame"]))
s1.append(float(e["frame"]))
col.append(t["sequence"] if len(seq_list) > 1 else (t["label"] if t["label"] is not None else t["sequence"]))
ev.append("Identity switch")
roles = {"lane": cs.col("Track", ln, "categorical", levels=[lane_of[t["track_id"]] for t in shown]),
"start": cs.col(FRAME, s0, "numeric"), "end": cs.col("Last frame", s1, "numeric"),
"color": cs.col(SEQ if len(seq_list) > 1 else (LABEL or SEQ), col, "categorical")}
if any(v is not None for v in ev):
roles["event"] = cs.col("Event", ev, "categorical")
charts.append(cs.chart("timeline", "track-timeline", "When each track was seen", roles,
note=("The first 60 tracks. " if len(tracks) > 60 else "") + "Bars break where a track missed more than one frame."))
out = csml.out_dir("target/academy-parity/run-8142/track.objects/sort-with-reference/out-python")
labels_path = os.path.join(out, "labels.parquet")
pd.DataFrame({"row": np.arange(n_input, dtype=np.int64), "cluster": np.asarray([-1 if v is None else v for v in track_id], dtype=np.int64)}).to_parquet(labels_path, index=False)
summary = (f"{n_tracks} track{'s' if n_tracks != 1 else ''} from {int(di.size)} detections in {len(seq_list)} sequence{'s' if len(seq_list) != 1 else ''} "
f"({ {'sort': 'SORT', 'bytetrack': 'ByteTrack', 'deepsort': 'DeepSORT-style'}[MODE] } association); {n_assigned} detections joined a track.")
if metrics is not None:
summary += (f" Against {metrics['n_gt_tracks']} reference tracks: MOTA {f3(metrics['mota'])}, IDF1 {f3(metrics['idf1'])}, "
f"{metrics['switches']} identity switches.")
cs.publish({
"method": "track.objects",
"methodVersion": "1.1.1",
"title": "Object tracks",
"engine": cs.engine_info("pandas", "numpy"),
"n": int(len(df)),
"summary": summary,
"statistics": [{"key": "n_tracks", "label": "Tracks", "value": n_tracks}]
+ ([{"key": "mota", "label": "MOTA", "value": metrics["mota"]}, {"key": "idf1", "label": "IDF1", "value": metrics["idf1"]},
{"key": "id_switches", "label": "Identity switches", "value": metrics["switches"]}] if metrics is not None else []),
"tables": tables,
"assumptions": assumptions,
"warnings": warnings,
"notes": [f"Tracks start from detections and are confirmed after {OPTS['min_hits']} detections; a confirmed track ends after {OPTS['max_age']:g} frames without one. "
+ ("Boxes pair only within the same class. " if (LABEL and OPTS["per_class"]) else "")
+ "Constant-velocity Kalman filter per box coordinate; assignment by the Hungarian method (clean-room implementation from the published papers)."],
"charts": charts,
"artifacts": [{"key": "labels", "path": labels_path, "format": "parquet"}],
"values": values,
})
MOTAMOTA (multiple object tracking accuracy)1 − (missed boxes + false boxes + identity switches) / reference boxes; 1 is perfect and it can fall below 0. subtracts misses, false boxes and identity switches from the number of reference boxes; here it is 0.886. With 0 false boxes and 0 switches, it is all misses: MOTA counts per box, so detection errors dominate it.
IDF1IDF1 (identity F1)Share of boxes on the right identity after matching whole tracks to whole objects; F1 of identity precision and recall. matches whole tracks to whole objects and asks what share of boxes kept the right identity: 0.939. There were 20 fragmentationsIdentity switch and fragmentationA switch: an object moves onto another track. A fragmentation: a track loses its object for a while and finds it again.: tracks that lost their object and found it again.
Loosen the tracker
Explore13 tracks from 184 detections in 2 sequences (SORT association); 184 detections joined a track. Against 7 reference tracks: MOTA 0.856, IDF1 0.925, 0 identity switches.
- Tracks
- 13
- MOTA
- 0.8557
- IDF1
- 0.9247
- Identity switches
- 0
Plots
Bars break where a track missed more than one frame.
View data
| media_id | Last frame | Track | frame |
|---|---|---|---|
| cam1 | 5 | 1 · person | 0 |
| cam1 | 11 | 1 · person | 7 |
| cam1 | 15 | 1 · person | 14 |
| cam1 | 22 | 1 · person | 17 |
| cam1 | 34 | 1 · person | 24 |
| cam1 | 39 | 1 · person | 36 |
| cam1 | 3 | 2 · person | 0 |
| cam1 | 6 | 2 · person | 5 |
| cam1 | 22 | 2 · person | 8 |
| cam1 | 26 | 2 · person | 24 |
| cam1 | 36 | 2 · person | 28 |
| cam1 | 39 | 2 · person | 38 |
| cam1 | 29 | 3 · car | 5 |
| cam1 | 14 | 4 · person | 14 |
| cam1 | 21 | 5 · person | 18 |
| cam1 | 25 | 5 · person | 23 |
| cam1 | 30 | 5 · person | 27 |
| cam1 | 39 | 5 · person | 32 |
| cam1 | 23 | 6 · person | 23 |
| cam1 | 28 | 7 · person | 28 |
| cam1 | 34 | 8 · person | 34 |
| cam2 | 10 | 9 · car | 0 |
| cam2 | 13 | 9 · car | 12 |
| cam2 | 17 | 9 · car | 15 |
| cam2 | 23 | 9 · car | 20 |
| cam2 | 25 | 9 · car | 25 |
| cam2 | 29 | 9 · car | 27 |
| cam2 | 23 | 10 · person | 3 |
| cam2 | 25 | 10 · person | 25 |
| cam2 | 29 | 10 · person | 27 |
| cam2 | 25 | 11 · person | 10 |
| cam2 | 14 | 12 · person | 14 |
| cam2 | 19 | 13 · person | 19 |
Assumptions
- Frames are in order — Tracks follow the frame numbers within each sequence; a gap between frame numbers counts as that many frames of motion and age.
- Objects move smoothly — The constant-velocity motion model expects small changes from frame to frame; fast jumps between frames break tracks.
Tracks
| Track | media_id | label | First frame | Last frame | Frames spanned | Detections |
|---|---|---|---|---|---|---|
| 1 | cam1 | person | 0 | 39 | 40 | 34 |
| 2 | cam1 | person | 0 | 39 | 40 | 35 |
| 3 | cam1 | car | 5 | 29 | 25 | 25 |
| 4 | cam1 | person | 14 | 14 | 1 | 1 |
| 5 | cam1 | person | 18 | 39 | 22 | 19 |
| 6 | cam1 | person | 23 | 23 | 1 | 1 |
| 7 | cam1 | person | 28 | 28 | 1 | 1 |
| 8 | cam1 | person | 34 | 34 | 1 | 1 |
| 9 | cam2 | car | 0 | 29 | 30 | 24 |
| 10 | cam2 | person | 3 | 29 | 27 | 25 |
| 11 | cam2 | person | 10 | 25 | 16 | 16 |
| 12 | cam2 | person | 14 | 14 | 1 | 1 |
| 13 | cam2 | person | 19 | 19 | 1 | 1 |
Against the reference tracks (IoU ≥ 0.5)
| Measure | Value | Meaning |
|---|---|---|
| MOTA | 0.8557 | 1 − (misses + false positives + identity switches) / reference boxes |
| IDF1 | 0.9247 | Share of boxes on the right identity (global track matching) |
| MOTP (mean IoU) | 0.8794 | Mean overlap of the paired boxes |
| Identity switches | 0 | A reference object took a different track |
| Fragmentations | 20 | A tracked object was lost and found again |
| Misses | 23 | Reference boxes with no track |
| False positives | 6 | Tracked boxes with no reference object |
| Mostly tracked | 7 | Reference tracks paired in at least 80% of their frames |
| Mostly lost | 0 | Reference tracks paired in under 20% of their frames |
- Tracks start from detections and are confirmed after 1 detections; a confirmed track ends after 2 frames without one. Constant-velocity Kalman filter per box coordinate; assignment by the Hungarian method (clean-room implementation from the published papers).
The exact R script · R R version 4.5.1 (2025-06-13)
# Track objects across frames (SORT, ByteTrack, DeepSORT-style)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method track.objects 1.1.1 · spec df49908e74fe6de2
# Dataset: img4_tracks (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr) # cs_track_objects (tracker), cs_eval_mot (tracking metrics), cs_eval_stacked
# %% Data
SEQ <- "media_id"; FRAME <- "frame"
X0 <- "x0"; Y0 <- "y0"; X1 <- "x1"; Y1 <- "y1"
SCORE <- NULL
LABEL <- "label"
FEATURES <- c()
SOURCE <- "source"
TRUTH <- "track_id"
MODE <- "sort" # sort | bytetrack | deepsort
OPTS <- list(iou = 0.5, min_hits = as.integer(1), max_age = as.numeric(2),
min_score = 0, high = 0.6, low = 0.1,
low_iou = 0.5, max_cosine = 0.3, motion_weight = 0,
per_class = FALSE)
MOT_IOU <- 0.5
REF_LEVEL <- NULL
SOURCE_LEVELS <- c("annotation", "prediction") # stored order
# Reference tracks from a second table (option reference_table): its own column for each role, or NULL.
REF_ROLES <- NULL
FEATURES <- if (length(FEATURES)) as.character(FEATURES) else character(0)
columns <- unique(c(SEQ, FRAME, X0, Y0, X1, Y1, SCORE, LABEL, SOURCE, TRUTH, FEATURES))
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/img4_tracks.parquet", col_select = columns))
df$`__row` <- seq_len(nrow(df)) - 1L # position in the analysis input
n_input <- nrow(df)
if (MODE == "bytetrack" && is.null(SCORE)) cs_error("CS_E_INVALID_OPTION", option = "Association", allowed = "SORT or DeepSORT-style unless a confidence score column is set", value = "ByteTrack")
if (MODE == "deepsort" && !length(FEATURES)) cs_error("CS_E_INVALID_OPTION", option = "Association", allowed = "SORT or ByteTrack unless embedding columns are set", value = "DeepSORT-style")
pre_warnings <- list()
if (!is.null(REF_ROLES)) {
# The reference table's rows go above the detections under an added source column (twin: with_reference).
w <- cs_eval_with_reference(df, cs_graph_dataset_option("target/academy-parity/run-8142/track.objects/sort-any-class-short-memory/out-r", "reference_table"),
list(sequence = SEQ, frame = FRAME, x0 = X0, y0 = Y0, x1 = X1, y1 = Y1, score = SCORE, label = LABEL, truth = TRUTH),
REF_ROLES, list(label = "Class"), SOURCE, REF_LEVEL, c("sequence", "frame", "x0", "y0", "x1", "y1", if (!is.null(LABEL)) "label"))
df <- w$df
pre_warnings <- w$warnings
wc <- w$columns
SEQ <- wc$sequence; FRAME <- wc$frame; X0 <- wc$x0; Y0 <- wc$y0; X1 <- wc$x1; Y1 <- wc$y1
LABEL <- wc$label; TRUTH <- wc$truth
SOURCE <- w$source; REF_LEVEL <- w$reference; SOURCE_LEVELS <- w$levels
}
needed <- c(SEQ, FRAME, X0, Y0, X1, Y1, LABEL)
numeric_cols <- c(FRAME, X0, Y0, X1, Y1, SCORE, FEATURES)
if (!is.null(SOURCE)) {
st <- cs_eval_stacked(df, c(needed, SOURCE), numeric_cols, SOURCE, REF_LEVEL, SOURCE_LEVELS)
df <- st$df
is_ref <- st$is_ref
warnings <- c(pre_warnings, st$warnings)
} else {
if (n_input == 0L) cs_error("CS_E_NO_ROWS")
for (c in needed) if (all(is.na(df[[c]]))) cs_error("CS_E_ALL_MISSING", column = c)
keep <- rep(TRUE, n_input)
for (c in needed) keep <- keep & !is.na(df[[c]])
df <- df[keep, , drop = FALSE]
warnings <- if (nrow(df) < n_input) list(cs_warning("CS_W_ROWS_DROPPED", dropped = n_input - nrow(df), total = n_input)) else list()
if (nrow(df) == 0L) cs_error("CS_E_NO_ROWS")
for (c in numeric_cols) {
k <- sum(is.infinite(as.numeric(df[[c]])))
if (k > 0) cs_error("CS_E_NOT_FINITE", column = c, count = k)
}
is_ref <- logical(nrow(df))
}
box <- cbind(as.numeric(df[[X0]]), as.numeric(df[[Y0]]), as.numeric(df[[X1]]), as.numeric(df[[Y1]]))
bad <- (box[, 3] < box[, 1]) | (box[, 4] < box[, 2])
if (any(bad)) cs_error("CS_E_INVALID_VALUES", column = sprintf("%s and %s", X1, Y1), requirement = sprintf("at least %s and %s", X0, Y0), count = sum(bad))
det <- !is_ref
if (!is.null(SCORE)) {
no_score <- det & is.na(as.numeric(df[[SCORE]]))
if (any(no_score)) {
warnings <- c(warnings, sprintf("%d detections have no %s and were left out.", sum(no_score), SCORE))
det <- det & !no_score
}
}
if (length(FEATURES)) {
no_feat <- det & !stats::complete.cases(df[FEATURES])
if (any(no_feat)) {
warnings <- c(warnings, sprintf("%d detections miss an embedding value and were left out.", sum(no_feat)))
det <- det & !no_feat
}
}
if (sum(det) < 2L) cs_error("CS_E_TOO_FEW_ROWS", what = "Tracking", min = 2, n = sum(det))
# %% Tracks
di <- which(det)
seq_all <- as.character(df[[SEQ]])
frame_all <- as.numeric(df[[FRAME]])
lab_all <- if (!is.null(LABEL)) as.character(df[[LABEL]]) else NULL
feats <- if (length(FEATURES)) as.matrix(df[di, FEATURES, drop = FALSE]) else NULL
if (!is.null(feats)) storage.mode(feats) <- "double"
res <- cs_track_objects(seq_all[di], frame_all[di], box[di, , drop = FALSE], if (!is.null(SCORE)) as.numeric(df[[SCORE]])[di] else NULL,
if (!is.null(LABEL)) lab_all[di] else NULL, feats, MODE, OPTS)
tid_det <- res$track
track_id <- rep(NA_integer_, n_input) # per input row; rows that weren't tracked stay empty
track_id[df$`__row`[di][tid_det > 0L] + 1L] <- tid_det[tid_det > 0L]
tracks <- res$tracks
n_tracks <- length(tracks)
n_assigned <- sum(tid_det > 0L)
# %% Against the reference tracks
metrics <- NULL
switch_events <- list()
if (!is.null(SOURCE) && !is.null(TRUTH) && sum(is_ref) > 0) {
truth_ok <- is_ref & !is.na(df[[TRUTH]])
if (sum(is_ref & !truth_ok) > 0) warnings <- c(warnings, sprintf("%d reference boxes have no %s and were left out of the tracking metrics.", sum(is_ref & !truth_ok), TRUTH))
truth_all <- as.character(df[[TRUTH]])
gi <- which(truth_ok)
hi <- di[tid_det > 0L]
hyp_of <- integer(nrow(df))
hyp_of[di] <- tid_det
seqs <- list()
for (sq in sort(unique(c(seq_all[gi], seq_all[hi])), method = "radix")) {
g_s <- gi[seq_all[gi] == sq]
h_s <- hi[seq_all[hi] == sq]
frames <- list()
for (f in sort(unique(c(frame_all[g_s], frame_all[h_s])))) {
g_f <- g_s[frame_all[g_s] == f]
h_f <- h_s[frame_all[h_s] == f]
# paste() would recycle an empty id vector into one id: frames with predictions but no reference boxes get none.
gt_ids <- if (length(g_f)) paste(sq, truth_all[g_f], sep = "\u001f") else character(0)
frames[[length(frames) + 1L]] <- list(frame = f, gt_ids = gt_ids, gt_boxes = box[g_f, , drop = FALSE],
hyp_ids = as.character(hyp_of[h_f]), hyp_boxes = box[h_f, , drop = FALSE])
}
seqs[[length(seqs) + 1L]] <- frames
}
metrics <- cs_eval_mot(seqs, MOT_IOU)
switch_events <- metrics$switch_events
}
# %% Assumptions
assumptions <- list(
list(key = "frames", label = "Frames are in order", status = "info",
detail = "Tracks follow the frame numbers within each sequence; a gap between frame numbers counts as that many frames of motion and age."),
list(key = "motion", label = "Objects move smoothly", status = "info",
detail = "The constant-velocity motion model expects small changes from frame to frame; fast jumps between frames break tracks.")
)
if (length(FEATURES)) assumptions[[3]] <- list(key = "appearance", label = "Embeddings describe appearance", status = "info",
detail = "DeepSORT-style matching trusts the embedding columns to tell objects apart; embeddings of the same object should be close.")
# %% Result
f3 <- function(v) if (is.null(v) || is.na(v)) "—" else sprintf("%.3f", v)
tl <- vapply(tracks, function(t) if (is.na(t$label)) NA_character_ else t$label, character(1))
labels_seen <- sort(unique(tl[!is.na(tl)]), method = "radix")
seq_list <- sort(unique(seq_all[di]), method = "radix")
n_frames <- sum(!duplicated(paste(seq_all[di], sprintf("%.17g", frame_all[di]), sep = "\u001f")))
nz <- function(v) if (is.null(v)) NA_real_ else v
values <- list(association = MODE, n_sequences = length(seq_list), n_frames = n_frames, n_detections = length(di), n_tracks = n_tracks,
n_assigned = n_assigned, n_unassigned = length(di) - n_assigned,
mean_track_length = if (n_tracks) mean(vapply(tracks, function(t) t$n_detections, numeric(1))) else NA_real_,
mota = NA_real_, motp = NA_real_, idf1 = NA_real_, idp = NA_real_, idr = NA_real_, id_switches = NA_real_, fragmentations = NA_real_,
false_positives = NA_real_, misses = NA_real_, mostly_tracked = NA_real_, partially_tracked = NA_real_, mostly_lost = NA_real_,
precision = NA_real_, recall = NA_real_, n_gt_tracks = NA_real_, n_gt_boxes = NA_real_, track_id = I(track_id))
for (lab in labels_seen) values[[sprintf("tracks[%s]", lab)]] <- sum(tl == lab, na.rm = TRUE)
if (!is.null(metrics)) {
values$mota <- metrics$mota; values$motp <- metrics$motp; values$idf1 <- metrics$idf1; values$idp <- metrics$idp; values$idr <- metrics$idr
values$id_switches <- metrics$switches; values$fragmentations <- metrics$fragmentations; values$false_positives <- metrics$false_positives
values$misses <- metrics$misses; values$mostly_tracked <- metrics$mostly_tracked; values$partially_tracked <- metrics$partially_tracked
values$mostly_lost <- metrics$mostly_lost; values$precision <- metrics$precision; values$recall <- metrics$recall
values$n_gt_tracks <- metrics$n_gt_tracks; values$n_gt_boxes <- metrics$objects
}
trk_rows <- lapply(tracks, function(t) list(track_id = t$track_id, sequence = t$sequence, label = t$label, first_frame = t$first_frame,
last_frame = t$last_frame, span = t$last_frame - t$first_frame + 1, n_detections = t$n_detections,
mean_score = t$mean_score))
tcols <- c(list(list(key = "track_id", label = "Track", type = "integer"), list(key = "sequence", label = SEQ, type = "string")),
if (!is.null(LABEL)) list(list(key = "label", label = LABEL, type = "string")),
list(list(key = "first_frame", label = "First frame", type = "number"), list(key = "last_frame", label = "Last frame", type = "number"),
list(key = "span", label = "Frames spanned", type = "number"), list(key = "n_detections", label = "Detections", type = "integer")),
if (!is.null(SCORE)) list(list(key = "mean_score", label = "Mean score", type = "number")))
tables <- list(list(key = "tracks", title = "Tracks", columns = tcols, rows = utils::head(trk_rows, 500),
note = if (length(trk_rows) > 500) "First 500 tracks." else NULL))
if (!is.null(metrics)) {
mrows <- list(list("MOTA", metrics$mota, "1 − (misses + false positives + identity switches) / reference boxes"),
list("IDF1", metrics$idf1, "Share of boxes on the right identity (global track matching)"),
list("MOTP (mean IoU)", metrics$motp, "Mean overlap of the paired boxes"),
list("Identity switches", metrics$switches, "A reference object took a different track"),
list("Fragmentations", metrics$fragmentations, "A tracked object was lost and found again"),
list("Misses", metrics$misses, "Reference boxes with no track"), list("False positives", metrics$false_positives, "Tracked boxes with no reference object"),
list("Mostly tracked", metrics$mostly_tracked, "Reference tracks paired in at least 80% of their frames"),
list("Mostly lost", metrics$mostly_lost, "Reference tracks paired in under 20% of their frames"))
tables[[length(tables) + 1L]] <- list(key = "mot", title = sprintf("Against the reference tracks (IoU ≥ %g)", MOT_IOU),
columns = list(list(key = "metric", label = "Measure", type = "string"), list(key = "value", label = "Value", type = "number"),
list(key = "meaning", label = "Meaning", type = "string")),
rows = lapply(mrows, function(r) list(metric = r[[1]], value = r[[2]], meaning = r[[3]])))
if (length(switch_events)) {
tables[[length(tables) + 1L]] <- list(key = "switches", title = "Identity switches",
columns = list(list(key = "sequence", label = SEQ, type = "string"), list(key = "frame", label = "Frame", type = "number"),
list(key = "object", label = "Reference object", type = "string"), list(key = "from", label = "From track", type = "string"),
list(key = "to", label = "To track", type = "string")),
rows = lapply(utils::head(switch_events, 200), function(e) { p <- strsplit(e$object, "\u001f", fixed = TRUE)[[1]]
list(sequence = p[1], frame = e$frame, object = p[2], from = e$from, to = e$to) }),
note = if (length(switch_events) > 200) "First 200 switches." else NULL)
}
}
charts <- list()
if (n_tracks) {
lane_of <- function(t) paste0(t$track_id, if (!is.na(t$label)) paste0(" · ", t$label) else "")
shown <- utils::head(tracks, 60)
color_of <- function(t) if (length(seq_list) > 1L) t$sequence else if (!is.na(t$label)) t$label else t$sequence
ln <- character(0); s0 <- numeric(0); s1 <- numeric(0); col <- character(0); ev <- character(0)
fr_det <- frame_all[di]
for (t in shown) {
fr <- sort(fr_det[tid_det == t$track_id])
brk <- which(diff(fr) > 1)
starts <- c(fr[1], fr[brk + 1L])
ends <- c(fr[brk], fr[length(fr)])
ln <- c(ln, rep(lane_of(t), length(starts))); s0 <- c(s0, starts); s1 <- c(s1, ends)
col <- c(col, rep(color_of(t), length(starts))); ev <- c(ev, rep(NA_character_, length(starts)))
}
shown_ids <- vapply(shown, function(t) t$track_id, numeric(1))
for (e in switch_events) {
to <- as.integer(e$to)
if (to %in% shown_ids) {
t <- shown[[which(shown_ids == to)[1]]]
ln <- c(ln, lane_of(t)); s0 <- c(s0, e$frame); s1 <- c(s1, e$frame); col <- c(col, color_of(t)); ev <- c(ev, "Identity switch")
}
}
roles <- list(lane = cs_col("Track", ln, "categorical", levels = vapply(shown, lane_of, character(1))),
start = cs_col(FRAME, s0, "numeric"), end = cs_col("Last frame", s1, "numeric"),
color = cs_col(if (length(seq_list) > 1L) SEQ else if (!is.null(LABEL)) LABEL else SEQ, col, "categorical"))
if (any(!is.na(ev))) roles$event <- cs_col("Event", ev, "categorical")
charts[[1]] <- cs_chart("timeline", "track-timeline", "When each track was seen", roles,
note = paste0(if (n_tracks > 60) "The first 60 tracks. " else "", "Bars break where a track missed more than one frame."))
}
out <- cs_ml_out_dir("target/academy-parity/run-8142/track.objects/sort-any-class-short-memory/out-r")
labels_path <- file.path(out, "labels.parquet")
nanoparquet::write_parquet(data.frame(row = as.numeric(seq_len(n_input) - 1L), cluster = as.numeric(ifelse(is.na(track_id), -1L, track_id))), labels_path)
names_mode <- c(sort = "SORT", bytetrack = "ByteTrack", deepsort = "DeepSORT-style")
summary <- sprintf("%d track%s from %d detections in %d sequence%s (%s association); %d detections joined a track.", n_tracks, if (n_tracks != 1) "s" else "",
length(di), length(seq_list), if (length(seq_list) != 1) "s" else "", names_mode[[MODE]], n_assigned)
if (!is.null(metrics)) summary <- paste0(summary, sprintf(" Against %d reference tracks: MOTA %s, IDF1 %s, %d identity switches.", as.integer(metrics$n_gt_tracks),
f3(metrics$mota), f3(metrics$idf1), as.integer(metrics$switches)))
cs_publish(list(
method = "track.objects",
methodVersion = "1.1.1",
title = "Object tracks",
engine = cs_engine_info("nanoparquet"),
n = nrow(df),
summary = summary,
statistics = c(list(list(key = "n_tracks", label = "Tracks", value = n_tracks)),
if (!is.null(metrics)) list(list(key = "mota", label = "MOTA", value = metrics$mota), list(key = "idf1", label = "IDF1", value = metrics$idf1),
list(key = "id_switches", label = "Identity switches", value = metrics$switches))),
tables = tables,
assumptions = assumptions,
warnings = warnings,
notes = list(paste0(sprintf("Tracks start from detections and are confirmed after %d detections; a confirmed track ends after %g frames without one. ", OPTS$min_hits, OPTS$max_age),
if (!is.null(LABEL) && OPTS$per_class) "Boxes pair only within the same class. " else "",
"Constant-velocity Kalman filter per box coordinate; assignment by the Hungarian method (clean-room implementation from the published papers).")),
charts = charts,
artifacts = list(list(key = "labels", path = labels_path, format = "parquet")),
values = values
))
13 tracks from 184 detections in 2 sequences (SORT association); 184 detections joined a track. Against 7 reference tracks: MOTA 0.856, IDF1 0.925, 0 identity switches.
- Tracks
- 13
- MOTA
- 0.8557
- IDF1
- 0.9247
- Identity switches
- 0
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Frames are in order — Tracks follow the frame numbers within each sequence; a gap between frame numbers counts as that many frames of motion and age.
- Objects move smoothly — The constant-velocity motion model expects small changes from frame to frame; fast jumps between frames break tracks.
Tracks
| Track | media_id | label | First frame | Last frame | Frames spanned | Detections |
|---|---|---|---|---|---|---|
| 1 | cam1 | person | 0 | 39 | 40 | 34 |
| 2 | cam1 | person | 0 | 39 | 40 | 35 |
| 3 | cam1 | car | 5 | 29 | 25 | 25 |
| 4 | cam1 | person | 14 | 14 | 1 | 1 |
| 5 | cam1 | person | 18 | 39 | 22 | 19 |
| 6 | cam1 | person | 23 | 23 | 1 | 1 |
| 7 | cam1 | person | 28 | 28 | 1 | 1 |
| 8 | cam1 | person | 34 | 34 | 1 | 1 |
| 9 | cam2 | car | 0 | 29 | 30 | 24 |
| 10 | cam2 | person | 3 | 29 | 27 | 25 |
| 11 | cam2 | person | 10 | 25 | 16 | 16 |
| 12 | cam2 | person | 14 | 14 | 1 | 1 |
| 13 | cam2 | person | 19 | 19 | 1 | 1 |
Against the reference tracks (IoU ≥ 0.5)
| Measure | Value | Meaning |
|---|---|---|
| MOTA | 0.8557 | 1 − (misses + false positives + identity switches) / reference boxes |
| IDF1 | 0.9247 | Share of boxes on the right identity (global track matching) |
| MOTP (mean IoU) | 0.8794 | Mean overlap of the paired boxes |
| Identity switches | 0 | A reference object took a different track |
| Fragmentations | 20 | A tracked object was lost and found again |
| Misses | 23 | Reference boxes with no track |
| False positives | 6 | Tracked boxes with no reference object |
| Mostly tracked | 7 | Reference tracks paired in at least 80% of their frames |
| Mostly lost | 0 | Reference tracks paired in under 20% of their frames |
- Tracks start from detections and are confirmed after 1 detections; a confirmed track ends after 2 frames without one. Constant-velocity Kalman filter per box coordinate; assignment by the Hungarian method (clean-room implementation from the published papers).
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Track objects across frames (SORT, ByteTrack, DeepSORT-style)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method track.objects 1.1.1 · spec df49908e74fe6de2
# Dataset: img4_tracks (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import os
import numpy as np
import pandas as pd
import codesplash as cs
from codesplash.evaluate import mot # twin: codesplashr cs_eval_mot
from codesplash.evaluate.stacked import stacked # twin: cs_eval_stacked
from codesplash import ml as csml
from codesplash.track import objects as tr # twin: codesplashr cs_track_objects
# %% Data
SEQ, FRAME = "media_id", "frame"
X0, Y0, X1, Y1 = "x0", "y0", "x1", "y1"
SCORE = None
LABEL = "label"
FEATURES = []
SOURCE = "source"
TRUTH = "track_id"
MODE = "sort" # sort | bytetrack | deepsort
OPTS = {"iou": 0.5, "min_hits": int(1), "max_age": float(2),
"min_score": 0, "high": 0.6, "low": 0.1,
"low_iou": 0.5, "max_cosine": 0.3, "motion_weight": 0,
"per_class": False}
MOT_IOU = 0.5
REF_LEVEL = None
SOURCE_LEVELS = ["annotation", "prediction"] # stored order
# Reference tracks from a second table (option reference_table): its own column for each role, or None.
REF_ROLES = None
columns = list(dict.fromkeys(c for c in [SEQ, FRAME, X0, Y0, X1, Y1, SCORE, LABEL, SOURCE, TRUTH] + FEATURES if c))
df = pd.read_parquet("tests/parity/fixtures/img4_tracks.parquet", columns=columns)
df["__row"] = np.arange(len(df)) # position in the analysis input
n_input = len(df)
if MODE == "bytetrack" and not SCORE:
cs.cs_error("CS_E_INVALID_OPTION", option="Association", allowed="SORT or DeepSORT-style unless a confidence score column is set", value="ByteTrack")
if MODE == "deepsort" and not FEATURES:
cs.cs_error("CS_E_INVALID_OPTION", option="Association", allowed="SORT or ByteTrack unless embedding columns are set", value="DeepSORT-style")
pre_warnings = []
if REF_ROLES is not None:
# The reference table's rows go above the detections under an added source column (twin: cs_eval_with_reference).
from codesplash.graph import dataset_option # the table the host wrote for the option
from codesplash.evaluate.stacked import with_reference
w = with_reference(df, dataset_option("target/academy-parity/run-8142/track.objects/sort-any-class-short-memory/out-python", "reference_table"),
{"sequence": SEQ, "frame": FRAME, "x0": X0, "y0": Y0, "x1": X1, "y1": Y1, "score": SCORE, "label": LABEL, "truth": TRUTH},
REF_ROLES, {"label": "Class"}, SOURCE, REF_LEVEL, ["sequence", "frame", "x0", "y0", "x1", "y1"] + (["label"] if LABEL else []))
df, pre_warnings, wc = w["df"], w["warnings"], w["columns"]
SEQ, FRAME, X0, Y0, X1, Y1 = wc["sequence"], wc["frame"], wc["x0"], wc["y0"], wc["x1"], wc["y1"]
LABEL, TRUTH = wc["label"], wc["truth"]
SOURCE, REF_LEVEL, SOURCE_LEVELS = w["source"], w["reference"], w["levels"]
needed = [SEQ, FRAME, X0, Y0, X1, Y1] + ([LABEL] if LABEL else [])
numeric = [c for c in [FRAME, X0, Y0, X1, Y1, SCORE] if c] + FEATURES
if SOURCE:
st = stacked(df, needed + [SOURCE], numeric, SOURCE, REF_LEVEL, SOURCE_LEVELS)
df, is_ref, warnings = st["df"], st["is_ref"], pre_warnings + st["warnings"]
else:
if n_input == 0:
cs.cs_error("CS_E_NO_ROWS")
for c in needed:
if df[c].isna().all():
cs.cs_error("CS_E_ALL_MISSING", column=c)
keep = np.ones(n_input, dtype=bool)
for c in needed:
keep &= df[c].notna().to_numpy()
df = df.loc[keep].reset_index(drop=True)
warnings = [cs.cs_warning("CS_W_ROWS_DROPPED", dropped=int(n_input - len(df)), total=n_input)] if len(df) < n_input else []
if len(df) == 0:
cs.cs_error("CS_E_NO_ROWS")
for c in numeric:
k = int(np.isinf(df[c].to_numpy(dtype=float, na_value=np.nan)).sum())
if k:
cs.cs_error("CS_E_NOT_FINITE", column=c, count=k)
is_ref = np.zeros(len(df), dtype=bool)
box = df[[X0, Y0, X1, Y1]].to_numpy(dtype=float)
bad = (box[:, 2] < box[:, 0]) | (box[:, 3] < box[:, 1])
if bad.any():
cs.cs_error("CS_E_INVALID_VALUES", column=f"{X1} and {Y1}", requirement=f"at least {X0} and {Y0}", count=int(bad.sum()))
det = ~is_ref
if SCORE:
no_score = det & np.isnan(df[SCORE].to_numpy(dtype=float, na_value=np.nan))
if no_score.any():
warnings.append(f"{int(no_score.sum())} detections have no {SCORE} and were left out.")
det &= ~no_score
if FEATURES:
no_feat = det & df[FEATURES].isna().any(axis=1).to_numpy()
if no_feat.any():
warnings.append(f"{int(no_feat.sum())} detections miss an embedding value and were left out.")
det &= ~no_feat
if int(det.sum()) < 2:
cs.cs_error("CS_E_TOO_FEW_ROWS", what="Tracking", min=2, n=int(det.sum()))
# %% Tracks
di = np.flatnonzero(det)
seq_all = np.asarray([str(x) for x in df[SEQ].tolist()], dtype=object)
frame_all = df[FRAME].to_numpy(dtype=float)
lab_all = np.asarray([str(x) for x in df[LABEL].tolist()], dtype=object) if LABEL else None
res = tr.track(seq_all[di], frame_all[di], box[di], df[SCORE].to_numpy(dtype=float)[di] if SCORE else None,
lab_all[di] if LABEL else None, df[FEATURES].to_numpy(dtype=float)[di] if FEATURES else None, MODE, **OPTS)
tid_det = res["track"]
track_id = [None] * n_input # per input row; rows that weren't tracked stay empty
for k, i in enumerate(di):
if tid_det[k] > 0:
track_id[int(df["__row"].iloc[i])] = int(tid_det[k])
tracks = res["tracks"]
n_tracks = len(tracks)
n_assigned = int(np.sum(tid_det > 0))
# %% Against the reference tracks
metrics = None
switch_events = []
if SOURCE and TRUTH and int(is_ref.sum()):
truth_ok = is_ref & df[TRUTH].notna().to_numpy()
if int((is_ref & ~truth_ok).sum()):
warnings.append(f"{int((is_ref & ~truth_ok).sum())} reference boxes have no {TRUTH} and were left out of the tracking metrics.")
truth_all = np.asarray([str(x) for x in df[TRUTH].tolist()], dtype=object)
gi = np.flatnonzero(truth_ok)
hi = di[tid_det > 0]
hyp_id = {int(i): str(int(t)) for i, t in zip(di, tid_det) if t > 0}
seqs = []
for sq in sorted(set(seq_all[gi].tolist()) | set(seq_all[hi].tolist())):
g_s = gi[seq_all[gi] == sq]
h_s = hi[seq_all[hi] == sq]
frames = []
for f in sorted(set(frame_all[g_s].tolist()) | set(frame_all[h_s].tolist())):
g_f = g_s[frame_all[g_s] == f]
h_f = h_s[frame_all[h_s] == f]
frames.append({"frame": f, "gt_ids": [f"{sq}\x1f{truth_all[i]}" for i in g_f], "gt_boxes": box[g_f],
"hyp_ids": [hyp_id[int(i)] for i in h_f], "hyp_boxes": box[h_f]})
seqs.append(frames)
metrics = mot.clear_mot(seqs, MOT_IOU)
switch_events = metrics["switch_events"]
# %% Assumptions
assumptions = [
{"key": "frames", "label": "Frames are in order", "status": "info",
"detail": "Tracks follow the frame numbers within each sequence; a gap between frame numbers counts as that many frames of motion and age."},
{"key": "motion", "label": "Objects move smoothly", "status": "info",
"detail": "The constant-velocity motion model expects small changes from frame to frame; fast jumps between frames break tracks."},
]
if FEATURES:
assumptions.append({"key": "appearance", "label": "Embeddings describe appearance", "status": "info",
"detail": "DeepSORT-style matching trusts the embedding columns to tell objects apart; embeddings of the same object should be close."})
# %% Result
f3 = lambda v: "—" if v is None else f"{v:.3f}"
labels_seen = sorted(set(t["label"] for t in tracks if t["label"] is not None))
seq_list = sorted(set(seq_all[di].tolist()))
n_frames = len(set(zip(seq_all[di].tolist(), frame_all[di].tolist())))
values = {"association": MODE, "n_sequences": len(seq_list), "n_frames": n_frames, "n_detections": int(di.size), "n_tracks": n_tracks,
"n_assigned": n_assigned, "n_unassigned": int(di.size - n_assigned),
"mean_track_length": float(np.mean([t["n_detections"] for t in tracks])) if tracks else None,
"mota": None, "motp": None, "idf1": None, "idp": None, "idr": None, "id_switches": None, "fragmentations": None,
"false_positives": None, "misses": None, "mostly_tracked": None, "partially_tracked": None, "mostly_lost": None,
"precision": None, "recall": None, "n_gt_tracks": None, "n_gt_boxes": None, "track_id": track_id}
for lab in labels_seen:
values[f"tracks[{lab}]"] = sum(1 for t in tracks if t["label"] == lab)
if metrics is not None:
values.update({"mota": metrics["mota"], "motp": metrics["motp"], "idf1": metrics["idf1"], "idp": metrics["idp"], "idr": metrics["idr"],
"id_switches": metrics["switches"], "fragmentations": metrics["fragmentations"], "false_positives": metrics["false_positives"],
"misses": metrics["misses"], "mostly_tracked": metrics["mostly_tracked"], "partially_tracked": metrics["partially_tracked"],
"mostly_lost": metrics["mostly_lost"], "precision": metrics["precision"], "recall": metrics["recall"],
"n_gt_tracks": metrics["n_gt_tracks"], "n_gt_boxes": metrics["objects"]})
trk_rows = [{"track_id": t["track_id"], "sequence": t["sequence"], "label": t["label"], "first_frame": t["first_frame"], "last_frame": t["last_frame"],
"span": t["last_frame"] - t["first_frame"] + 1.0, "n_detections": t["n_detections"], "mean_score": t["mean_score"]} for t in tracks]
tables = [{"key": "tracks", "title": "Tracks",
"columns": [{"key": "track_id", "label": "Track", "type": "integer"}, {"key": "sequence", "label": SEQ, "type": "string"}]
+ ([{"key": "label", "label": LABEL, "type": "string"}] if LABEL else [])
+ [{"key": "first_frame", "label": "First frame", "type": "number"}, {"key": "last_frame", "label": "Last frame", "type": "number"},
{"key": "span", "label": "Frames spanned", "type": "number"}, {"key": "n_detections", "label": "Detections", "type": "integer"}]
+ ([{"key": "mean_score", "label": "Mean score", "type": "number"}] if SCORE else []),
"rows": trk_rows[:500], "note": "First 500 tracks." if len(trk_rows) > 500 else None}]
if metrics is not None:
mrows = [("MOTA", metrics["mota"], "1 − (misses + false positives + identity switches) / reference boxes"),
("IDF1", metrics["idf1"], "Share of boxes on the right identity (global track matching)"),
("MOTP (mean IoU)", metrics["motp"], "Mean overlap of the paired boxes"),
("Identity switches", metrics["switches"], "A reference object took a different track"),
("Fragmentations", metrics["fragmentations"], "A tracked object was lost and found again"),
("Misses", metrics["misses"], "Reference boxes with no track"), ("False positives", metrics["false_positives"], "Tracked boxes with no reference object"),
("Mostly tracked", metrics["mostly_tracked"], "Reference tracks paired in at least 80% of their frames"),
("Mostly lost", metrics["mostly_lost"], "Reference tracks paired in under 20% of their frames")]
tables.append({"key": "mot", "title": f"Against the reference tracks (IoU ≥ {MOT_IOU:g})",
"columns": [{"key": "metric", "label": "Measure", "type": "string"}, {"key": "value", "label": "Value", "type": "number"},
{"key": "meaning", "label": "Meaning", "type": "string"}],
"rows": [{"metric": a, "value": b, "meaning": c} for a, b, c in mrows]})
if switch_events:
tables.append({"key": "switches", "title": "Identity switches",
"columns": [{"key": "sequence", "label": SEQ, "type": "string"}, {"key": "frame", "label": "Frame", "type": "number"},
{"key": "object", "label": "Reference object", "type": "string"}, {"key": "from", "label": "From track", "type": "string"},
{"key": "to", "label": "To track", "type": "string"}],
"rows": [{"sequence": e["object"].split("\x1f")[0], "frame": e["frame"], "object": e["object"].split("\x1f")[1],
"from": e["from"], "to": e["to"]} for e in switch_events[:200]],
"note": "First 200 switches." if len(switch_events) > 200 else None})
charts = []
if tracks:
lane_of = {t["track_id"]: f"{t['track_id']}" + (f" · {t['label']}" if t["label"] is not None else "") for t in tracks}
shown = tracks[:60]
ln, s0, s1, col, ev = [], [], [], [], []
for t in shown:
fr = np.sort(frame_all[di][tid_det == t["track_id"]])
brk = np.flatnonzero(np.diff(fr) > 1.0)
starts = np.concatenate([[fr[0]], fr[brk + 1]])
ends = np.concatenate([fr[brk], [fr[-1]]])
for a, b in zip(starts, ends):
ln.append(lane_of[t["track_id"]])
s0.append(float(a))
s1.append(float(b))
col.append(t["sequence"] if len(seq_list) > 1 else (t["label"] if t["label"] is not None else t["sequence"]))
ev.append(None)
shown_ids = {t["track_id"] for t in shown}
for e in switch_events:
if int(e["to"]) in shown_ids:
t = next(x for x in shown if x["track_id"] == int(e["to"]))
ln.append(lane_of[t["track_id"]])
s0.append(float(e["frame"]))
s1.append(float(e["frame"]))
col.append(t["sequence"] if len(seq_list) > 1 else (t["label"] if t["label"] is not None else t["sequence"]))
ev.append("Identity switch")
roles = {"lane": cs.col("Track", ln, "categorical", levels=[lane_of[t["track_id"]] for t in shown]),
"start": cs.col(FRAME, s0, "numeric"), "end": cs.col("Last frame", s1, "numeric"),
"color": cs.col(SEQ if len(seq_list) > 1 else (LABEL or SEQ), col, "categorical")}
if any(v is not None for v in ev):
roles["event"] = cs.col("Event", ev, "categorical")
charts.append(cs.chart("timeline", "track-timeline", "When each track was seen", roles,
note=("The first 60 tracks. " if len(tracks) > 60 else "") + "Bars break where a track missed more than one frame."))
out = csml.out_dir("target/academy-parity/run-8142/track.objects/sort-any-class-short-memory/out-python")
labels_path = os.path.join(out, "labels.parquet")
pd.DataFrame({"row": np.arange(n_input, dtype=np.int64), "cluster": np.asarray([-1 if v is None else v for v in track_id], dtype=np.int64)}).to_parquet(labels_path, index=False)
summary = (f"{n_tracks} track{'s' if n_tracks != 1 else ''} from {int(di.size)} detections in {len(seq_list)} sequence{'s' if len(seq_list) != 1 else ''} "
f"({ {'sort': 'SORT', 'bytetrack': 'ByteTrack', 'deepsort': 'DeepSORT-style'}[MODE] } association); {n_assigned} detections joined a track.")
if metrics is not None:
summary += (f" Against {metrics['n_gt_tracks']} reference tracks: MOTA {f3(metrics['mota'])}, IDF1 {f3(metrics['idf1'])}, "
f"{metrics['switches']} identity switches.")
cs.publish({
"method": "track.objects",
"methodVersion": "1.1.1",
"title": "Object tracks",
"engine": cs.engine_info("pandas", "numpy"),
"n": int(len(df)),
"summary": summary,
"statistics": [{"key": "n_tracks", "label": "Tracks", "value": n_tracks}]
+ ([{"key": "mota", "label": "MOTA", "value": metrics["mota"]}, {"key": "idf1", "label": "IDF1", "value": metrics["idf1"]},
{"key": "id_switches", "label": "Identity switches", "value": metrics["switches"]}] if metrics is not None else []),
"tables": tables,
"assumptions": assumptions,
"warnings": warnings,
"notes": [f"Tracks start from detections and are confirmed after {OPTS['min_hits']} detections; a confirmed track ends after {OPTS['max_age']:g} frames without one. "
+ ("Boxes pair only within the same class. " if (LABEL and OPTS["per_class"]) else "")
+ "Constant-velocity Kalman filter per box coordinate; assignment by the Hungarian method (clean-room implementation from the published papers)."],
"charts": charts,
"artifacts": [{"key": "labels", "path": labels_path, "format": "parquet"}],
"values": values,
})
Now classes may mix, one detection confirms a track and a lost track ends after two frames. The tracker formed 13 tracks for 7 reference objects, with 6 false boxes. MOTA fell to 0.856 and IDF1 to 0.925.
How many people walked past?
PredictPredict first
A shop counts visitors as the number of track ids its tracker produced in a day. Compared with the true number of visitors, what will that count usually be?
Reveal
Too high: there are fewer objects than track ids. Every time a person is hidden longer than the tracker keeps lost tracks, or two people cross and a track restarts, a new id appears. In the run above, ids outnumber objects. Check identity switches and fragmentations before counting ids.
HOTA: balance finding and following
ReadHOTAHOTAA tracking score that balances finding objects (DetA) and keeping their identities (AssA), averaged over overlap thresholds. scores detection and association separately and combines them with a geometric mean, at each overlap threshold , then averages over thresholds:
AssA averages, over matched boxes, how much each predicted track and its object's true track overlap in time. In the reference's toy, detection accuracy 0.8 and association accuracy 0.6 give 0.693. A geometric mean punishes imbalance: a tracker can't buy a high HOTA with detection alone.
The protocol is part of the score
ReadA HOTA, MOTA or IDF1 number means something only with its protocol:
- the matching rule and overlap threshold (MOT benchmarks use IoU 0.5 for MOTA and IDF1);
- which regions and classes are ignored;
- for HOTA, the threshold grid; the geometric mean alone isn't the whole algorithm;
- the implementation: use one reference implementation for every tracker you compare.
Sequences, not frames, are the unit for resampling. Report DetA and AssA, or MOTA and IDF1, beside any single total, and audit long occlusions by eye.
DExplorable · Boxes, IoU, non-maximum suppression and average precision
How does a detector turn a cloud of overlapping guesses into one box per object, and how is it scored?
After NMS at this threshold, will every object still have at least one box?
Scene
Three well-separated objects, two people standing close together plus one more, or four small objects.
A box is dropped when it overlaps a higher-scoring kept box by more than this IoU.
Candidates scoring below this are dropped before NMS.
IoU to count a hit
A kept box counts as a true positive when it overlaps an unmatched object by at least this much.
How far the detector's guesses wander from each true box, as a share of its size.
Numbers on the kept boxes are their scores. AP averages the best precision reachable at 101 recall levels, so a false positive ranked above a hit costs more than one ranked last.
Commit your prediction above to see the result
Make your prediction to see the result.
What runs here
Read| Entry | In CodeSplash |
|---|---|
| EVA050 · HOTA multi-object tracking evaluation | Runs as a notebook (the reference program); Track objects reports MOTA and IDF1, not HOTA |
| VID034 · Simple Online and Realtime Tracking | Runs in CodeSplash on tables (Experimental): Track objects, SORT |
| VID036 · ByteTrack | Runs in CodeSplash on tables (Experimental): Track objects, ByteTrack option |
Check: scoring trackers
CheckpointCheck yourself
How does HOTA combine detection and association at one overlap threshold?
Show the answer
Answer: b
A geometric mean, then averaged over thresholds. A weak side drags the total down more than an average would.
Check yourself
Tracker A has excellent detection and poor association; tracker B is good at both. Why does HOTA tend to favor B?
Show the answer
Answer: a
With a product inside the square root, a low AssA can't be offset by a high DetA.
Check yourself
Two papers report HOTA for their trackers using different implementations and ignore rules. Can you rank the trackers by those numbers?
Show the answer
Answer: b
Use one conforming implementation, such as TrackEval, for every tracker, and report DetA and AssA.
Check yourself
You want an interval for a tracker's HOTA on a benchmark. What should you resample?
Show the answer
Answer: c
Frames within a sequence are strongly dependent. Sequences are the natural unit.
Check yourself
A tracker's MOTA improves after switching to a better detector, while its IDF1 stays flat. What most likely changed?
Show the answer
Answer: a
MOTA counts per-box errors and is dominated by misses and false boxes. IDF1 tracks identities.
Check yourself
Run ByteTrack on the same table (example track.objects/bytetrack-with-reference). What MOTA does it reach? Give three decimals.
Show the answer
Answer: 0.81592039800995
On these detections ByteTrack's thresholds leave more boxes unmatched than SORT's settings did, so its MOTA is lower. Neither number says which tracker is better on your data; hold the detections fixed and look at IDF1 too.
Check yourself
A tracker produced almost twice as many track ids as there are reference objects. Which errors explain the extra ids?
Show the answer
Answer: b
Lost tracks that restart get new ids; ids count track segments, not objects.
Recap
Recap- Tracking has three parts: detection, association and localization.
- MOTA is dominated by detection errors; IDF1 by identity keeping.
- HOTA is the geometric mean of DetA and AssA, averaged over thresholds; report the parts and the protocol.
- Track ids overstate object counts; check switches and fragmentations first.
Concepts in this lesson