Skip to content

Labeling time: action segmentation and localization

Label every frame (MS-TCN) or find each action's start and end in a long video (ActionFormer), then score segments, not only frames: temporal IoU, segment F1, edit score and average precision.

Advanced ~15 min11 steps

What runs in CodeSplash

You will be able to

  • Tell classification, frame-wise segmentation and interval localization apart as targets
  • Explain MS-TCN's refinement stages and its truncated smoothing loss
  • Decode an ActionFormer prediction into an interval and compute its temporal IoU
  • Read frame accuracy, segment F1 at several thresholds, edit score and temporal average precision together

Read first

01

Three different targets

Read

"Recognize actions in video" hides three tasks with different outputs and scores:

TaskOutputTypical score
Classificationone label per trimmed clipaccuracy
Action segmentationTemporal action segmentationGive every frame of a video an action label, so the video becomes a sequence of labeled segments.a label for every frameframe accuracy, edit score, segment F1
Action localizationTemporal action localizationFind each action in a long video as a class plus a start and an end time, possibly overlapping others.intervals with a class and a confidence, in a long untrimmed videoaverage precision at temporal IoU thresholds

A number from one row says little about another.

02

MS-TCN: label, then refine

Read
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.

MS-TCN labels every frame with stacks of dilated temporal convolutionsTemporal convolutional networkA network of stacked causal convolutions whose dilations double each block, so it sees far into the past without recurrence., then passes those probabilities through further stages that refine them. Its loss adds a truncated smoothing term to frame-wise cross-entropy:

L=LCE+λ∑t,cmin⁡((log⁡pt,c−log⁡pt−1,c)2, τ2).L = L_{\text{CE}} + \lambda \sum_{t,c} \min\big((\log p_{t,c} - \log p_{t-1,c})^2,\ \tau^2\big).

The smoothing fights over-segmentation, the flicker of short spurious fragments; the cap τ\tau keeps real boundaries from being smoothed away. In the reference's toy, the penalty for three frames is 0.138.

03

Dilations reach far back

Explore
Temporal convolutional network forecast (TCN)Recorded · Python and R agreeRecorded 2026-11-25 · 28 values compared
R

TCN on seasonal changes: 6-step forecasts of passengers (monthly data, 144 observations). Backtest MAE 10.6 over 1 origin.

MAE
10.589
RMSE
13.338
MAPE
0.0224

Plots

Forecast of passengersWhere is the series heading, and how uncertain is the forecast?
View data
hi_80hi_95kindlo_80lo_95monthpassengers
——actual——−662,688,000,000112
——actual——−660,009,600,000118
——actual——−657,590,400,000132
——actual——−654,912,000,000129
——actual——−652,320,000,000121
——actual——−649,641,600,000135
——actual——−647,049,600,000148
——actual——−644,371,200,000148
——actual——−641,692,800,000136
——actual——−639,100,800,000119
——actual——−636,422,400,000104
——actual——−633,830,400,000118
——actual——−631,152,000,000115
——actual——−628,473,600,000126
——actual——−626,054,400,000141
——actual——−623,376,000,000135
——actual——−620,784,000,000125
——actual——−618,105,600,000149
——actual——−615,513,600,000170
——actual——−612,835,200,000170
——actual——−610,156,800,000158
——actual——−607,564,800,000133
——actual——−604,886,400,000114
——actual——−602,294,400,000140
——actual——−599,616,000,000145
——actual——−596,937,600,000150
——actual——−594,518,400,000178
——actual——−591,840,000,000163
——actual——−589,248,000,000172
——actual——−586,569,600,000178
——actual——−583,977,600,000199
——actual——−581,299,200,000199
——actual——−578,620,800,000184
——actual——−576,028,800,000162
——actual——−573,350,400,000146
——actual——−570,758,400,000166
——actual——−568,080,000,000171
——actual——−565,401,600,000180
——actual——−562,896,000,000193
——actual——−560,217,600,000181
——actual——−557,625,600,000183
——actual——−554,947,200,000218
——actual——−552,355,200,000230
——actual——−549,676,800,000242
——actual——−546,998,400,000209
——actual——−544,406,400,000191
——actual——−541,728,000,000172
——actual——−539,136,000,000194
——actual——−536,457,600,000196
——actual——−533,779,200,000196
——actual——−531,360,000,000236
——actual——−528,681,600,000235
——actual——−526,089,600,000229
——actual——−523,411,200,000243
——actual——−520,819,200,000264
——actual——−518,140,800,000272
——actual——−515,462,400,000237
——actual——−512,870,400,000211
——actual——−510,192,000,000180
——actual——−507,600,000,000201

First 60 of 150 rows.

Backtest errors by horizonHow does forecast error grow with the horizon, and how stable is it across origins?
View data
errorhorizonorigin
20.77411960-06-01
−0.902821960-06-01
−2.17731960-06-01
4.84241960-06-01
−17.32051960-06-01
−17.51961960-06-01
Residual autocorrelationIs a series (or a model's residuals) autocorrelated, and at which lags?
View data
ACFboundlag
−0.13430.17891
0.05120.17892
0.04030.17893
−0.08700.17894
0.10660.17895
−0.04140.17896
−0.03980.17897
−0.05200.17898
0.10340.17899
−0.04000.178910
0.03210.178911
0.05370.178912
0.02770.178913
0.03280.178914
−0.08960.178915
−0.14390.178916
−0.08000.178917
0.03890.178918
−0.17430.178919
−0.07260.178920
−0.03220.178921
−0.13800.178922
0.20110.178923
0.05550.178924

Backtest accuracy (1 origin, horizon 6)

MetricValue
MAE10.589
RMSE13.338
MAPE0.0224
sMAPE0.0222
MASE0.3375
WAPE0.0210
Coverage of the 80% interval0.8333
Coverage of the 95% interval0.8333

Forecast

monthForecast80% low80% high95% low95% high
1961-01-01437.49425.22449.77418.72456.27
1961-02-01408.29390.93425.65381.74434.84
1961-03-01432.91411.65454.17400.39465.43
1961-04-01475.85451.30500.40438.30513.40
1961-05-01490.69463.24518.14448.71532.68
1961-06-01562.20532.13592.27516.21608.19
The exact R script · R R version 4.5.1 (2025-06-13)
# Temporal convolutional network forecast (TCN)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method forecast.tcn 1.1.0 · spec e3ec94900af53df1
# Dataset: ml_airpassengers (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr)
# torch for R (LibTorch); the network is built by codesplashr's cs_seq_* / cs_deep_* twins.

# %% Data
TIME <- "month"
VALUE <- "passengers"
SERIES <- NULL
H <- 6
LEVELS <- as.numeric(c(80, 95))
SEASON <- NULL  # NULL = from the time steps (12 monthly, 4 quarterly, 7 daily …)
WINDOWS <- 1
STEP <- NULL  # NULL = the horizon
OFFSETS <- NULL  # the host's BacktestPlan: distance of each origin from the end of the series; NULL = windows and step
TRAIN_WINDOW <- NULL  # NULL = train on all values before each origin
TRAIN_START <- NULL  # rows before this time are left out (for example, before a structural break)
SEED <- 42
XREG <- character(0)
PARAMS <- list(
  channels = 6,
  kernel_size = 3,
  blocks = 2,
  window = 12,
  differencing = "seasonal",
  epochs = 100,
  learning_rate = 0.02,
  batch_size = NULL,
  weight_decay = 0,
  optimizer = "default",
  lr_schedule = "none",
  warmup_epochs = 0,
  grad_clip = 0,
  ema_decay = 0,
  swa_start = 0,
  history_every_step = FALSE,
  profile = "parity",
  checkpoint_every = NULL
)
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ml_airpassengers.parquet", col_select = unique(c(TIME, VALUE, SERIES, XREG))))
cs_check_finite_columns(df, c(TIME, VALUE, XREG))  # infinite values stop with CS_E_NOT_FINITE, naming the column
if (nrow(df) == 0) cs_error("CS_E_NO_ROWS")
warnings <- list()
td <- cs_ml_fc_to_days(df[[TIME]])
times_all <- td$values
TEMPORAL <- td$temporal
values_all <- suppressWarnings(as.numeric(df[[VALUE]]))
x_all <- if (length(XREG)) do.call(cbind, lapply(XREG, function(c) suppressWarnings(as.numeric(df[[c]])))) else NULL
n_early <- 0L
if (!is.null(TRAIN_START)) {
  cut <- cs_ml_fc_parse_time(TRAIN_START, TEMPORAL)
  early <- !is.na(times_all) & times_all < cut
  n_early <- sum(early)
  if (n_early > 0) {
    warnings <- c(warnings, sprintf("%d rows before %s were left out of training.", n_early, as.character(TRAIN_START)))
    times_all[early] <- NA
  }
}
keys_all <- if (!is.null(SERIES)) as.character(df[[SERIES]]) else rep(NA_character_, nrow(df))
dropped <- sum(is.na(times_all)) - n_early
if (dropped > 0) warnings <- c(warnings, sprintf("%d rows without a time were left out.", dropped))
series_keys <- if (!is.null(SERIES)) sort(unique(keys_all[!is.na(keys_all)]), method = "radix") else list(NULL)
if (!is.null(SERIES) && anyNA(keys_all)) warnings <- c(warnings, "Rows without a series name were left out.")
# Degenerate inputs stop with catalog codes, in the same order as the Python driver.
if (all(is.na(values_all))) cs_error("CS_E_ALL_MISSING", column = VALUE)
if (!any(!is.na(times_all) & !is.na(values_all))) cs_error("CS_E_NO_ROWS")
out <- cs_ml_out_dir("target/academy-parity/run-8142/forecast.tcn/seasonal_kernel3/out-r")
extra_tables <- list()  # model blocks may add result tables (assign with <<-)
extra_assumptions <- list()  # … and assumption rows
current_series <- NULL
X_TRAIN <- NULL  # regressors while fit_forecast runs: rows × regressors, aligned with its y
X_FUTURE <- NULL  # … and h × regressors for the steps it forecasts
# Model blocks may set DIAG[[current_series, or "_"]] <<- list(resid = ..., fitdf = k, lags = L) from each fit (the final fit's
# entry is kept): the residuals their own check tests when that is not actual − fitted (GARCH: standardized; ARIMAX:
# the ARMA errors), the ARMA terms they were filtered with, and the Ljung–Box lags when the method's rule differs from
# min(2m, n/5). They go to forecast.parquet so the host's Residuals tab tests the same thing.
DIAG <- list()

# %% Model
# Training options, live progress and checkpoints (twin: codesplash.deep.trainer.configure).
cs_deep_trainer_configure(list(
  optimizer = "default",
  lr_schedule = "none",
  warmup_epochs = 0,
  grad_clip = 0,
  ema_decay = 0,
  swa_start = 0,
  history_every_step = FALSE,
  profile = "parity",
  checkpoint_every = NULL
), out_dir = "target/academy-parity/run-8142/forecast.tcn/seasonal_kernel3/out-r")
# A temporal convolutional network on torch for R (float64, one thread): residual blocks of dilated causal
# convolutions read windows of the standardized (differenced) series and predict the next value; Python's torch
# trains the same network from the same initial weights with the same Adam steps. Forecasts are recursive.
min_train <- function(m) {
  k <- cs_deep_diff_lag(PARAMS$differencing, m)
  L <- if (!is.null(PARAMS$window)) as.integer(PARAMS$window) else if (m > 1) max(as.integer(m), 4L) else 8L
  k + L + 10
}
prepare_series <- function(y, t, m, freq) {
  cs_check_finite(y, VALUE)  # CS_E_NOT_FINITE, like the Python twin
  NULL
}

fit_forecast <- function(y, t, h, m, levels, spec) {
  cs_deep_tcn_fit_forecast(
    y, h, m, levels,
    channels = as.integer(PARAMS$channels),
    kernel_size = as.integer(PARAMS$kernel_size),
    blocks = PARAMS$blocks,
    window = PARAMS$window,
    differencing = PARAMS$differencing,
    epochs = as.integer(PARAMS$epochs),
    lr = PARAMS$learning_rate,
    batch_size = PARAMS$batch_size,
    weight_decay = PARAMS$weight_decay,
    seed = SEED
  )
}

# %% Backtests and forecasts
lv <- function(level) if (level == floor(level)) as.character(as.integer(level)) else gsub(".", "_", as.character(level), fixed = TRUE)
bt_rows <- list()
fc_rows <- list()
facts <- list()
labels <- list()
freq_label <- ""
freq_alias <- ""
seasons <- integer(0)
n_obs <- 0
n_origins <- 0
filled <- 0
residuals_first <- NULL
for (key in series_keys) {
  current_series <- key  # model blocks may read it (e.g. table titles)
  sel <- !is.na(times_all) & (if (!is.null(SERIES)) (!is.na(keys_all) & keys_all == key) else TRUE)
  t_raw <- times_all[sel]; y_raw <- values_all[sel]
  if (sum(!is.na(y_raw)) < 3) {  # too few values to read the time step from
    cs_error("CS_E_TOO_FEW_ROWS", what = if (is.null(key)) "Forecasting" else paste("Series", key), min = min_train(1) + 1, n = sum(!is.na(y_raw)))
  }
  x_later <- NULL
  if (length(XREG)) {  # rows after the last observed value carry known future regressors
    x_raw <- x_all[sel, , drop = FALSE]
    last_y <- max(t_raw[!is.na(y_raw)])
    later <- t_raw > last_y
    x_later <- x_raw[later, , drop = FALSE][order(t_raw[later]), , drop = FALSE]
    t_raw <- t_raw[!later]; y_raw <- y_raw[!later]; x_raw <- x_raw[!later, , drop = FALSE]
  }
  freq <- cs_ml_fc_detect_frequency(sort(t_raw), TEMPORAL)
  reg <- cs_ml_fc_regularize(t_raw, y_raw, freq)
  t <- reg$t; y <- reg$y
  x_grid <- if (length(XREG)) do.call(cbind, lapply(seq_len(ncol(x_raw)), function(j) cs_ml_fc_regularize(t_raw, x_raw[, j], freq)$y)) else NULL
  filled <- filled + reg$filled
  freq_label <- freq$label
  freq_alias <- cs_ml_fc_alias(freq$unit)
  m <- if (!is.null(SEASON)) as.integer(SEASON) else as.integer(freq$season)
  seasons <- c(seasons, m)
  n <- length(y)
  n_obs <- n_obs + n
  if (n < min_train(m) + 1) cs_error("CS_E_TOO_FEW_ROWS", what = if (is.null(key)) "Forecasting" else paste("Series", key), min = min_train(m) + 1, n = n)
  spec <- prepare_series(y, t, m, freq)
  step <- if (!is.null(STEP)) as.integer(STEP) else H
  if (!is.null(OFFSETS)) {
    origins <- cs_ml_fc_plan_origins(n, H, as.integer(OFFSETS), min_train(m))
    if (length(origins) < length(OFFSETS)) {
      warnings <- c(warnings, sprintf("%d of %d backtest origins were skipped for %s: too few values before them.", length(OFFSETS) - length(origins), length(OFFSETS), if (is.null(key)) VALUE else key))
    }
  } else {
    origins <- cs_ml_fc_backtest_origins(n, H, WINDOWS, step, min_train(m))
  }
  for (o in origins) {
    start <- if (!is.null(TRAIN_WINDOW)) max(1L, o - as.integer(TRAIN_WINDOW) + 1L) else 1L
    if (length(XREG)) {
      X_TRAIN <- x_grid[start:o, , drop = FALSE]
      X_FUTURE <- x_grid[(o + 1):(o + H), , drop = FALSE]
    }
    res <- tryCatch(fit_forecast(y[start:o], t[start:o], H, m, LEVELS, spec), error = function(e) e)
    if (inherits(res, "error")) {
      warnings <- c(warnings, sprintf("Backtest from %s failed: %s", cs_ml_fc_format_time(t[o], TEMPORAL), conditionMessage(res)))
      next
    }
    n_origins <- n_origins + 1
    scale <- cs_ml_fc_mase_scale(y[1:o], m)
    scale2 <- cs_ml_fc_rmsse_scale(y[1:o], m)
    lag <- if (m > 1 && o > m) m else 1  # the seasonal naive forecast from this origin (MASE's lag rule)
    for (k in seq_len(H)) {
      row <- list(series = if (is.null(key)) NA_character_ else key, origin = cs_ml_fc_format_time(t[o], TEMPORAL),
                  time = cs_ml_fc_format_time(t[o + k], TEMPORAL), h = k, actual = y[o + k],
                  mean = res$mean[k], scale = scale, scale2 = scale2, last = y[o],
                  snaive = y[o - lag + (k - 1) %% lag + 1])
      for (level in LEVELS) {
        row[[paste0("lo_", lv(level))]] <- res$lower[[as.character(level)]][k]
        row[[paste0("hi_", lv(level))]] <- res$upper[[as.character(level)]][k]
      }
      bt_rows[[length(bt_rows) + 1]] <- row
    }
  }
  if (length(XREG)) {
    X_TRAIN <- x_grid
    X_FUTURE <- cs_ml_fc_future_regressors(x_grid, x_later, H)
    if (nrow(x_later) < H) {
      warnings <- c(warnings, sprintf("Future values of %s are known for %d of %d steps; the last known values are held for the rest.", paste(XREG, collapse = ", "), nrow(x_later), H))
    }
  }
  final <- fit_forecast(y, t, H, m, LEVELS, spec)
  labels[[length(labels) + 1]] <- final$label
  for (name in names(final$facts)) facts[[if (is.null(SERIES)) name else sprintf("%s[%s]", name, key)]] <- final$facts[[name]]
  fitted <- final$fitted
  diag <- DIAG[[if (is.null(key)) "_" else key]]
  resid <- diag$resid
  if (is.null(residuals_first) && !is.null(resid)) {
    residuals_first <- as.numeric(resid)
  } else if (is.null(residuals_first) && !is.null(fitted)) {
    ok <- !is.na(fitted)
    residuals_first <- (y - fitted)[ok]
  }
  skey <- if (is.null(key)) NA_character_ else key
  for (i in seq_len(n)) {
    row <- list(series = skey, time = cs_ml_fc_format_time(t[i], TEMPORAL), t = t[i], kind = "actual", mean = y[i])
    if (!is.null(resid) && i > n - length(resid)) row$resid <- resid[i - (n - length(resid))]  # the last length(resid) times
    if (!is.null(diag$fitdf)) row$lb_fitdf <- as.numeric(diag$fitdf)
    if (!is.null(diag$lags)) row$lb_lags <- as.numeric(diag$lags)
    fc_rows[[length(fc_rows) + 1]] <- row
    if (!is.null(fitted) && !is.na(fitted[i])) {
      fc_rows[[length(fc_rows) + 1]] <- list(series = skey, time = cs_ml_fc_format_time(t[i], TEMPORAL), t = t[i], kind = "fitted", mean = fitted[i])
    }
  }
  future <- cs_ml_fc_future_times(t[n], freq, H)
  for (k in seq_len(H)) {
    row <- list(series = skey, time = cs_ml_fc_format_time(future[k], TEMPORAL), t = future[k], kind = "forecast", mean = final$mean[k])
    for (level in LEVELS) {
      row[[paste0("lo_", lv(level))]] <- final$lower[[as.character(level)]][k]
      row[[paste0("hi_", lv(level))]] <- final$upper[[as.character(level)]][k]
    }
    fc_rows[[length(fc_rows) + 1]] <- row
  }
}
if (filled > 0) warnings <- c(warnings, sprintf("%d missing time steps or values were filled by linear interpolation.", filled))

as_frame <- function(rows) {
  cols <- unique(unlist(lapply(rows, names)))
  as.data.frame(stats::setNames(lapply(cols, function(cn) {
    v <- lapply(rows, function(r) if (is.null(r[[cn]])) NA else r[[cn]])
    unlist(v)
  }), cols), stringsAsFactors = FALSE, check.names = FALSE)
}

# %% Accuracy
bt <- if (length(bt_rows)) as_frame(bt_rows) else data.frame()
accuracy <- if (nrow(bt)) cs_ml_fc_accuracy(bt, LEVELS) else list()
fc_df <- as_frame(fc_rows)
forecasts <- fc_df[fc_df$kind == "forecast", , drop = FALSE]
weights <- seq_len(nrow(forecasts))
top <- if (length(LEVELS)) lv(max(LEVELS)) else NULL
wsum <- function(xs) sum(weights * xs) / sum(weights)
values <- list(
  n_series = length(series_keys), n_obs = n_obs, horizon = H, season = seasons[1], n_origins = n_origins,
  filled = filled, fc_check = wsum(forecasts$mean),
  model_label = if (length(series_keys) == 1) labels[[1]] else sprintf("%d series, one model each", length(series_keys)),
  freq_label = freq_label, frequency = freq_alias
)
if (!is.null(top)) {
  values$fc_lo_check <- wsum(forecasts[[paste0("lo_", top)]])
  values$fc_hi_check <- wsum(forecasts[[paste0("hi_", top)]])
}
for (k in names(accuracy)) values[[sprintf("bt[%s]", k)]] <- accuracy[[k]]
values <- c(values, facts)

nanoparquet::write_parquet(fc_df, file.path(out, "forecast.parquet"))
artifacts <- list(list(key = "forecast", path = file.path(out, "forecast.parquet"), format = "parquet"))
if (nrow(bt)) {
  nanoparquet::write_parquet(bt, file.path(out, "backtest.parquet"))
  artifacts[[2]] <- list(key = "backtest", path = file.path(out, "backtest.parquet"), format = "parquet")
}

# %% Charts
charts <- list()
shown <- if (!is.null(SERIES)) utils::head(series_keys, 8) else NULL
fan <- fc_df[fc_df$kind != "fitted" & (if (!is.null(SERIES)) fc_df$series %in% shown else TRUE), , drop = FALSE]
roles <- list(
  time = cs_col(TIME, fan$time, kind = if (TEMPORAL) "temporal" else "numeric"),
  value = cs_col(VALUE, fan$mean, kind = "numeric"),
  kind = cs_col("kind", fan$kind, kind = "categorical", levels = c("actual", "forecast"))
)
for (level in c(80, 95)) {
  if (level %in% LEVELS) {
    roles[[paste0("lo_", lv(level))]] <- cs_col(paste0("lo_", lv(level)), fan[[paste0("lo_", lv(level))]], kind = "numeric")
    roles[[paste0("hi_", lv(level))]] <- cs_col(paste0("hi_", lv(level)), fan[[paste0("hi_", lv(level))]], kind = "numeric")
  }
}
if (!is.null(SERIES)) roles$series <- cs_col(SERIES, fan$series, kind = "categorical", levels = shown)
charts[[1]] <- cs_chart("forecast", "forecast-fan", sprintf("Forecast of %s", VALUE), roles)
if (nrow(bt)) {
  charts[[length(charts) + 1]] <- cs_chart("backtest", "backtest-errors", "Backtest errors by horizon", list(
    h = cs_col("horizon", bt$h, kind = "numeric"),
    error = cs_col("error", bt$actual - bt$mean, kind = "numeric"),
    origin = cs_col("origin", bt$origin, kind = "categorical")
  ))
}
if (length(residuals_first) > 4) {
  lags <- min(max(2 * seasons[1], 10), length(residuals_first) - 1, 48)
  r_acf <- cs_ml_fc_acf(residuals_first, lags)
  bound <- 1.959963984540054 / sqrt(length(residuals_first))
  charts[[length(charts) + 1]] <- cs_chart("acf", "acf-plot", "Residual autocorrelation", list(
    lag = cs_col("lag", seq_len(lags), kind = "numeric"),
    acf = cs_col("ACF", r_acf, kind = "numeric"),
    bound = cs_col("bound", rep(bound, lags), kind = "numeric")
  ))
}

# %% Result
show <- intersect(c("mae", "rmse", "mape", "smape", "mase", "wape"), names(accuracy))
tables <- list()
if (length(accuracy)) {
  rows <- lapply(show, function(k) list(metric = if (k == "smape") "sMAPE" else toupper(k), value = accuracy[[k]]))
  for (level in LEVELS) {
    ck <- paste0("coverage_", lv(level))
    if (!is.null(accuracy[[ck]])) rows[[length(rows) + 1]] <- list(metric = sprintf("Coverage of the %s%% interval", lv(level)), value = accuracy[[ck]])
  }
  tables[[1]] <- list(key = "accuracy", title = sprintf("Backtest accuracy (%d origin%s, horizon %d)", n_origins, if (n_origins != 1) "s" else "", H),
                      columns = list(list(key = "metric", label = "Metric"), list(key = "value", label = "Value", type = "number")), rows = rows)
}
fc_cols <- c(if (!is.null(SERIES)) list(list(key = "series", label = "Series")),
             list(list(key = "time", label = TIME), list(key = "mean", label = "Forecast", type = "number")))
for (level in LEVELS) {
  fc_cols <- c(fc_cols, list(list(key = paste0("lo_", lv(level)), label = sprintf("%s%% low", lv(level)), type = "number"),
                             list(key = paste0("hi_", lv(level)), label = sprintf("%s%% high", lv(level)), type = "number")))
}
tables <- c(tables, extra_tables)
keep <- setdiff(names(forecasts), c("t", "kind", if (is.null(SERIES)) "series"))
tables[[length(tables) + 1]] <- list(key = "forecast", title = "Forecast", columns = fc_cols,
  rows = lapply(seq_len(min(200, nrow(forecasts))), function(i) as.list(forecasts[i, keep, drop = FALSE])))
summary <- sprintf("%s: %d-step forecasts of %s (%s data, %d observations).", values$model_label, H, VALUE, freq_label, n_obs)
if (!is.null(accuracy$mae)) summary <- paste0(summary, sprintf(" Backtest MAE %s over %d origin%s.", format(signif(accuracy$mae, 3)), n_origins, if (n_origins != 1) "s" else ""))
cs_publish(list(
  title = "Temporal convolutional network forecast (TCN)",
  engine = cs_engine_info("torch", "codesplashr", "nanoparquet"),
  n = n_obs,
  summary = summary,
  statistics = lapply(utils::head(show, 3), function(k) list(key = k, label = toupper(k), value = accuracy[[k]])),
  tables = tables,
  values = values,
  assumptions = extra_assumptions,
  warnings = warnings,
  notes = list(),
  charts = charts,
  artifacts = artifacts
))
Python

TCN on seasonal changes: 6-step forecasts of passengers (monthly data, 144 observations). Backtest MAE 10.6 over 1 origin.

MAE
10.589
RMSE
13.338
MAPE
0.0224

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

Backtest accuracy (1 origin, horizon 6)

MetricValue
MAE10.589
RMSE13.338
MAPE0.0224
sMAPE0.0222
MASE0.3375
WAPE0.0210
Coverage of the 80% interval0.8333
Coverage of the 95% interval0.8333

Forecast

monthForecast80% low80% high95% low95% high
1961-01-01437.49425.22449.77418.72456.27
1961-02-01408.29390.93425.65381.74434.84
1961-03-01432.91411.65454.17400.39465.43
1961-04-01475.85451.30500.40438.30513.40
1961-05-01490.69463.24518.14448.71532.68
1961-06-01562.20532.13592.27516.21608.19
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Temporal convolutional network forecast (TCN)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method forecast.tcn 1.1.0 · spec e3ec94900af53df1
# Dataset: ml_airpassengers (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import math
import os

import numpy as np
import pandas as pd

import codesplash as cs
from codesplash import ml as csml
from codesplash.ml import forecast as fc
from codesplash.errors import check_finite
from codesplash.deep import forecast as deepfc, tcn  # twins of codesplashr::cs_deep_tcn_fit_forecast (torch, shared initial weights)

# %% Data
TIME = "month"
VALUE = "passengers"
SERIES = None
H = 6
LEVELS = [float(v) for v in [80, 95]]
SEASON = None  # None = from the time steps (12 monthly, 4 quarterly, 7 daily …)
WINDOWS = 1
STEP = None  # None = the horizon
OFFSETS = None  # the host's BacktestPlan: distance of each origin from the end of the series; None = windows and step
TRAIN_WINDOW = None  # None = train on all values before each origin
TRAIN_START = None  # rows before this time are left out (for example, before a structural break)
SEED = 42
XREG = []
PARAMS = {
    "channels": 6,
    "kernel_size": 3,
    "blocks": 2,
    "window": 12,
    "differencing": "seasonal",
    "epochs": 100,
    "learning_rate": 0.02,
    "batch_size": None,
    "weight_decay": 0,
    "optimizer": "default",
    "lr_schedule": "none",
    "warmup_epochs": 0,
    "grad_clip": 0,
    "ema_decay": 0,
    "swa_start": 0,
    "history_every_step": False,
    "profile": "parity",
    "checkpoint_every": None,
}
df = pd.read_parquet("tests/parity/fixtures/ml_airpassengers.parquet", columns=list(dict.fromkeys([c for c in (TIME, VALUE, SERIES) if c] + list(XREG))))
cs.check_finite_columns(df, [TIME, VALUE] + list(XREG))  # infinite values stop with CS_E_NOT_FINITE, naming the column
if len(df) == 0:
    cs.cs_error("CS_E_NO_ROWS")
warnings = []
times_all, TEMPORAL = fc.to_days(df[TIME])
values_all = pd.to_numeric(df[VALUE], errors="coerce").to_numpy(dtype=np.float64)
x_all = np.column_stack([pd.to_numeric(df[c], errors="coerce").to_numpy(dtype=np.float64) for c in XREG]) if XREG else None
if TRAIN_START is not None:
    cut = fc.parse_time(TRAIN_START, TEMPORAL)
    early = np.nan_to_num(times_all, nan=np.inf) < cut
    if early.any():
        warnings.append(f"{int(early.sum())} rows before {TRAIN_START} were left out of training.")
        times_all = np.where(early, np.nan, times_all)
keys_all = df[SERIES].astype("object").to_numpy() if SERIES else np.array([None] * len(df), dtype=object)
dropped = int(np.isnan(times_all).sum()) - (int(early.sum()) if TRAIN_START is not None else 0)
if dropped:
    warnings.append(f"{dropped} rows without a time were left out.")
series_keys = sorted({str(k) for k in keys_all if not pd.isna(k)}) if SERIES else [None]  # None, NaN, pd.NA: no name
if SERIES and any(pd.isna(k) for k in keys_all):
    warnings.append("Rows without a series name were left out.")
# Degenerate inputs stop with catalog codes, in the same order as the R driver.
if bool(np.isnan(values_all).all()):
    cs.cs_error("CS_E_ALL_MISSING", column=VALUE)
if not bool((~np.isnan(times_all) & ~np.isnan(values_all)).any()):
    cs.cs_error("CS_E_NO_ROWS")
out = csml.out_dir("target/academy-parity/run-8142/forecast.tcn/seasonal_kernel3/out-python")
extra_tables = []  # model blocks may add result tables (e.g. automatic selection)
extra_assumptions = []  # … and assumption rows
current_series = None
X_TRAIN = None  # regressors while fit_forecast runs: rows × regressors, aligned with its y
X_FUTURE = None  # … and h × regressors for the steps it forecasts
# Model blocks may set DIAG[current_series] = {"resid": [...], "fitdf": k, "lags": L} from each fit (the final fit's
# entry is kept): the residuals their own check tests when that is not actual − fitted (GARCH: standardized; ARIMAX:
# the ARMA errors), the ARMA terms they were filtered with, and the Ljung–Box lags when the method's rule differs from
# min(2m, n/5). They go to forecast.parquet so the host's Residuals tab tests the same thing.
DIAG = {}


# %% Model
from codesplash.deep import trainer as deep_trainer  # training options, live progress, checkpoints (twin: cs_deep_trainer_*)

deep_trainer.configure(
    {
        "optimizer": "default",
        "lr_schedule": "none",
        "warmup_epochs": 0,
        "grad_clip": 0,
        "ema_decay": 0,
        "swa_start": 0,
        "history_every_step": False,
        "profile": "parity",
        "checkpoint_every": None,
    },
    out_dir="target/academy-parity/run-8142/forecast.tcn/seasonal_kernel3/out-python",
)
# A temporal convolutional network on PyTorch (float64, one thread): residual blocks of dilated causal
# convolutions read windows of the standardized (differenced) series and predict the next value; R's torch
# trains the same network from the same initial weights with the same Adam steps. Forecasts are recursive.
def min_train(m):
    k = deepfc.diff_lag(PARAMS["differencing"], m)
    L = int(PARAMS["window"]) if PARAMS["window"] else (max(m, 4) if m > 1 else 8)
    return k + L + 10


def prepare_series(y, t, m, freq):
    check_finite(y, VALUE)  # CS_E_NOT_FINITE, like the R twin
    return None


def fit_forecast(y, t, h, m, levels, spec):
    return tcn.fit_forecast(
        y, h, m, levels,
        channels=int(PARAMS["channels"]),
        kernel_size=int(PARAMS["kernel_size"]),
        blocks=PARAMS["blocks"],
        window=PARAMS["window"],
        differencing=PARAMS["differencing"],
        epochs=int(PARAMS["epochs"]),
        lr=PARAMS["learning_rate"],
        batch_size=PARAMS["batch_size"],
        weight_decay=PARAMS["weight_decay"],
        seed=SEED,
    )


# %% Backtests and forecasts
def lv(level):
    return str(int(level)) if float(level).is_integer() else str(level).replace(".", "_")


bt_rows = []
fc_rows = []
facts = {}
labels = {}
freq_label = ""
freq_alias = ""
seasons = []
n_obs = 0
n_origins = 0
filled = 0
residuals_first = None
for key in series_keys:
    current_series = key  # model blocks may read it (e.g. table titles)
    sel = ~np.isnan(times_all) & ((keys_all.astype(str) == key) if SERIES else True)
    t_raw, y_raw = times_all[sel], values_all[sel]
    if int(np.sum(~np.isnan(y_raw))) < 3:  # too few values to read the time step from
        cs.cs_error("CS_E_TOO_FEW_ROWS", what=("Forecasting" if key is None else f"Series {key}"), min=min_train(1) + 1, n=int(np.sum(~np.isnan(y_raw))))
    x_later = None
    if XREG:  # rows after the last observed value carry known future regressors
        x_raw = x_all[sel]
        last_y = np.nanmax(np.where(np.isnan(y_raw), np.nan, t_raw))
        later = t_raw > last_y
        order_later = np.argsort(t_raw[later], kind="stable")
        x_later = x_raw[later][order_later]
        t_raw, y_raw, x_raw = t_raw[~later], y_raw[~later], x_raw[~later]
    freq = fc.detect_frequency(np.sort(t_raw), TEMPORAL)
    t, y, nfill = fc.regularize(t_raw, y_raw, freq)
    x_grid = np.column_stack([fc.regularize(t_raw, x_raw[:, j], freq)[1] for j in range(x_raw.shape[1])]) if XREG else None
    filled += nfill
    freq_label = freq["label"]
    freq_alias = fc.ALIASES.get(freq["unit"], "")
    m = int(SEASON) if SEASON else int(freq["season"])
    seasons.append(m)
    y = [float(v) for v in y]
    n = len(y)
    n_obs += n
    if n < min_train(m) + 1:
        cs.cs_error("CS_E_TOO_FEW_ROWS", what=("Forecasting" if key is None else f"Series {key}"), min=min_train(m) + 1, n=n)
    spec = prepare_series(y, t, m, freq)
    step = int(STEP) if STEP else H
    if OFFSETS is not None:
        origins = fc.plan_origins(n, H, [int(v) for v in OFFSETS], min_train(m))
        if len(origins) < len(OFFSETS):
            warnings.append(f"{len(OFFSETS) - len(origins)} of {len(OFFSETS)} backtest origins were skipped for {key or VALUE}: too few values before them.")
    else:
        origins = fc.backtest_origins(n, H, WINDOWS, step, min_train(m))
    for o in origins:
        start = max(0, o - int(TRAIN_WINDOW)) if TRAIN_WINDOW else 0
        if XREG:
            X_TRAIN, X_FUTURE = x_grid[start:o], x_grid[o:o + H]
        try:
            res = fit_forecast(y[start:o], t[start:o], H, m, LEVELS, spec)
        except Exception as e:  # a failed origin is skipped, not fatal
            warnings.append(f"Backtest from {fc.format_time(t[o - 1], TEMPORAL)} failed: {e}")
            continue
        n_origins += 1
        scale = fc.mase_scale(y[:o], m)
        scale2 = fc.rmsse_scale(y[:o], m)
        lag = m if (m > 1 and o > m) else 1  # the seasonal naive forecast from this origin (MASE's lag rule)
        for k in range(H):
            row = {
                "series": key,
                "origin": fc.format_time(t[o - 1], TEMPORAL),
                "time": fc.format_time(t[o + k], TEMPORAL),
                "h": k + 1,
                "actual": y[o + k],
                "mean": float(res["mean"][k]),
                "scale": scale,
                "scale2": scale2,
                "last": y[o - 1],
                "snaive": y[o - lag + k % lag],
            }
            for level in LEVELS:
                row[f"lo_{lv(level)}"] = float(res["lower"][level][k])
                row[f"hi_{lv(level)}"] = float(res["upper"][level][k])
            bt_rows.append(row)
    if XREG:
        X_TRAIN = x_grid
        X_FUTURE = fc.future_regressors(x_grid, x_later, H)
        if len(x_later) < H:
            warnings.append(f"Future values of {', '.join(XREG)} are known for {len(x_later)} of {H} steps; the last known values are held for the rest.")
    final = fit_forecast(y, t, H, m, LEVELS, spec)
    labels[key] = final["label"]
    for name, value in final["facts"].items():
        facts[name if not SERIES else f"{name}[{key}]"] = value
    fitted = final.get("fitted")
    diag = DIAG.get(key) or {}
    resid = diag.get("resid")
    if residuals_first is None and resid is not None:
        residuals_first = [float(v) for v in resid]
    elif residuals_first is None and fitted is not None:
        residuals_first = [y[i] - fitted[i] for i in range(n) if fitted[i] is not None and not math.isnan(fitted[i])]
    for i in range(n):
        row = {"series": key, "time": fc.format_time(t[i], TEMPORAL), "t": float(t[i]), "kind": "actual", "mean": y[i]}
        if resid is not None and i >= n - len(resid):  # the last len(resid) times (differencing drops early ones)
            row["resid"] = float(resid[i - (n - len(resid))])
        if "fitdf" in diag:
            row["lb_fitdf"] = float(diag["fitdf"])
        if "lags" in diag:
            row["lb_lags"] = float(diag["lags"])
        fc_rows.append(row)
        if fitted is not None and not math.isnan(fitted[i]):
            fc_rows.append({"series": key, "time": fc.format_time(t[i], TEMPORAL), "t": float(t[i]), "kind": "fitted", "mean": float(fitted[i])})
    future = fc.future_times(t[-1], freq, H)
    for k in range(H):
        row = {"series": key, "time": fc.format_time(future[k], TEMPORAL), "t": float(future[k]), "kind": "forecast", "mean": float(final["mean"][k])}
        for level in LEVELS:
            row[f"lo_{lv(level)}"] = float(final["lower"][level][k])
            row[f"hi_{lv(level)}"] = float(final["upper"][level][k])
        fc_rows.append(row)
if filled:
    warnings.append(f"{filled} missing time steps or values were filled by linear interpolation.")

# %% Accuracy
accuracy = fc.accuracy(bt_rows, LEVELS)
forecasts = [r for r in fc_rows if r["kind"] == "forecast"]
weights = [i + 1.0 for i in range(len(forecasts))]
top = lv(max(LEVELS)) if LEVELS else None


def wsum(xs):
    return fc._sum([weights[i] * xs[i] for i in range(len(xs))]) / fc._sum(weights)


values = {
    "n_series": len(series_keys),
    "n_obs": n_obs,
    "horizon": H,
    "season": seasons[0],
    "n_origins": n_origins,
    "filled": filled,
    "fc_check": wsum([r["mean"] for r in forecasts]),
    "model_label": labels[series_keys[0]] if len(series_keys) == 1 else f"{len(series_keys)} series, one model each",
    "freq_label": freq_label,
    "frequency": freq_alias,
}
if top:
    values["fc_lo_check"] = wsum([r[f"lo_{top}"] for r in forecasts])
    values["fc_hi_check"] = wsum([r[f"hi_{top}"] for r in forecasts])
for k, v in accuracy.items():
    values[f"bt[{k}]"] = v
values.update(facts)

pd.DataFrame(fc_rows).to_parquet(os.path.join(out, "forecast.parquet"), index=False)
artifacts = [{"key": "forecast", "path": os.path.join(out, "forecast.parquet"), "format": "parquet"}]
if bt_rows:
    pd.DataFrame(bt_rows).to_parquet(os.path.join(out, "backtest.parquet"), index=False)
    artifacts.append({"key": "backtest", "path": os.path.join(out, "backtest.parquet"), "format": "parquet"})

# %% Charts
charts = []
shown = series_keys[:8]
fan = [r for r in fc_rows if r["series"] in shown and r["kind"] != "fitted"]
kind = "temporal" if TEMPORAL else "numeric"
roles = {
    "time": cs.col(TIME, [r["time"] for r in fan], kind=kind),
    "value": cs.col(VALUE, [r["mean"] for r in fan], kind="numeric"),
    "kind": cs.col("kind", [r["kind"] for r in fan], kind="categorical", levels=["actual", "forecast"]),
}
for level in (80.0, 95.0):
    if level in LEVELS:
        roles[f"lo_{lv(level)}"] = cs.col(f"lo_{lv(level)}", [r.get(f"lo_{lv(level)}") for r in fan], kind="numeric")
        roles[f"hi_{lv(level)}"] = cs.col(f"hi_{lv(level)}", [r.get(f"hi_{lv(level)}") for r in fan], kind="numeric")
if SERIES:
    roles["series"] = cs.col(SERIES, [r["series"] for r in fan], kind="categorical", levels=shown)
charts.append(cs.chart("forecast", "forecast-fan", f"Forecast of {VALUE}", roles))
if bt_rows:
    charts.append(
        cs.chart(
            "backtest",
            "backtest-errors",
            "Backtest errors by horizon",
            {
                "h": cs.col("horizon", [r["h"] for r in bt_rows], kind="numeric"),
                "error": cs.col("error", [r["actual"] - r["mean"] for r in bt_rows], kind="numeric"),
                "origin": cs.col("origin", [r["origin"] for r in bt_rows], kind="categorical"),
            },
        )
    )
if residuals_first and len(residuals_first) > 4:
    lags = min(max(2 * seasons[0], 10), len(residuals_first) - 1, 48)
    r_acf = fc.acf(residuals_first, lags)
    bound = 1.959963984540054 / math.sqrt(len(residuals_first))
    charts.append(
        cs.chart(
            "acf",
            "acf-plot",
            "Residual autocorrelation",
            {
                "lag": cs.col("lag", list(range(1, lags + 1)), kind="numeric"),
                "acf": cs.col("ACF", r_acf, kind="numeric"),
                "bound": cs.col("bound", [bound] * lags, kind="numeric"),
            },
        )
    )

# %% Result
show = [m for m in ("mae", "rmse", "mape", "smape", "mase", "wape") if m in accuracy]
tables = []
if accuracy:
    tables.append(
        {
            "key": "accuracy",
            "title": f"Backtest accuracy ({n_origins} origin{'s' if n_origins != 1 else ''}, horizon {H})",
            "columns": [{"key": "metric", "label": "Metric"}, {"key": "value", "label": "Value", "type": "number"}],
            "rows": [{"metric": k.upper() if k != "smape" else "sMAPE", "value": accuracy[k]} for k in show]
            + [{"metric": f"Coverage of the {lv(level)}% interval", "value": accuracy.get(f"coverage_{lv(level)}")} for level in LEVELS if f"coverage_{lv(level)}" in accuracy],
        }
    )
tables.extend(extra_tables)
tables.append(
    {
        "key": "forecast",
        "title": "Forecast",
        "columns": ([{"key": "series", "label": "Series"}] if SERIES else [])
        + [{"key": "time", "label": TIME}, {"key": "mean", "label": "Forecast", "type": "number"}]
        + [c for level in LEVELS for c in ({"key": f"lo_{lv(level)}", "label": f"{lv(level)}% low", "type": "number"}, {"key": f"hi_{lv(level)}", "label": f"{lv(level)}% high", "type": "number"})],
        "rows": [{k: v for k, v in r.items() if k not in ("t", "kind") and (SERIES or k != "series")} for r in forecasts[:200]],
    }
)
summary = f"{values['model_label']}: {H}-step forecasts of {VALUE} ({freq_label} data, {n_obs} observations)."
if "mae" in accuracy:
    summary += f" Backtest MAE {accuracy['mae']:.3g} over {n_origins} origin{'s' if n_origins != 1 else ''}."
cs.publish(
    {
        "title": "Temporal convolutional network forecast (TCN)",
        "engine": cs.engine_info("torch", "codesplash", "numpy", "pandas"),
        "n": n_obs,
        "summary": summary,
        "statistics": [{"key": k, "label": k.upper(), "value": accuracy[k]} for k in show[:3]],
        "tables": tables,
        "values": values,
        "assumptions": extra_assumptions,
        "warnings": warnings,
        "notes": [],
        "charts": charts,
        "artifacts": artifacts,
    }
)

CodeSplash runs dilated temporal convolutions on series, not video. This forecaster's receptive fieldReceptive fieldHow many past values one output of a convolutional network can see; for a TCN 1 + 2(k − 1)(2^B − 1). covers 13 months with only 2 blocks of size-3 filters: doubling the dilation each layer grows the reach quickly.

MS-TCN uses the same trick to see minutes of context per frame. Many versions run on features extracted beforehand; if that extractor looked at future frames, so does the model.

04

ActionFormer: intervals from every moment

Read
Reference · VID017 · Runs as a notebookActionFormerFinds action intervals in untrimmed video using a transformer-based temporal feature pyramid and per-location predictions.

ActionFormer runs a transformer over a temporal feature pyramid. At each time step tt it predicts class scores and two distances, to the action's start and end:

[ t−dtL,  t+dtR ].[\,t - d^L_t,\; t + d^R_t\,].

In the reference's toy, a moment at time five with distances two and three decodes to the interval from 3 to 8. Against a true action from four to nine, the temporal IoUTemporal IoUThe overlap of two time intervals divided by the time either covers. One means the same interval; zero, no overlap. is 0.667.

The feature stride limits how precisely a boundary can be placed.

05

Scores for segments

Read
  • Frame accuracy: the share of frames labeled right. Blind to fragments.
  • Edit scoreSegmental edit scoreHow few segment insertions, deletions and swaps turn the predicted order of actions into the true order, scaled to 0–100.: compares the order of predicted segments with the true order. Punishes fragments; ignores timing.
  • Segment F1 at kSegment F1 at an IoU thresholdPrecision and recall of whole segments: a predicted segment counts when its time IoU with a labeled one reaches the threshold.: a predicted segment counts as correct if its temporal IoU with an unmatched true segment of the same class reaches kk.
  • Average precision at tIoUAverage precision of time segments (mAP@tIoU)Average precision of scored segments matched at a time IoU threshold, averaged over classes (the ActivityNet convention).: for localization, ranks predictions by confidence and averages precision over recall, per class and threshold.

Report several of these, at stated thresholds.

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?

How sure?
8

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.

1

Each frame of the second prediction takes the most common action in a window this wide. 1 means no smoothing.

TruthLate boundariesSecond prediction
  • Reach
  • Grasp
  • Lift
  • wrong frame
92Accuracylate92Accuracysecond100Editlate24Editsecond100F1@0.5late23F1@0.5second

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 first; the figure appears when you commit.

Make your prediction to see the result.

06

Tighter thresholds

Predict

Predict first

You raise the temporal IoU needed for a predicted segment to count as correct from 0.1 to 0.5. What happens to segment F1?

F1 risesF1 stays the same or fallsF1 can go either way
Reveal

It stays the same or falls. A match at the stricter threshold is also a match at the looser one, so matches can only be lost. How fast F1 falls shows how precise the boundaries are.

07

Segment scores in CodeSplash

Explore
Segmentation qualityRecorded · Python and R agreeRecorded 2026-11-25 · 30 values compared
R

Across 4 recordings and 3 classes, mean IoU = 0.612, mean Dice = 0.754 and time-weighted accuracy = 0.742. Segment F1: 0.730 at IoU 0.1, 0.730 at IoU 0.25, 0.676 at IoU 0.5. mAP over the thresholds = 0.684.

Mean IoU
0.6119
Mean Dice
0.7536
Time-weighted accuracy
0.7419

Plots

IoU and Dice by classHow do categories compare on one value — and across up to three groups?
View data
labelMeasureOverlap
musicIoU0.4993
musicDice0.6661
noiseIoU0.7616
noiseDice0.8647
speechIoU0.5749
speechDice0.7301
Segment F1, precision and recall by IoU thresholdHow do categories compare on one value — and across up to three groups?
View data
IoU thresholdMeasureShare
IoU 0.1F10.7297
IoU 0.1Precision0.6923
IoU 0.1Recall0.7714
IoU 0.25F10.7297
IoU 0.25Precision0.6923
IoU 0.25Recall0.7714
IoU 0.5F10.6757
IoU 0.5Precision0.6410
IoU 0.5Recall0.7143

Assumptions

  • The reference is complete — Regions or segments missing from the reference turn correct predictions into errors.
  • Reference classes don't overlap — Where reference regions of two classes overlap, the shared part counts for both; accuracy then divides by more than the scored area.

Per class (time overlap)

labelReference secondsPredicted secondsOverlap (seconds)IoUDiceAP@0.1AP@0.25AP@0.5
music41.7004729.5400.49930.66610.55560.55560.5556
noise71.76071.90062.1100.76160.86470.83210.83210.6448
speech71.28053.12045.4100.57490.73010.72730.72730.7273

Segments matched at each IoU threshold

IoU thresholdMatchedFalse alarmsMissedPrecisionRecallF1mAP
0.1000271280.69230.77140.72970.7050
0.2500271280.69230.77140.72970.7050
0.50002514100.64100.71430.67570.6425
  • Reference rows: source = annotation; predictions: source = prediction. Segments match within a recording and class, highest score first.
The exact R script · R R version 4.5.1 (2025-06-13)
# Segmentation quality (IoU, Dice, segment F1)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method evaluate.segments 1.1.0 · spec c2ef3c414cd4e641
# Dataset: img4_intervals (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr)  # cs_eval_seg_* (segmentation scores), cs_eval_det_runs, cs_eval_stacked, cs_rle_* (COCO RLE)

# %% Data
GROUP <- "recording"
FRAME <- NULL
LABEL <- "label"
SOURCE <- "source"
MASK <- NULL
WIDTH <- NULL
HEIGHT <- NULL
CROWD <- NULL
START <- "start"
END <- "end"
SCORE <- "score"
KIND <- "intervals"  # masks | intervals
BACKGROUND <- TRUE
THRESHOLDS <- as.numeric(unlist(c(0.1, 0.25, 0.5)))
if (!length(THRESHOLDS)) THRESHOLDS <- 0.5
THRESHOLDS <- sort(unique(THRESHOLDS))
REF_LEVEL <- NULL
SOURCE_LEVELS <- c("annotation", "prediction")  # stored order
# Reference rows from a second table (option reference_table): its own column for each role, or NULL.
REF_ROLES <- NULL
columns <- unique(c(GROUP, FRAME, LABEL, SOURCE, MASK, WIDTH, HEIGHT, CROWD, START, END, SCORE))
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/img4_intervals.parquet", col_select = columns))
if (KIND == "masks" && (is.null(MASK) || is.null(WIDTH) || is.null(HEIGHT))) {
  cs_error("CS_E_INVALID_OPTION", option = "Segments are", allowed = "time intervals unless the mask, width and height columns are set", value = "masks")
}
if (KIND == "intervals" && (is.null(START) || is.null(END))) {
  cs_error("CS_E_INVALID_OPTION", option = "Segments are", allowed = "masks unless the start and end columns are set", value = "time intervals")
}
pre_warnings <- list()
if (!is.null(REF_ROLES)) {
  # The reference table's rows go above this table's rows under an added source column (twin: with_reference).
  w <- cs_eval_with_reference(df, cs_graph_dataset_option("target/academy-parity/run-8142/evaluate.segments/intervals-scored/out-r", "reference_table"),
                              list(group = GROUP, frame = FRAME, label = LABEL, mask = MASK, width = WIDTH, height = HEIGHT, crowd = CROWD,
                                   start = START, end = END, score = SCORE), REF_ROLES,
                              c(list(frame = "Frame"), if (KIND == "masks") list(mask = "Mask", width = "Image width", height = "Image height") else list(start = "Start", end = "End")),
                              SOURCE, REF_LEVEL, c("group", "label", if (KIND == "masks") c("mask", "width", "height") else c("start", "end")))
  df <- w$df
  pre_warnings <- w$warnings
  wc <- w$columns
  GROUP <- wc$group; FRAME <- wc$frame; LABEL <- wc$label; MASK <- wc$mask; WIDTH <- wc$width; HEIGHT <- wc$height
  CROWD <- wc$crowd; START <- wc$start; END <- wc$end
  SOURCE <- w$source; REF_LEVEL <- w$reference; SOURCE_LEVELS <- w$levels
} else if (is.null(SOURCE)) {
  cs_error("CS_E_INVALID_OPTION", option = "Reference table", allowed = "a table of reference rows unless the Reference or prediction column is set", value = "none")
}
needed <- c(GROUP, LABEL, SOURCE, if (KIND == "masks") c(MASK, WIDTH, HEIGHT) else c(START, END))
numeric_cols <- if (KIND == "masks") c(WIDTH, HEIGHT) else c(START, END, SCORE)
st <- cs_eval_stacked(df, needed, numeric_cols, SOURCE, REF_LEVEL, SOURCE_LEVELS)
df <- st$df
is_ref <- st$is_ref
warnings <- c(pre_warnings, st$warnings)
if (sum(is_ref) == 0L || sum(!is_ref) == 0L) cs_error("CS_E_GROUP_COUNT", column = SOURCE, expected = 2, k = 1)
labels_all <- as.character(df[[LABEL]])
crowd <- if (!is.null(CROWD) && KIND == "masks") cs_eval_flags(df[[CROWD]]) else logical(nrow(df))
crowd[!is_ref] <- FALSE
classes <- sort(unique(labels_all[!crowd]), method = "radix")

if (KIND == "masks") {
  # %% Masks -> runs, per image
  ik <- cs_eval_image_keys(df[[GROUP]], if (!is.null(FRAME)) df[[FRAME]] else NULL)
  img_idx <- ik$index
  ws <- as.numeric(df[[WIDTH]])
  hs <- as.numeric(df[[HEIGHT]])
  runs <- lapply(seq_len(nrow(df)), function(i) {
    tryCatch(cs_eval_det_runs(cs_rle_string_to_counts(as.character(df[[MASK]][i])), as.integer(hs[i]), as.integer(ws[i])),
             error = function(e) NULL)
  })
  n_bad <- sum(vapply(runs, is.null, logical(1)))
  if (n_bad > 0) cs_error("CS_E_INVALID_VALUES", column = MASK, requirement = "a COCO RLE string that covers width × height pixels", count = n_bad)
  ims <- lapply(seq_along(ik$media), function(i) list(n = NULL, size = NULL, ref = list(), pred = list(), void = list()))
  for (i in seq_along(runs)) {
    q <- img_idx[i] + 1L
    r <- runs[[i]]
    if (is.null(ims[[q]]$n)) {
      ims[[q]]$n <- as.numeric(r$size[1]) * as.numeric(r$size[2])
      ims[[q]]$size <- r$size
    } else if (!identical(ims[[q]]$size, r$size)) {
      cs_error("CS_E_INVALID_VALUES", column = sprintf("%s and %s", WIDTH, HEIGHT), requirement = "the same size for every mask of an image", count = 1)
    }
    rr <- list(s = r$s, e = r$e)
    if (crowd[i]) {
      ims[[q]]$void[[length(ims[[q]]$void) + 1L]] <- rr
    } else if (is_ref[i]) {
      lab <- labels_all[i]
      ims[[q]]$ref[[lab]] <- c(if (is.null(ims[[q]]$ref[[lab]])) list() else ims[[q]]$ref[[lab]], list(rr))
    } else {
      lab <- labels_all[i]
      ims[[q]]$pred[[lab]] <- c(if (is.null(ims[[q]]$pred[[lab]])) list() else ims[[q]]$pred[[lab]], list(rr))
    }
  }
  res <- cs_eval_seg_masks(ims, classes, BACKGROUND)
  names_ <- res$classes
  n_ref <- sum(is_ref & !crowd)
  n_pred <- sum(!is_ref)
  unit <- "pixels"
  group_rows <- lapply(seq_along(ik$media), function(i) list(group = ik$media[i], frame = if (is.infinite(ik$frame[i])) NA_real_ else ik$frame[i],
                                                             miou = if (is.null(res$per_image[[i]])) NA_real_ else res$per_image[[i]]))
  n_groups <- length(ik$media)
  has_score <- FALSE
} else {
  # %% Intervals per recording
  s_all <- as.numeric(df[[START]])
  e_all <- as.numeric(df[[END]])
  bad <- e_all < s_all
  if (any(bad)) cs_error("CS_E_INVALID_VALUES", column = END, requirement = sprintf("at least %s", START), count = sum(bad))
  sc_all <- if (!is.null(SCORE)) as.numeric(df[[SCORE]]) else rep(NA_real_, nrow(df))
  has_score <- !is.null(SCORE)
  if (has_score) {
    miss <- !is_ref & is.na(sc_all)
    if (any(miss)) {
      warnings <- c(warnings, sprintf("%d predicted segments have no %s and were left out.", sum(miss), SCORE))
      keep <- !miss
      df <- df[keep, , drop = FALSE]; is_ref <- is_ref[keep]; labels_all <- labels_all[keep]
      s_all <- s_all[keep]; e_all <- e_all[keep]; sc_all <- sc_all[keep]
      classes <- sort(unique(labels_all), method = "radix")
    }
  }
  grp <- as.character(df[[GROUP]])
  groups <- sort(unique(grp), method = "radix")
  recs <- lapply(groups, function(g) {
    rows <- which(grp == g)
    rr <- rows[is_ref[rows]]
    pr <- rows[!is_ref[rows]]
    list(ref = data.frame(start = s_all[rr], end = e_all[rr], label = labels_all[rr], stringsAsFactors = FALSE),
         pred = data.frame(start = s_all[pr], end = e_all[pr], label = labels_all[pr], score = if (has_score) sc_all[pr] else rep(0, length(pr)),
                           row = pr - 1L, stringsAsFactors = FALSE))
  })
  res <- cs_eval_seg_intervals(recs, classes, THRESHOLDS, has_score)
  names_ <- res$classes
  n_ref <- res$n_ref
  n_pred <- res$n_pred
  unit <- "seconds"
  n_groups <- length(groups)
}

# %% Assumptions
assumptions <- list(
  list(key = "complete", label = "The reference is complete", status = "info",
       detail = "Regions or segments missing from the reference turn correct predictions into errors."),
  list(key = "overlap", label = "Reference classes don't overlap", status = "info",
       detail = "Where reference regions of two classes overlap, the shared part counts for both; accuracy then divides by more than the scored area.")
)

# %% Result
f3 <- function(v) if (is.null(v) || is.na(v)) "—" else sprintf("%.3f", v)
tkey <- function(t) sprintf("%g", t)
values <- list(kind = KIND, n_groups = n_groups, n_classes = length(names_), n_reference = n_ref, n_predictions = n_pred,
               accuracy = res$accuracy, miou = res$miou, mean_dice = res$mean_dice, fw_iou = res$fw_iou,
               scored = if (!is.null(res$scored)) res$scored else sum(res$gsum), ignored = if (!is.null(res$ignored)) res$ignored else NA_real_,
               map = NA_real_)
for (j in seq_along(names_)) {
  values[[sprintf("iou[%s]", names_[j])]] <- res$iou[j]
  values[[sprintf("dice[%s]", names_[j])]] <- res$dice[j]
}
cls_cols <- list(list(key = "class", label = LABEL, type = "string"), list(key = "ref", label = sprintf("Reference %s", unit), type = "number"),
                 list(key = "pred", label = sprintf("Predicted %s", unit), type = "number"), list(key = "inter", label = sprintf("Overlap (%s)", unit), type = "number"),
                 list(key = "iou", label = "IoU", type = "number"), list(key = "dice", label = "Dice", type = "number"))
cls_rows <- lapply(seq_along(names_), function(j) list(class = names_[j], ref = res$gsum[j], pred = res$psum[j], inter = res$inter[j],
                                                       iou = res$iou[j], dice = res$dice[j]))
tables <- list()
charts <- list()
if (KIND == "intervals") {
  m_rows <- res$matching
  for (r in m_rows) {
    values[[sprintf("f1[%s]", tkey(r$threshold))]] <- r$f1
    values[[sprintf("precision[%s]", tkey(r$threshold))]] <- r$precision
    values[[sprintf("recall[%s]", tkey(r$threshold))]] <- r$recall
    if (has_score) values[[sprintf("ap[%s]", tkey(r$threshold))]] <- r$map
  }
  if (has_score) {
    maps <- vapply(m_rows, function(r) r$map, numeric(1))
    maps <- maps[!is.na(maps)]
    values$map <- if (length(maps)) mean(maps) else NA_real_
    for (r in m_rows) {
      key <- sprintf("ap_%s", tkey(r$threshold))
      cls_cols[[length(cls_cols) + 1L]] <- list(key = key, label = sprintf("AP@%s", tkey(r$threshold)), type = "number")
      for (j in seq_along(cls_rows)) cls_rows[[j]][[key]] <- if (is.null(r$ap[[cls_rows[[j]]$class]])) NA_real_ else r$ap[[cls_rows[[j]]$class]]
    }
  }
  tables[[length(tables) + 1L]] <- list(key = "classes", title = "Per class (time overlap)", columns = cls_cols, rows = cls_rows)
  mcols <- list(list(key = "threshold", label = "IoU threshold", type = "number"), list(key = "tp", label = "Matched", type = "integer"),
                list(key = "fp", label = "False alarms", type = "integer"), list(key = "fn", label = "Missed", type = "integer"),
                list(key = "precision", label = "Precision", type = "number"), list(key = "recall", label = "Recall", type = "number"),
                list(key = "f1", label = "F1", type = "number"))
  if (has_score) mcols[[length(mcols) + 1L]] <- list(key = "map", label = "mAP", type = "number")
  tables[[length(tables) + 1L]] <- list(key = "matching", title = "Segments matched at each IoU threshold", columns = mcols,
    rows = lapply(m_rows, function(r) r[c("threshold", "tp", "fp", "fn", "precision", "recall", "f1", "map")]))
  pc <- character(0); pm <- character(0); pv <- numeric(0)
  for (r in m_rows) for (km in list(c("f1", "F1"), c("precision", "Precision"), c("recall", "Recall"))) if (!is.na(r[[km[1]]])) {
    pc <- c(pc, sprintf("IoU %s", tkey(r$threshold))); pm <- c(pm, km[2]); pv <- c(pv, r[[km[1]]])
  }
  if (length(pv)) {
    charts[[length(charts) + 1L]] <- cs_chart("f1-at-iou", "cleveland-dot", "Segment F1, precision and recall by IoU threshold", list(
      category = cs_col("IoU threshold", pc, "categorical", levels = vapply(m_rows, function(r) sprintf("IoU %s", tkey(r$threshold)), character(1))),
      value = cs_col("Share", pv, "numeric"),
      group = cs_col("Measure", pm, "categorical", levels = c("F1", "Precision", "Recall"))))
  }
} else {
  tables[[length(tables) + 1L]] <- list(key = "classes", title = "Per class (pixels summed over images)", columns = cls_cols, rows = cls_rows)
  tables[[length(tables) + 1L]] <- list(key = "images", title = "Mean IoU per image", rows = utils::head(group_rows, 500),
    columns = c(list(list(key = "group", label = GROUP, type = "string")), if (!is.null(FRAME)) list(list(key = "frame", label = FRAME, type = "number")),
                list(list(key = "miou", label = "Mean IoU", type = "number"))),
    note = if (length(group_rows) > 500) "First 500 images." else NULL)
}
dc <- character(0); dm <- character(0); dv <- numeric(0)
for (j in seq_along(names_)) for (km in list(c("iou", "IoU"), c("dice", "Dice"))) if (!is.na(res[[km[1]]][j])) {
  dc <- c(dc, names_[j]); dm <- c(dm, km[2]); dv <- c(dv, res[[km[1]]][j])
}
if (length(dv)) {
  charts <- c(list(cs_chart("by-class", "cleveland-dot", "IoU and Dice by class", list(
    category = cs_col(LABEL, dc, "categorical", levels = names_), value = cs_col("Overlap", dv, "numeric"),
    group = cs_col("Measure", dm, "categorical", levels = c("IoU", "Dice"))))), charts)
}
what <- if (KIND == "masks") "pixel accuracy" else "time-weighted accuracy"
summary <- sprintf("Across %d %s and %d classes, mean IoU = %s, mean Dice = %s and %s = %s.", n_groups, if (KIND == "masks") "images" else "recordings",
                   length(names_), f3(res$miou), f3(res$mean_dice), what, f3(res$accuracy))
if (KIND == "intervals") {
  summary <- paste0(summary, " Segment F1: ", paste(vapply(res$matching, function(r) sprintf("%s at IoU %s", f3(r$f1), tkey(r$threshold)), character(1)), collapse = ", "), ".")
  if (has_score && !is.na(values$map)) summary <- paste0(summary, sprintf(" mAP over the thresholds = %s.", f3(values$map)))
}
cs_publish(list(
  method = "evaluate.segments",
  methodVersion = "1.1.0",
  title = "Segmentation quality",
  engine = cs_engine_info("nanoparquet"),
  n = nrow(df),
  summary = summary,
  statistics = list(list(key = "miou", label = "Mean IoU", value = res$miou), list(key = "mean_dice", label = "Mean Dice", value = res$mean_dice),
                    list(key = "accuracy", label = if (KIND == "masks") "Pixel accuracy" else "Time-weighted accuracy", value = res$accuracy)),
  tables = tables,
  assumptions = assumptions,
  warnings = warnings,
  notes = list(paste0(if (is.null(REF_ROLES)) sprintf("Reference rows: %s = %s; predictions: %s = %s. ", SOURCE, st$reference, SOURCE, st$prediction)
                      else "Reference rows come from the reference table; this table's rows are the predictions. ",
                      if (KIND == "masks") paste0("Masks are compared on their run lengths (no pixels decoded)", if (BACKGROUND) "; unlabeled pixels form a background class" else "",
                                                  if (!is.null(CROWD)) "; crowd regions are left out of scoring" else "", ".")
                      else paste0("Segments match within a recording and class, ", if (!is.null(SCORE)) "highest score first." else "earliest first."))),
  charts = charts,
  values = values
))
Python

Across 4 recordings and 3 classes, mean IoU = 0.612, mean Dice = 0.754 and time-weighted accuracy = 0.742. Segment F1: 0.730 at IoU 0.1, 0.730 at IoU 0.25, 0.676 at IoU 0.5. mAP over the thresholds = 0.684.

Mean IoU
0.6119
Mean Dice
0.7536
Time-weighted accuracy
0.7419

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

Assumptions

  • The reference is complete — Regions or segments missing from the reference turn correct predictions into errors.
  • Reference classes don't overlap — Where reference regions of two classes overlap, the shared part counts for both; accuracy then divides by more than the scored area.

Per class (time overlap)

labelReference secondsPredicted secondsOverlap (seconds)IoUDiceAP@0.1AP@0.25AP@0.5
music41.7004729.5400.49930.66610.55560.55560.5556
noise71.76071.90062.1100.76160.86470.83210.83210.6448
speech71.28053.12045.4100.57490.73010.72730.72730.7273

Segments matched at each IoU threshold

IoU thresholdMatchedFalse alarmsMissedPrecisionRecallF1mAP
0.1000271280.69230.77140.72970.7050
0.2500271280.69230.77140.72970.7050
0.50002514100.64100.71430.67570.6425
  • Reference rows: source = annotation; predictions: source = prediction. Segments match within a recording and class, highest score first.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Segmentation quality (IoU, Dice, segment F1)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method evaluate.segments 1.1.0 · spec c2ef3c414cd4e641
# Dataset: img4_intervals (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.

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

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

# %% Data
GROUP = "recording"
FRAME = None
LABEL = "label"
SOURCE = "source"
MASK = None
WIDTH = None
HEIGHT = None
CROWD = None
START = "start"
END = "end"
SCORE = "score"
KIND = "intervals"  # masks | intervals
BACKGROUND = True
THRESHOLDS = [float(t) for t in [0.1, 0.25, 0.5]] or [0.5]
THRESHOLDS = sorted(set(THRESHOLDS))
REF_LEVEL = None
SOURCE_LEVELS = ["annotation", "prediction"]  # stored order
# Reference rows from a second table (option reference_table): its own column for each role, or None.
REF_ROLES = None
columns = list(dict.fromkeys(c for c in [GROUP, FRAME, LABEL, SOURCE, MASK, WIDTH, HEIGHT, CROWD, START, END, SCORE] if c))
df = pd.read_parquet("tests/parity/fixtures/img4_intervals.parquet", columns=columns)
if KIND == "masks" and not (MASK and WIDTH and HEIGHT):
    cs.cs_error("CS_E_INVALID_OPTION", option="Segments are", allowed="time intervals unless the mask, width and height columns are set", value="masks")
if KIND == "intervals" and not (START and END):
    cs.cs_error("CS_E_INVALID_OPTION", option="Segments are", allowed="masks unless the start and end columns are set", value="time intervals")
pre_warnings = []
if REF_ROLES is not None:
    # The reference table's rows go above this table's rows under an added source column (twin: cs_eval_with_reference).
    from codesplash.graph import dataset_option  # the table the host wrote for the option
    from codesplash.evaluate.stacked import with_reference
    w = with_reference(df, dataset_option("target/academy-parity/run-8142/evaluate.segments/intervals-scored/out-python", "reference_table"),
                       {"group": GROUP, "frame": FRAME, "label": LABEL, "mask": MASK, "width": WIDTH, "height": HEIGHT, "crowd": CROWD,
                        "start": START, "end": END, "score": SCORE}, REF_ROLES,
                       {"frame": "Frame", **({"mask": "Mask", "width": "Image width", "height": "Image height"} if KIND == "masks" else {"start": "Start", "end": "End"})},
                       SOURCE, REF_LEVEL, ["group", "label"] + (["mask", "width", "height"] if KIND == "masks" else ["start", "end"]))
    df, pre_warnings, wc = w["df"], w["warnings"], w["columns"]
    GROUP, FRAME, LABEL, MASK, WIDTH, HEIGHT = wc["group"], wc["frame"], wc["label"], wc["mask"], wc["width"], wc["height"]
    CROWD, START, END = wc["crowd"], wc["start"], wc["end"]
    SOURCE, REF_LEVEL, SOURCE_LEVELS = w["source"], w["reference"], w["levels"]
elif SOURCE is None:
    cs.cs_error("CS_E_INVALID_OPTION", option="Reference table", allowed="a table of reference rows unless the Reference or prediction column is set", value="none")
needed = [GROUP, LABEL, SOURCE] + ([MASK, WIDTH, HEIGHT] if KIND == "masks" else [START, END])
numeric = [WIDTH, HEIGHT] if KIND == "masks" else [c for c in [START, END, SCORE] if c]
st = stacked(df, needed, numeric, SOURCE, REF_LEVEL, SOURCE_LEVELS)
df, is_ref, warnings = st["df"], st["is_ref"], pre_warnings + st["warnings"]
if int(is_ref.sum()) == 0 or int((~is_ref).sum()) == 0:
    cs.cs_error("CS_E_GROUP_COUNT", column=SOURCE, expected=2, k=1)
labels_all = np.asarray([str(x) for x in df[LABEL].tolist()], dtype=object)
crowd = flags(df[CROWD]) if (CROWD and KIND == "masks") else np.zeros(len(df), dtype=bool)
crowd[~is_ref] = False
classes = sorted(set(labels_all[~crowd].tolist()))

if KIND == "masks":
    # %% Masks → runs, per image
    img_idx, images = image_keys(df[GROUP], df[FRAME] if FRAME else None)
    ws, hs = df[WIDTH].to_numpy(dtype=float), df[HEIGHT].to_numpy(dtype=float)
    runs, n_bad = [], 0
    for s, w, h in zip(df[MASK].tolist(), ws, hs):
        try:
            runs.append(det.runs_from_counts(vb.string_to_counts(str(s)), int(h), int(w)))
        except (ValueError, OverflowError):
            runs.append(None)
            n_bad += 1
    if n_bad:
        cs.cs_error("CS_E_INVALID_VALUES", column=MASK, requirement="a COCO RLE string that covers width × height pixels", count=n_bad)
    ims = [{"n": None, "ref": {}, "pred": {}, "void": []} for _ in images]
    for i, r in enumerate(runs):
        im = ims[int(img_idx[i])]
        n = float(r[2][0]) * float(r[2][1])
        if im["n"] is None:
            im["n"], im["size"] = n, r[2]
        elif im["size"] != r[2]:
            cs.cs_error("CS_E_INVALID_VALUES", column=f"{WIDTH} and {HEIGHT}", requirement="the same size for every mask of an image", count=1)
        if crowd[i]:
            im["void"].append(r[:2])
        else:
            side = im["ref"] if is_ref[i] else im["pred"]
            side.setdefault(labels_all[i], []).append(r[:2])
    res = seg.mask_scores(ims, classes, BACKGROUND)
    names = res["classes"]
    n_ref = int(np.sum(is_ref & ~crowd))
    n_pred = int(np.sum(~is_ref))
    unit = "pixels"
    group_rows = [{"group": m, "frame": None if f == float("-inf") else f, "miou": res["per_image"][i]} for i, (m, f) in enumerate(images)]
    n_groups = len(images)
else:
    # %% Intervals per recording
    s_all, e_all = df[START].to_numpy(dtype=float), df[END].to_numpy(dtype=float)
    bad = e_all < s_all
    if bad.any():
        cs.cs_error("CS_E_INVALID_VALUES", column=END, requirement=f"at least {START}", count=int(bad.sum()))
    sc_all = df[SCORE].to_numpy(dtype=float, na_value=np.nan) if SCORE else np.full(len(df), np.nan)
    has_score = SCORE is not None
    if has_score:
        miss = ~is_ref & np.isnan(sc_all)
        if miss.any():
            warnings.append(f"{int(miss.sum())} predicted segments have no {SCORE} and were left out.")
            keep = ~miss
            df, is_ref, labels_all, s_all, e_all, sc_all = df.loc[keep].reset_index(drop=True), is_ref[keep], labels_all[keep], s_all[keep], e_all[keep], sc_all[keep]
            classes = sorted(set(labels_all.tolist()))
    grp = np.asarray([str(x) for x in df[GROUP].tolist()], dtype=object)
    groups = sorted(set(grp.tolist()))
    recs = []
    for g in groups:
        rows = np.flatnonzero(grp == g)
        recs.append({"ref": [(s_all[i], e_all[i], labels_all[i]) for i in rows if is_ref[i]],
                     "pred": [(s_all[i], e_all[i], labels_all[i], float(sc_all[i]) if has_score else 0.0, int(i)) for i in rows if not is_ref[i]]})
    res = seg.interval_scores(recs, classes, THRESHOLDS, has_score)
    names = res["classes"]
    n_ref, n_pred = res["n_ref"], res["n_pred"]
    unit = "seconds"
    n_groups = len(groups)

# %% Assumptions
assumptions = [
    {"key": "complete", "label": "The reference is complete", "status": "info",
     "detail": "Regions or segments missing from the reference turn correct predictions into errors."},
    {"key": "overlap", "label": "Reference classes don't overlap", "status": "info",
     "detail": "Where reference regions of two classes overlap, the shared part counts for both; accuracy then divides by more than the scored area."},
]

# %% Result
f3 = lambda v: "—" if v is None else f"{v:.3f}"
tkey = lambda t: "%g" % t
values = {"kind": KIND, "n_groups": n_groups, "n_classes": len(names), "n_reference": n_ref, "n_predictions": n_pred,
          "accuracy": res["accuracy"], "miou": res["miou"], "mean_dice": res["mean_dice"], "fw_iou": res["fw_iou"],
          "scored": res.get("scored", float(np.sum(res["gsum"]))), "ignored": res.get("ignored"), "map": None}
for j, c in enumerate(names):
    values[f"iou[{c}]"] = res["iou"][j]
    values[f"dice[{c}]"] = res["dice"][j]
cls_cols = [{"key": "class", "label": LABEL, "type": "string"}, {"key": "ref", "label": f"Reference {unit}", "type": "number"},
            {"key": "pred", "label": f"Predicted {unit}", "type": "number"}, {"key": "inter", "label": f"Overlap ({unit})", "type": "number"},
            {"key": "iou", "label": "IoU", "type": "number"}, {"key": "dice", "label": "Dice", "type": "number"}]
cls_rows = [{"class": c, "ref": float(res["gsum"][j]), "pred": float(res["psum"][j]), "inter": float(res["inter"][j]),
             "iou": res["iou"][j], "dice": res["dice"][j]} for j, c in enumerate(names)]
tables = []
charts = []
if KIND == "intervals":
    m_rows = res["matching"]
    for r in m_rows:
        values[f"f1[{tkey(r['threshold'])}]"] = r["f1"]
        values[f"precision[{tkey(r['threshold'])}]"] = r["precision"]
        values[f"recall[{tkey(r['threshold'])}]"] = r["recall"]
        if has_score:
            values[f"ap[{tkey(r['threshold'])}]"] = r["map"]
    if has_score:
        maps = [r["map"] for r in m_rows if r["map"] is not None]
        values["map"] = float(np.mean(maps)) if maps else None
        for r in m_rows:
            cls_cols.append({"key": f"ap_{tkey(r['threshold'])}", "label": f"AP@{tkey(r['threshold'])}", "type": "number"})
            for row in cls_rows:
                row[f"ap_{tkey(r['threshold'])}"] = r["ap"].get(row["class"])
    tables.append({"key": "classes", "title": "Per class (time overlap)", "columns": cls_cols, "rows": cls_rows})
    tables.append({"key": "matching", "title": "Segments matched at each IoU threshold",
                   "columns": [{"key": "threshold", "label": "IoU threshold", "type": "number"}, {"key": "tp", "label": "Matched", "type": "integer"},
                               {"key": "fp", "label": "False alarms", "type": "integer"}, {"key": "fn", "label": "Missed", "type": "integer"},
                               {"key": "precision", "label": "Precision", "type": "number"}, {"key": "recall", "label": "Recall", "type": "number"},
                               {"key": "f1", "label": "F1", "type": "number"}] + ([{"key": "map", "label": "mAP", "type": "number"}] if has_score else []),
                   "rows": [{k: r[k] for k in ("threshold", "tp", "fp", "fn", "precision", "recall", "f1", "map")} for r in m_rows]})
    pts = [(f"IoU {tkey(r['threshold'])}", lab, r[key]) for r in m_rows for key, lab in (("f1", "F1"), ("precision", "Precision"), ("recall", "Recall")) if r[key] is not None]
    if pts:
        charts.append(cs.chart("f1-at-iou", "cleveland-dot", "Segment F1, precision and recall by IoU threshold", {
            "category": cs.col("IoU threshold", [p[0] for p in pts], "categorical", levels=[f"IoU {tkey(r['threshold'])}" for r in m_rows]),
            "value": cs.col("Share", [p[2] for p in pts], "numeric"),
            "group": cs.col("Measure", [p[1] for p in pts], "categorical", levels=["F1", "Precision", "Recall"])}))
else:
    tables.append({"key": "classes", "title": "Per class (pixels summed over images)", "columns": cls_cols, "rows": cls_rows})
    tables.append({"key": "images", "title": "Mean IoU per image", "rows": group_rows[:500],
                   "columns": [{"key": "group", "label": GROUP, "type": "string"}] + ([{"key": "frame", "label": FRAME, "type": "number"}] if FRAME else [])
                   + [{"key": "miou", "label": "Mean IoU", "type": "number"}], "note": "First 500 images." if len(group_rows) > 500 else None})
dots = [(c, m, res[key][j]) for j, c in enumerate(names) for key, m in (("iou", "IoU"), ("dice", "Dice")) if res[key][j] is not None]
if dots:
    charts.insert(0, cs.chart("by-class", "cleveland-dot", "IoU and Dice by class", {
        "category": cs.col(LABEL, [d[0] for d in dots], "categorical", levels=names),
        "value": cs.col("Overlap", [d[2] for d in dots], "numeric"),
        "group": cs.col("Measure", [d[1] for d in dots], "categorical", levels=["IoU", "Dice"])}))
what = "pixel accuracy" if KIND == "masks" else "time-weighted accuracy"
summary = (f"Across {n_groups} {'images' if KIND == 'masks' else 'recordings'} and {len(names)} classes, mean IoU = {f3(res['miou'])}, "
           f"mean Dice = {f3(res['mean_dice'])} and {what} = {f3(res['accuracy'])}.")
if KIND == "intervals":
    summary += " Segment F1: " + ", ".join(f"{f3(r['f1'])} at IoU {tkey(r['threshold'])}" for r in res["matching"]) + "."
    if has_score and values["map"] is not None:
        summary += f" mAP over the thresholds = {f3(values['map'])}."
cs.publish({
    "method": "evaluate.segments",
    "methodVersion": "1.1.0",
    "title": "Segmentation quality",
    "engine": cs.engine_info("pandas", "numpy"),
    "n": int(len(df)),
    "summary": summary,
    "statistics": [{"key": "miou", "label": "Mean IoU", "value": res["miou"]}, {"key": "mean_dice", "label": "Mean Dice", "value": res["mean_dice"]},
                   {"key": "accuracy", "label": "Pixel accuracy" if KIND == "masks" else "Time-weighted accuracy", "value": res["accuracy"]}],
    "tables": tables,
    "assumptions": assumptions,
    "warnings": warnings,
    "notes": [(f"Reference rows: {SOURCE} = {st['reference']}; predictions: {SOURCE} = {st['prediction']}. " if REF_ROLES is None
               else "Reference rows come from the reference table; this table's rows are the predictions. ")
              + ("Masks are compared on their run lengths (no pixels decoded)" + ("; unlabeled pixels form a background class" if BACKGROUND else "")
                 + ("; crowd regions are left out of scoring" if CROWD else "") + "." if KIND == "masks"
                 else "Segments match within a recording and class, " + ("highest score first." if SCORE else "earliest first."))],
    "charts": charts,
    "values": values,
})

Segmentation quality with Segments set to Time intervals compares 39 predicted segments with 35 reference segments over 4 recordings. Segment F1 is 0.730 at IoU 0.1 and 0.676 at 0.5. With confidence scores, mean average precision across classes and thresholds is 0.684.

These segments are audio events here; video actions in the same table form score the same way. Edit score isn't computed.

08

Splits and leakage

Read
  • Keep every frame, clip and proposal of a video in one split.
  • Precomputed features are part of the method: say what extracted them and whether they saw future frames.
  • Break results down by action duration: short actions are where both models and smoothing fail.
  • Overlapping actions and annotation habits (where exactly "pouring" starts) can dominate what generalizes.
09

What runs here

Read
EntryIn CodeSplash
VID016 · Multi-Stage Temporal Convolutional NetworkRuns as a notebook (the reference program; no method)
VID017 · ActionFormerRuns as a notebook (the reference program; no method)
10

Check: temporal segmentation

Checkpoint

Check yourself

What does MS-TCN output?

Show the answer

Answer: b

It is a frame-wise segmenter; later stages clean up the earlier stages' fragments.

Check yourself

Why is MS-TCN's smoothing penalty truncated at τ?

Show the answer

Answer: a

Without the cap, smoothing would also erase real changes and short real actions.

Check yourself

An action segmenter reports only frame accuracy. What is missing?

Show the answer

Answer: b

Frame accuracy can be high while actions are chopped into fragments. Segment scores catch that.

Check yourself

At time 20, ActionFormer predicts distances 4 to the start and 6 to the end. What interval does that give?

Show the answer

Answer: b

Start = t − d_left, end = t + d_right.

Check yourself

How is a temporal localization model like ActionFormer usually scored?

Show the answer

Answer: b

Localization produces scored intervals; average precision at tIoU thresholds rewards both detection and boundary precision.

Check yourself

What limits how precisely ActionFormer can place an action boundary?

Show the answer

Answer: b

Boundaries can't be placed more finely than the time step between feature vectors.

Check yourself

A predicted action runs from 2 s to 6 s; the true one from 4 s to 8 s. What is their temporal IoU?

Show the answer

Answer: b

They overlap for 2 s out of the 6 s either covers: 2/6.

Check yourself

In the interval run above, what is segment F1 at temporal IoU 0.5? Give three decimals.

Show the answer

Answer: 0.675675675675676

Lower than at 0.1: some predicted segments overlap their match enough to count loosely but not strictly.

11

Recap

Recap
  • Classification, frame-wise segmentation and interval localization are different targets with different scores.
  • MS-TCN refines frame labels and smooths them with a capped penalty; dilated convolutions give it long reach.
  • ActionFormer predicts distances to start and end at each moment; feature stride limits precision.
  • Report frame accuracy, edit score, segment F1 at several thresholds and average precision; keep each video in one split.

Concepts in this lesson