Skip to content

Counting errors: word and character error rates, and SI-SDR for signals

When there is one right output, count how far a system is from it. Align a transcript to its reference and count substitutions, deletions and insertions, then meet SI-SDR, the same idea for a separated audio signal.

Applied ~14 min8 steps

What runs in CodeSplash

You will be able to

  • Compute WER from an edit alignment and explain why it can exceed 100%
  • Choose between word and character error rates, and state the normalization used
  • Read substitution, deletion and insertion counts to see how a system fails
  • Explain what SI-SDR measures and why it ignores the signal's scale

Read first

01

Edits to the reference

Read

For a transcript or any output with one right answer, align it with the reference word by word using the fewest edits. Each edit is a substitution (S), a deletion (D, a reference word missing) or an insertion (I, an extra word). The word error rateWord error rateSubstitutions + deletions + insertions needed to turn the output into its closest reference, over reference words, in %. divides the total by the number of reference words N:

WER=S+D+IN\mathrm{WER} = \frac{S + D + I}{N}

With 4 substitutions, 2 deletions and 3 insertions against 100 reference words, the reference program gets 9%. Insertions aren't bounded by N, so a system that babbles can exceed 100%. The character error rateCharacter error rateThe same edit count per reference character (spaces included), in %; useful for languages written without spaces. does the same on characters, which suits languages written without spaces.

02

Two systems, with their edits

Read
Generated-text metrics (BLEU, chrF, ROUGE)Recorded · Python and R agreeRecorded 2026-11-25 · 78 values compared
R

system_a: BLEU 68.8, chrF 82.9, ROUGE-L F1 85.6 on 30 rows. WER 23.5%, CER 15.4%.

BLEU
68.780
chrF
82.896
ROUGE-1 F1
90.323
ROUGE-2 F1
74.155
ROUGE-L F1
85.566
Brevity penalty
0.9770
WER (%)
23.478
CER (%)
15.367

Plots

Scores per rowHow do overlap scores spread across rows, metric by metric (and system by system)?

Row-level BLEU uses the effective order and exponential smoothing; corpus BLEU is not their mean.

View data
MetricScore (0–100)System
BLEU100system_a
BLEU71.894system_a
BLEU59.695system_a
BLEU52.474system_a
BLEU70.711system_a
BLEU68.037system_a
BLEU53.077system_a
BLEU61.020system_a
BLEU73.111system_a
BLEU100system_a
BLEU69.144system_a
BLEU33.913system_a
BLEU100system_a
BLEU15.881system_a
BLEU35.495system_a
BLEU51.311system_a
BLEU58.143system_a
BLEU65.804system_a
BLEU100system_a
BLEU34.192system_a
BLEU48.110system_a
BLEU100system_a
BLEU100system_a
BLEU84.090system_a
BLEU100system_a
BLEU35.084system_a
BLEU100system_a
BLEU61.020system_a
BLEU52.474system_a
BLEU79.527system_a
chrF100system_a
chrF85.516system_a
chrF80.294system_a
chrF74.648system_a
chrF80.006system_a
chrF91.414system_a
chrF70.693system_a
chrF89.889system_a
chrF83.741system_a
chrF100system_a
chrF78.501system_a
chrF67.629system_a
chrF100system_a
chrF54.242system_a
chrF67.280system_a
chrF75.106system_a
chrF75.818system_a
chrF77.961system_a
chrF100system_a
chrF70.190system_a
chrF88.069system_a
chrF100system_a
chrF100system_a
chrF86.455system_a
chrF100system_a
chrF60.563system_a
chrF100system_a
chrF72.993system_a
chrF69.859system_a
chrF85.124system_a

First 60 of 300 rows.

Corpus scores with 95% bootstrap intervalsWhich system scores higher on each metric, and is the gap larger than the resampling noise?
View data
ScoreUpperLowerMetricSystem
68.78076.93061.650BLEUsystem_a
82.89687.80078.599chrFsystem_a
90.32393.34187.562ROUGE-1system_a
74.15581.24668.267ROUGE-2system_a
85.56689.65681.928ROUGE-Lsystem_a
3.5284.6481.892BLEUsystem_b
30.73734.69627.366chrFsystem_b
35.67342.15629.616ROUGE-1system_b
11.44015.6187.736ROUGE-2system_b
32.96739.01427.797ROUGE-Lsystem_b
Error rates per rowHow do overlap scores spread across rows, metric by metric (and system by system)?

Edits needed to turn each output into its closest reference, per reference word (WER) or character (CER); lower is better and it can exceed 100%.

View data
MetricError rate (%)System
WER0system_a
CER0system_a
WER12.500system_a
CER7.692system_a
WER28.571system_a
CER14.286system_a
WER25system_a
CER13.636system_a
WER11.111system_a
CER7.143system_a
WER14.286system_a
CER8.889system_a
WER25system_a
CER21.739system_a
WER12.500system_a
CER7.843system_a
WER14.286system_a
CER4.762system_a
WER0system_a
CER0system_a
WER14.286system_a
CER14.894system_a
WER42.857system_a
CER25system_a
WER0system_a
CER0system_a
WER55.556system_a
CER45.652system_a
WER33.333system_a
CER18.367system_a
WER37.500system_a
CER34.091system_a
WER14.286system_a
CER13.333system_a
WER11.111system_a
CER11.111system_a
WER0system_a
CER0system_a
WER62.500system_a
CER41.667system_a
WER71.429system_a
CER59.524system_a
WER0system_a
CER0system_a
WER0system_a
CER0system_a
WER25system_a
CER12.500system_a
WER0system_a
CER0system_a
WER62.500system_a
CER34.884system_a
WER33.333system_a
CER2.703system_a
WER37.500system_a
CER26.316system_a
WER25system_a
CER19.512system_a
WER28.571system_a
CER13.043system_a

First 60 of 120 rows.

Assumptions

  • Good references — 2 reference column(s); rows have 1–2 usable references. More references make overlap scores fairer to correct rewordings.
  • Same rows for every system — Every system is scored on the same rows, so the comparison is paired.
  • Wording, not meaning — Overlap metrics miss meaning, facts and safety; review a sample by hand or with LLM-as-judge.

Corpus scores by system

SystemBLEUchrFROUGE-1ROUGE-2ROUGE-Lp (BLEU vs first)
system_a68.78082.89690.32374.15585.566—
system_b3.52830.73735.67311.44032.967.003

Word and character error rates by system

SystemWER (%)CER (%)SubstitutionsDeletionsInsertionsReference wordsp (WER vs first)
system_a23.47815.367271512230—
system_b81.25060.812801002224.003
  • 2 rows have a missing output or no reference and are left out.
The exact R script · R R version 4.5.1 (2025-06-13)
# Generated-text metrics (BLEU, chrF, ROUGE)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method evaluate.text 1.1.1 · spec ab60482aa541a57b
# Dataset: ml_gentext (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr)

# %% Rows: every candidate present and at least one non-empty reference
CANDIDATES <- c("system_a", "system_b")
REFERENCES <- c("ref1", "ref2")
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ml_gentext.parquet", col_select = unique(c(CANDIDATES, REFERENCES))))
warnings <- list()
has_cand <- Reduce(`&`, lapply(CANDIDATES, function(c) !is.na(df[[c]])))
ref_lists <- lapply(seq_len(nrow(df)), function(i) {
  v <- vapply(REFERENCES, function(c) as.character(df[[c]][i]), "")
  unname(v[!is.na(v) & nzchar(v)])
})
has_ref <- lengths(ref_lists) > 0
rows <- which(has_cand & has_ref)
n_dropped <- nrow(df) - length(rows)
if (n_dropped) warnings <- c(warnings, sprintf("%d rows have a missing output or no reference and are left out.", n_dropped))
if (!length(rows)) cs_error("CS_E_NO_ROWS")  # no row has every output and at least one reference
refs <- ref_lists[rows]

# %% Segment statistics per system (sacreBLEU-compatible BLEU and chrF, rouge-score ROUGE)
TOKENIZE <- "13a"
LOWER <- FALSE
WORD_ORDER <- as.integer("0")
segs <- lapply(CANDIDATES, function(c) cs_tm_segments(as.character(df[[c]][rows]), refs, tokenize = TOKENIZE, lowercase = LOWER, word_order = WORD_ORDER))
scores <- lapply(segs, cs_tm_corpus)
METRICS <- c("bleu", "chrf", "rouge1", "rouge2", "rougeL")
ROUGE <- c("rouge1", "rouge2", "rougeL")

# %% Paired bootstrap over rows (shared Wichmann-Hill stream)
B <- 300
CONF <- 0.95
reps <- if (B > 0) cs_tm_bootstrap(segs, B, 42) else NULL

# %% Word and character error rates (only with the option on; closest reference per row, same resamples)
ERROR_RATES <- TRUE
esegs <- if (ERROR_RATES) lapply(CANDIDATES, function(c) cs_tm_error_segments(as.character(df[[c]][rows]), refs, lowercase = LOWER)) else NULL
ereps <- if (ERROR_RATES && B > 0) cs_tm_error_bootstrap(esegs, B, 42) else NULL

# %% Artifacts: one row per input row and system
out <- cs_ml_out_dir("target/academy-parity/run-8142/evaluate.text/wer_cer_two_systems/out-r")
per_row <- do.call(rbind, lapply(seq_along(CANDIDATES), function(s) {
  seg <- segs[[s]]
  data.frame(row = as.integer(rows - 1L), system = CANDIDATES[s], bleu = seg$sent_bleu, chrf = seg$sent_chrf,
             rouge1 = seg$rouge[, 3], rouge2 = seg$rouge[, 6], rougeL = seg$rouge[, 9])
}))
if (ERROR_RATES) {
  per_row$wer <- unlist(lapply(esegs, function(e) ifelse(e[, 2] > 0, 100 * e[, 1] / e[, 2], NA_real_)))
  per_row$cer <- unlist(lapply(esegs, function(e) ifelse(e[, 7] > 0, 100 * e[, 6] / e[, 7], NA_real_)))
}
nanoparquet::write_parquet(per_row, file.path(out, "scores.parquet"))

# %% Result
LABELS <- c(bleu = "BLEU", chrf = if (WORD_ORDER) "chrF++" else "chrF", rouge1 = "ROUGE-1", rouge2 = "ROUGE-2", rougeL = "ROUGE-L")
first <- segs[[1]]
b0 <- cs_tm_bleu_score(colSums(first$bleu_stats))
values <- list(n = length(rows), n_dropped = n_dropped, n_systems = length(CANDIDATES), n_refs = length(REFERENCES),
               bleu = b0$score, bleu_bp = b0$bp, bleu_ratio = b0$ratio,
               bleu_p1 = b0$p1, bleu_p2 = b0$p2, bleu_p3 = b0$p3, bleu_p4 = b0$p4,
               hyp_len = b0$hyp_len, ref_len = b0$ref_len, chrf = scores[[1]]$chrf,
               sent_bleu_mean = mean(first$sent_bleu), sent_chrf_mean = mean(first$sent_chrf),
               tokenize = TOKENIZE, chrf_label = unname(LABELS["chrf"]))
for (j in seq_along(ROUGE)) {
  k <- ROUGE[j]
  values[[k]] <- scores[[1]][[k]]
  values[[paste0(k, "_p")]] <- 100 * mean(first$rouge[, 3 * j - 2])
  values[[paste0(k, "_r")]] <- 100 * mean(first$rouge[, 3 * j - 1])
}
ci_rows <- list()
for (s in seq_along(CANDIDATES)) {
  c <- CANDIDATES[s]
  values[[sprintf("system[%d]", s)]] <- c
  for (m in seq_along(METRICS)) {
    k <- METRICS[m]
    values[[sprintf("%s[%s]", k, c)]] <- scores[[s]][[k]]
    lo <- NULL; hi <- NULL
    if (!is.null(reps)) {
      ci <- cs_tm_percentile_ci(reps[s, , m], CONF)
      lo <- ci[1]; hi <- ci[2]
      if (s == 1) { values[[paste0(k, "_ci_low")]] <- lo; values[[paste0(k, "_ci_high")]] <- hi }
      if (s > 1) {
        d <- scores[[s]][[k]] - scores[[1]][[k]]
        values[[sprintf("diff_%s[%s]", k, c)]] <- d
        values[[sprintf("p_%s[%s]", k, c)]] <- cs_tm_paired_p(d, reps[s, , m] - reps[1, , m])
      }
    } else if (s > 1) {
      values[[sprintf("diff_%s[%s]", k, c)]] <- scores[[s]][[k]] - scores[[1]][[k]]
    }
    ci_rows[[length(ci_rows) + 1]] <- list(system = c, metric = unname(LABELS[k]), estimate = scores[[s]][[k]], low = lo, high = hi)
  }
}
if (is.null(reps)) for (k in METRICS) { values[paste0(k, "_ci_low")] <- list(NULL); values[paste0(k, "_ci_high")] <- list(NULL) }

assumptions <- list(
  list(key = "references", label = "Good references", status = "info",
       detail = sprintf("%d reference column(s); rows have %d–%d usable references. More references make overlap scores fairer to correct rewordings.",
                        length(REFERENCES), min(lengths(refs)), max(lengths(refs)))),
  list(key = "same_rows", label = "Same rows for every system", status = if (length(CANDIDATES) > 1) "pass" else "info",
       detail = if (length(CANDIDATES) > 1) "Every system is scored on the same rows, so the comparison is paired." else "One system: nothing to pair."),
  list(key = "wording_not_meaning", label = "Wording, not meaning", status = "info",
       detail = "Overlap metrics miss meaning, facts and safety; review a sample by hand or with LLM-as-judge.")
)
if (is.finite(b0$ratio) && b0$ratio < 0.8) {
  warnings <- c(warnings, sprintf("%s is much shorter than the references (length ratio %.2f); BLEU's brevity penalty is %.3f.", CANDIDATES[1], b0$ratio, b0$bp))
}
table_rows <- lapply(seq_along(CANDIDATES), function(s) {
  row <- list(system = CANDIDATES[s])
  for (k in METRICS) row[[k]] <- scores[[s]][[k]]
  if (s > 1 && !is.null(reps)) row$p_bleu <- values[[sprintf("p_bleu[%s]", CANDIDATES[s])]]
  row
})
cols <- c(list(list(key = "system", label = "System")), lapply(METRICS, function(k) list(key = k, label = unname(LABELS[k]), type = "number")))
if (length(CANDIDATES) > 1 && !is.null(reps)) cols[[length(cols) + 1]] <- list(key = "p_bleu", label = "p (BLEU vs first)", type = "pvalue")
metric_col <- character(0); score_col <- numeric(0); system_col <- character(0)
for (s in seq_along(CANDIDATES)) {
  seg <- segs[[s]]
  parts <- list(bleu = seg$sent_bleu, chrf = seg$sent_chrf, rouge1 = 100 * seg$rouge[, 3], rouge2 = 100 * seg$rouge[, 6], rougeL = 100 * seg$rouge[, 9])
  for (k in METRICS) {
    metric_col <- c(metric_col, rep(unname(LABELS[k]), length(parts[[k]])))
    score_col <- c(score_col, parts[[k]])
    system_col <- c(system_col, rep(CANDIDATES[s], length(parts[[k]])))
  }
}
metric_levels <- unname(LABELS[METRICS])
seg_roles <- list(metric = cs_col("Metric", metric_col, "categorical", metric_levels), score = cs_col("Score (0–100)", score_col, "numeric"))
if (length(CANDIDATES) > 1) seg_roles$system <- cs_col("System", system_col, "categorical", CANDIDATES)
charts <- list(cs_chart("segments", "text-metric-scores", "Scores per row", seg_roles,
                        note = "Row-level BLEU uses the effective order and exponential smoothing; corpus BLEU is not their mean."))
if (!is.null(reps)) {
  ci_roles <- list(
    metric = cs_col("Metric", vapply(ci_rows, `[[`, "", "metric"), "categorical", metric_levels),
    estimate = cs_col("Score", vapply(ci_rows, `[[`, 0, "estimate"), "numeric"),
    low = cs_col("Lower", vapply(ci_rows, `[[`, 0, "low"), "numeric"),
    high = cs_col("Upper", vapply(ci_rows, `[[`, 0, "high"), "numeric"))
  if (length(CANDIDATES) > 1) ci_roles$system <- cs_col("System", vapply(ci_rows, `[[`, "", "system"), "categorical", CANDIDATES)
  charts[[2]] <- cs_chart("corpus", "text-metric-ci", sprintf("Corpus scores with %s bootstrap intervals", paste0(round(CONF * 100), "%")), ci_roles)
}
extra_stats <- list(); extra_tables <- list(); summary_extra <- ""
if (ERROR_RATES) {
  e0 <- colSums(esegs[[1]])
  values$wer <- cs_tm_error_rate(e0[1], e0[2]); values$cer <- cs_tm_error_rate(e0[6], e0[7])
  if (is.null(values$wer)) values["wer"] <- list(NULL)
  if (is.null(values$cer)) values["cer"] <- list(NULL)
  values$wer_sub <- as.integer(e0[3]); values$wer_del <- as.integer(e0[4]); values$wer_ins <- as.integer(e0[5])
  values$wer_ref_words <- as.integer(e0[2]); values$cer_ref_chars <- as.integer(e0[7])
  er_rows <- list()
  rates <- list()
  for (s in seq_along(CANDIDATES)) {
    c <- CANDIDATES[s]
    t <- colSums(esegs[[s]])
    row <- list(system = c, wer = cs_tm_error_rate(t[1], t[2]), cer = cs_tm_error_rate(t[6], t[7]), sub = as.integer(t[3]),
                del = as.integer(t[4]), ins = as.integer(t[5]), words = as.integer(t[2]))
    rates[[s]] <- list(wer = row$wer, cer = row$cer)
    for (m in 1:2) {
      k <- c("wer", "cer")[m]
      est <- rates[[s]][[k]]; base <- rates[[1]][[k]]
      values[sprintf("%s[%s]", k, c)] <- list(est)
      d <- if (s > 1 && !is.null(est) && !is.null(base)) est - base else NULL
      if (s > 1) values[sprintf("diff_%s[%s]", k, c)] <- list(d)
      if (!is.null(ereps)) {
        col <- ereps[s, , m]
        if (s == 1) {
          ci <- if (!anyNA(col)) cs_tm_percentile_ci(col, CONF) else NULL
          values[paste0(k, "_ci_low")] <- list(if (is.null(ci)) NULL else ci[1])
          values[paste0(k, "_ci_high")] <- list(if (is.null(ci)) NULL else ci[2])
        } else {
          dif <- col - ereps[1, , m]
          values[sprintf("p_%s[%s]", k, c)] <- list(if (!is.null(d) && !anyNA(dif)) cs_tm_paired_p(d, dif) else NULL)
        }
      }
    }
    if (s > 1 && !is.null(ereps)) row$p_wer <- values[[sprintf("p_wer[%s]", c)]]
    er_rows[[s]] <- row
  }
  if (is.null(ereps)) for (k in c("wer", "cer")) { values[paste0(k, "_ci_low")] <- list(NULL); values[paste0(k, "_ci_high")] <- list(NULL) }
  er_cols <- list(list(key = "system", label = "System"), list(key = "wer", label = "WER (%)", type = "number"), list(key = "cer", label = "CER (%)", type = "number"),
                  list(key = "sub", label = "Substitutions", type = "number"), list(key = "del", label = "Deletions", type = "number"),
                  list(key = "ins", label = "Insertions", type = "number"), list(key = "words", label = "Reference words", type = "number"))
  if (length(CANDIDATES) > 1 && !is.null(ereps)) er_cols[[length(er_cols) + 1]] <- list(key = "p_wer", label = "p (WER vs first)", type = "pvalue")
  extra_tables <- list(list(key = "error_rates", title = "Word and character error rates by system", columns = er_cols, rows = er_rows))
  extra_stats <- list(list(key = "wer", label = "WER (%)", value = values$wer), list(key = "cer", label = "CER (%)", value = values$cer))
  if (!is.null(values$wer) && !is.null(values$cer)) summary_extra <- sprintf(" WER %.1f%%, CER %.1f%%.", values$wer, values$cer)
  em_col <- character(0); es_col <- numeric(0); esys_col <- character(0)
  for (s in seq_along(CANDIDATES)) {
    e <- esegs[[s]]
    for (i in seq_len(nrow(e))) {
      if (e[i, 2] > 0) { em_col <- c(em_col, "WER"); es_col <- c(es_col, 100 * e[i, 1] / e[i, 2]); esys_col <- c(esys_col, CANDIDATES[s]) }
      if (e[i, 7] > 0) { em_col <- c(em_col, "CER"); es_col <- c(es_col, 100 * e[i, 6] / e[i, 7]); esys_col <- c(esys_col, CANDIDATES[s]) }
    }
  }
  er_roles <- list(metric = cs_col("Metric", em_col, "categorical", c("WER", "CER")), score = cs_col("Error rate (%)", es_col, "numeric"))
  if (length(CANDIDATES) > 1) er_roles$system <- cs_col("System", esys_col, "categorical", CANDIDATES)
  charts[[length(charts) + 1]] <- cs_chart("error_rates", "text-metric-scores", "Error rates per row", er_roles,
    note = "Edits needed to turn each output into its closest reference, per reference word (WER) or character (CER); lower is better and it can exceed 100%.")
}
cs_publish(list(
  title = "Generated-text metrics (BLEU, chrF, ROUGE)",
  engine = cs_engine_info("codesplashr", "nanoparquet"),
  n = length(rows),
  summary = paste0(sprintf("%s: BLEU %.1f, %s %.1f, ROUGE-L F1 %.1f on %d rows.", CANDIDATES[1], values$bleu, LABELS[["chrf"]], values$chrf, values$rougeL, length(rows)), summary_extra),
  statistics = list(
    list(key = "bleu", label = "BLEU", value = values$bleu),
    list(key = "chrf", label = unname(LABELS["chrf"]), value = values$chrf),
    list(key = "rouge1", label = "ROUGE-1 F1", value = values$rouge1),
    list(key = "rouge2", label = "ROUGE-2 F1", value = values$rouge2),
    list(key = "rougeL", label = "ROUGE-L F1", value = values$rougeL),
    list(key = "bleu_bp", label = "Brevity penalty", value = values$bleu_bp)
  ) |> c(extra_stats),
  tables = c(list(list(key = "systems", title = "Corpus scores by system", columns = cols, rows = table_rows)), extra_tables),
  assumptions = assumptions,
  charts = charts,
  values = values,
  warnings = warnings,
  artifacts = list(list(key = "scores", path = file.path(out, "scores.parquet"), format = "parquet"))
))
Python

system_a: BLEU 68.8, chrF 82.9, ROUGE-L F1 85.6 on 30 rows. WER 23.5%, CER 15.4%.

BLEU
68.780
chrF
82.896
ROUGE-1 F1
90.323
ROUGE-2 F1
74.155
ROUGE-L F1
85.566
Brevity penalty
0.9770
WER (%)
23.478
CER (%)
15.367

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

Assumptions

  • Good references — 2 reference column(s); rows have 1–2 usable references. More references make overlap scores fairer to correct rewordings.
  • Same rows for every system — Every system is scored on the same rows, so the comparison is paired.
  • Wording, not meaning — Overlap metrics miss meaning, facts and safety; review a sample by hand or with LLM-as-judge.

Corpus scores by system

SystemBLEUchrFROUGE-1ROUGE-2ROUGE-Lp (BLEU vs first)
system_a68.78082.89690.32374.15585.566—
system_b3.52830.73735.67311.44032.967.003

Word and character error rates by system

SystemWER (%)CER (%)SubstitutionsDeletionsInsertionsReference wordsp (WER vs first)
system_a23.47815.367271512230—
system_b81.25060.812801002224.003
  • 2 rows have a missing output or no reference and are left out.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Generated-text metrics (BLEU, chrF, ROUGE)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method evaluate.text 1.1.1 · spec ab60482aa541a57b
# Dataset: ml_gentext (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 import ml as csml
from codesplash.text import error_rates as er
from codesplash.text import metrics as tm

# %% Rows: every candidate present and at least one non-empty reference
CANDIDATES = ["system_a", "system_b"]
REFERENCES = ["ref1", "ref2"]
df = pd.read_parquet("tests/parity/fixtures/ml_gentext.parquet", columns=list(dict.fromkeys(CANDIDATES + REFERENCES)))
warnings = []
has_cand = df[CANDIDATES].notna().all(axis=1).to_numpy()
ref_lists = [[str(v) for v in row if not pd.isna(v) and str(v) != ""] for row in df[REFERENCES].itertuples(index=False)]  # None, NaN, pd.NA: none
has_ref = np.array([len(r) > 0 for r in ref_lists])
rows = np.flatnonzero(has_cand & has_ref)
n_dropped = len(df) - len(rows)
if n_dropped:
    warnings.append(f"{n_dropped} rows have a missing output or no reference and are left out.")
if not len(rows):
    cs.cs_error("CS_E_NO_ROWS")  # no row has every output and at least one reference
refs = [ref_lists[i] for i in rows]

# %% Segment statistics per system (sacreBLEU-compatible BLEU and chrF, rouge-score ROUGE)
TOKENIZE = "13a"
LOWER = False
WORD_ORDER = int("0")
segs = [tm.segments([str(v) for v in df[c].iloc[rows]], refs, tokenize=TOKENIZE, lowercase=LOWER, word_order=WORD_ORDER) for c in CANDIDATES]
scores = [tm.corpus_scores(s) for s in segs]

# %% Paired bootstrap over rows (shared Wichmann–Hill stream)
B = 300
CONF = 0.95
reps = tm.bootstrap(segs, B, 42) if B > 0 else None

# %% Word and character error rates (only with the option on; closest reference per row, same resamples)
ERROR_RATES = True
esegs = [er.segments([str(v) for v in df[c].iloc[rows]], refs, lowercase=LOWER) for c in CANDIDATES] if ERROR_RATES else None
ereps = er.bootstrap(esegs, B, 42) if ERROR_RATES and B > 0 else None

# %% Artifacts: one row per input row and system
out = csml.out_dir("target/academy-parity/run-8142/evaluate.text/wer_cer_two_systems/out-python")
per_row = []
for s, c in enumerate(CANDIDATES):
    seg = segs[s]
    for i, r in enumerate(rows):
        per_row.append({"row": int(r), "system": c, "bleu": float(seg["sent_bleu"][i]), "chrf": float(seg["sent_chrf"][i]),
                        "rouge1": float(seg["rouge"][i, 2]), "rouge2": float(seg["rouge"][i, 5]), "rougeL": float(seg["rouge"][i, 8])})
        if ERROR_RATES:
            e = esegs[s][i]
            per_row[-1].update({"wer": er.rate(e[0], e[1]), "cer": er.rate(e[5], e[6])})
pd.DataFrame(per_row).to_parquet(os.path.join(out, "scores.parquet"), index=False)

# %% Result
LABELS = {"bleu": "BLEU", "chrf": "chrF++" if WORD_ORDER else "chrF", "rouge1": "ROUGE-1", "rouge2": "ROUGE-2", "rougeL": "ROUGE-L"}
first = segs[0]
b0 = tm.bleu_score(first["bleu_stats"].sum(axis=0))
values = {
    "n": len(rows), "n_dropped": n_dropped, "n_systems": len(CANDIDATES), "n_refs": len(REFERENCES),
    "bleu": b0["score"], "bleu_bp": b0["bp"], "bleu_ratio": b0["ratio"],
    "bleu_p1": b0["p1"], "bleu_p2": b0["p2"], "bleu_p3": b0["p3"], "bleu_p4": b0["p4"],
    "hyp_len": b0["hyp_len"], "ref_len": b0["ref_len"], "chrf": scores[0]["chrf"],
    "sent_bleu_mean": float(first["sent_bleu"].mean()), "sent_chrf_mean": float(first["sent_chrf"].mean()),
    "tokenize": TOKENIZE, "chrf_label": LABELS["chrf"],
}
for j, k in enumerate(tm.ROUGE):
    values[k] = scores[0][k]
    values[f"{k}_p"] = 100.0 * float(first["rouge"][:, 3 * j].mean())
    values[f"{k}_r"] = 100.0 * float(first["rouge"][:, 3 * j + 1].mean())
ci_rows = []
for s, c in enumerate(CANDIDATES):
    values[f"system[{s + 1}]"] = c
    for m, k in enumerate(tm.METRICS):
        values[f"{k}[{c}]"] = scores[s][k]
        lo = hi = None
        if reps is not None:
            lo, hi = tm.percentile_ci(reps[s, :, m], CONF)
            if s == 0:
                values[f"{k}_ci_low"], values[f"{k}_ci_high"] = lo, hi
            if s > 0:
                d = scores[s][k] - scores[0][k]
                values[f"diff_{k}[{c}]"] = d
                values[f"p_{k}[{c}]"] = tm.paired_p(d, reps[s, :, m] - reps[0, :, m])
        elif s > 0:
            values[f"diff_{k}[{c}]"] = scores[s][k] - scores[0][k]
        ci_rows.append({"system": c, "metric": LABELS[k], "estimate": scores[s][k], "low": lo, "high": hi})
if reps is None:
    for k in tm.METRICS:
        values[f"{k}_ci_low"] = values[f"{k}_ci_high"] = None

assumptions = [
    {"key": "references", "label": "Good references", "status": "info",
     "detail": f"{len(REFERENCES)} reference column(s); rows have {min(len(r) for r in refs)}–{max(len(r) for r in refs)} usable references. More references make overlap scores fairer to correct rewordings."},
    {"key": "same_rows", "label": "Same rows for every system", "status": "pass" if len(CANDIDATES) > 1 else "info",
     "detail": "Every system is scored on the same rows, so the comparison is paired." if len(CANDIDATES) > 1 else "One system: nothing to pair."},
    {"key": "wording_not_meaning", "label": "Wording, not meaning", "status": "info",
     "detail": "Overlap metrics miss meaning, facts and safety; review a sample by hand or with LLM-as-judge."},
]
if b0["ratio"] == b0["ratio"] and b0["ratio"] < 0.8:
    warnings.append(f"{CANDIDATES[0]} is much shorter than the references (length ratio {b0['ratio']:.2f}); BLEU's brevity penalty is {b0['bp']:.3f}.")
table_rows = []
for s, c in enumerate(CANDIDATES):
    row = {"system": c}
    for k in tm.METRICS:
        row[k] = scores[s][k]
    if s > 0 and reps is not None:
        row["p_bleu"] = values[f"p_bleu[{c}]"]
    table_rows.append(row)
cols = [{"key": "system", "label": "System"}] + [{"key": k, "label": LABELS[k], "type": "number"} for k in tm.METRICS]
if len(CANDIDATES) > 1 and reps is not None:
    cols.append({"key": "p_bleu", "label": "p (BLEU vs first)", "type": "pvalue"})
metric_col, score_col, system_col = [], [], []
for s, c in enumerate(CANDIDATES):
    seg = segs[s]
    for k, v in (("bleu", seg["sent_bleu"]), ("chrf", seg["sent_chrf"]), ("rouge1", 100 * seg["rouge"][:, 2]), ("rouge2", 100 * seg["rouge"][:, 5]), ("rougeL", 100 * seg["rouge"][:, 8])):
        metric_col += [LABELS[k]] * len(v)
        score_col += [float(x) for x in v]
        system_col += [c] * len(v)
metric_levels = [LABELS[k] for k in tm.METRICS]
charts = [cs.chart("segments", "text-metric-scores", "Scores per row", {
    "metric": cs.col("Metric", metric_col, "categorical", metric_levels),
    "score": cs.col("Score (0–100)", score_col, "numeric"),
    **({"system": cs.col("System", system_col, "categorical", list(CANDIDATES))} if len(CANDIDATES) > 1 else {}),
}, note="Row-level BLEU uses the effective order and exponential smoothing; corpus BLEU is not their mean.")]
if reps is not None:
    charts.append(cs.chart("corpus", "text-metric-ci", f"Corpus scores with {CONF:.0%} bootstrap intervals", {
        "metric": cs.col("Metric", [r["metric"] for r in ci_rows], "categorical", metric_levels),
        "estimate": cs.col("Score", [r["estimate"] for r in ci_rows], "numeric"),
        "low": cs.col("Lower", [r["low"] for r in ci_rows], "numeric"),
        "high": cs.col("Upper", [r["high"] for r in ci_rows], "numeric"),
        **({"system": cs.col("System", [r["system"] for r in ci_rows], "categorical", list(CANDIDATES))} if len(CANDIDATES) > 1 else {}),
    }))
extra_stats, extra_tables, summary_extra = [], [], ""
if ERROR_RATES:
    e0 = esegs[0].sum(axis=0)
    values.update({"wer": er.rate(e0[0], e0[1]), "cer": er.rate(e0[5], e0[6]), "wer_sub": int(e0[2]), "wer_del": int(e0[3]),
                   "wer_ins": int(e0[4]), "wer_ref_words": int(e0[1]), "cer_ref_chars": int(e0[6])})
    er_rows = []
    for s, c in enumerate(CANDIDATES):
        t = esegs[s].sum(axis=0)
        row = {"system": c, "wer": er.rate(t[0], t[1]), "cer": er.rate(t[5], t[6]), "sub": int(t[2]), "del": int(t[3]), "ins": int(t[4]), "words": int(t[1])}
        for m, k in enumerate(("wer", "cer")):
            values[f"{k}[{c}]"] = row[k]
            base = values[f"{k}[{CANDIDATES[0]}]"]
            d = row[k] - base if (s > 0 and row[k] is not None and base is not None) else None
            if s > 0:
                values[f"diff_{k}[{c}]"] = d
            if ereps is not None:
                col = ereps[s, :, m]
                if s == 0:
                    values[f"{k}_ci_low"], values[f"{k}_ci_high"] = tm.percentile_ci(col, CONF) if not np.isnan(col).any() else (None, None)
                else:
                    dif = col - ereps[0, :, m]
                    values[f"p_{k}[{c}]"] = tm.paired_p(d, dif) if d is not None and not np.isnan(dif).any() else None
        if s > 0 and ereps is not None:
            row["p_wer"] = values[f"p_wer[{c}]"]
        er_rows.append(row)
    if ereps is None:
        for k in ("wer", "cer"):
            values[f"{k}_ci_low"] = values[f"{k}_ci_high"] = None
    er_cols = [{"key": "system", "label": "System"}, {"key": "wer", "label": "WER (%)", "type": "number"}, {"key": "cer", "label": "CER (%)", "type": "number"},
               {"key": "sub", "label": "Substitutions", "type": "number"}, {"key": "del", "label": "Deletions", "type": "number"},
               {"key": "ins", "label": "Insertions", "type": "number"}, {"key": "words", "label": "Reference words", "type": "number"}]
    if len(CANDIDATES) > 1 and ereps is not None:
        er_cols.append({"key": "p_wer", "label": "p (WER vs first)", "type": "pvalue"})
    extra_tables.append({"key": "error_rates", "title": "Word and character error rates by system", "columns": er_cols, "rows": er_rows})
    extra_stats = [{"key": "wer", "label": "WER (%)", "value": values["wer"]}, {"key": "cer", "label": "CER (%)", "value": values["cer"]}]
    if values["wer"] is not None and values["cer"] is not None:
        summary_extra = f" WER {values['wer']:.1f}%, CER {values['cer']:.1f}%."
    em_col, es_col, esys_col = [], [], []
    for s, c in enumerate(CANDIDATES):
        for i in range(esegs[s].shape[0]):
            e = esegs[s][i]
            for lab, num, den in (("WER", e[0], e[1]), ("CER", e[5], e[6])):
                if den > 0:
                    em_col.append(lab)
                    es_col.append(100.0 * float(num) / float(den))
                    esys_col.append(c)
    charts.append(cs.chart("error_rates", "text-metric-scores", "Error rates per row", {
        "metric": cs.col("Metric", em_col, "categorical", ["WER", "CER"]),
        "score": cs.col("Error rate (%)", es_col, "numeric"),
        **({"system": cs.col("System", esys_col, "categorical", list(CANDIDATES))} if len(CANDIDATES) > 1 else {}),
    }, note="Edits needed to turn each output into its closest reference, per reference word (WER) or character (CER); lower is better and it can exceed 100%."))
cs.publish({
    "title": "Generated-text metrics (BLEU, chrF, ROUGE)",
    "engine": cs.engine_info("numpy", "pandas"),
    "n": len(rows),
    "summary": f"{CANDIDATES[0]}: BLEU {values['bleu']:.1f}, {LABELS['chrf']} {values['chrf']:.1f}, ROUGE-L F1 {values['rougeL']:.1f} on {len(rows)} rows." + summary_extra,
    "statistics": [
        {"key": "bleu", "label": "BLEU", "value": values["bleu"]},
        {"key": "chrf", "label": LABELS["chrf"], "value": values["chrf"]},
        {"key": "rouge1", "label": "ROUGE-1 F1", "value": values["rouge1"]},
        {"key": "rouge2", "label": "ROUGE-2 F1", "value": values["rouge2"]},
        {"key": "rougeL", "label": "ROUGE-L F1", "value": values["rougeL"]},
        {"key": "bleu_bp", "label": "Brevity penalty", "value": values["bleu_bp"]},
    ] + extra_stats,
    "tables": [{"key": "systems", "title": "Corpus scores by system", "columns": cols, "rows": table_rows}] + extra_tables,
    "assumptions": assumptions,
    "charts": charts,
    "values": values,
    "warnings": warnings,
    "artifacts": [{"key": "scores", "path": os.path.join(out, "scores.parquet"), "format": "parquet"}],
})

With Word and character error rates on, system A's WER is 23.5% and system B's 81.3%. For system A, the edits split into 27 substitutions, 15 deletions and 12 insertions over 230 reference words.

The split tells you how a system fails: deletions mean dropped content, insertions invented content. Casing and punctuation change WER too, so state the normalization (Ignore case here was off).

03

One error, big or small?

Predict

Predict first

A transcript drops one word, "not", from "the test was not positive" in a 200-word report. What does WER do?

It counts as one substitution among many, so WER barely movesWER rises sharply because the meaning flippedWER ignores it
Reveal

It counts one deletion, half a percent of 200 words, though the meaning reversed. WER weighs every word the same; check the words that matter for your use separately.

04

The same idea for signals: SI-SDR

Read

When the output is a waveform, such as one voice separated from a mix, the reference is the true source. SI-SDRSI-SDR (scale-invariant signal-to-distortion ratio)How close a separated signal is to the true source in dB, ignoring its overall volume; higher is better, 0 dB means as much error as signal. first scales the reference to best match the estimate, so loudness doesn't count, then compares that target with what is left:

st=⟨s^,s⟩∥s∥2 s,SI-SDR=10log⁡10∥st∥2∥s^−st∥2s_t = \frac{\langle \hat s, s\rangle}{\lVert s\rVert^2}\, s, \qquad \mathrm{SI\text{-}SDR} = 10\log_{10}\frac{\lVert s_t\rVert^2}{\lVert \hat s - s_t\rVert^2}

The reference program's estimate is close to its source: 21.5 dB. Zero dB means as much error as signal.

DExplorable · Scoring separated sources: SI-SDR and permutation-invariant matching

How do you score a separator that returns the right voices in the wrong order?

2

A tone and a buzzy wave, plus a noise burst when there are three.

Output order

Separators don't know which output is which voice: here the outputs can come back rotated.

0.15

Share of the whole mix left in each output: the other sources bleeding through.

1.0

Scales every output. SI-SDR ignores the volume; SNR does not.

0.05

White noise the separator adds to each output.

Scoring

Match outputs to sources by trying every assignment (PIT), or score output k against source k.

SourcesOutputs, in the order returned1216.3−22.9−20.218.5Source 1Source 2Output 1Output 217.4 dBSI-SDR, best assignment−21.6 dBSI-SDR, fixed order16.6 dBSNR as scored

Bars below zero are drawn flat; read their numbers. SI-SDR first rescales the source to fit the output, so the output's volume can't change it.

Mean SI-SDR as scored (dB)
17.40
Mean SI-SDR, best assignment (dB)
17.40
Mean SI-SDR, fixed order (dB)
−21.57
Mean SNR as scored (dB)
16.62
SI-SDR improvement over the mix (dB)
17.40
  • Puzzle: With the best assignment, find settings where SNR and SI-SDR disagree by more than 6 dB.
PIT matches source 1 → output 2, source 2 → output 1: mean SI-SDR 17.4 dB (SNR 16.6 dB); against the raw mix that is a change of 17.4 dB. Best assignment 17.4 dB against fixed order −21.6 dB.

PIT matches source 1 → output 2, source 2 → output 1: mean SI-SDR 17.4 dB (SNR 16.6 dB); against the raw mix that is a change of 17.4 dB. Best assignment 17.4 dB against fixed order −21.6 dB.

05

Separation in CodeSplash

Read
Source separation metrics (SI-SDR, SDR, SIR, SAR)Recorded · Python and R agreeRecorded 2026-11-25 · 32 values compared
R

Mean SI-SDR 8.1 dB over 2 clip(s) and 3 source(s).

Mean SI-SDR (dB)
8.081
Mean SI-SDRi (dB)
11.413
Mean SDR (dB)
9.581
Mean SIR (dB)
10.972
Mean SAR (dB)
15.629
Mean SNR (dB)
8.620

Plots

SI-SDR by source: mixture and separatedHow do categories compare on one value — and across up to three groups?

Mean over clips. The gap between the dots is SI-SDRi, the gain over the unseparated mixture.

View data
True sourceSignalSI-SDR (dB)
s1Mixture0.2224
s1Separated11.103
s2Mixture−5.643
s2Separated6.031
s3Mixture−4.643
s3Separated6.833
s1Mixture1.127
s1Separated11.966
s2Mixture−6.423
s2Separated5.388
s3Mixture−4.630
s3Separated7.167
BSS Eval by sourceHow do categories compare on one value — and across up to three groups?

SDR counts every error; SIR only leakage from the other sources; SAR only artifacts the separation added.

View data
True sourceMetricdB
s1SDR12.628
s1SIR14.130
s1SAR18.132
s2SDR7.940
s2SIR9.386
s2SAR13.894
s3SDR8.236
s3SIR9.613
s3SAR14.344
s1SDR13.368
s1SIR15.032
s1SAR18.475
s2SDR6.653
s2SIR7.731
s2SAR13.910
s3SDR8.662
s3SIR9.939
s3SAR15.019

Assumptions

  • Signals are aligned in time — Rows are read as samples in time order; a delay between a source and its estimate lowers SI-SDR.
  • No silent sources — Every true source varies in every clip.
  • One estimate per source — 3 separated signals for 3 true sources; matching reordered them in 1 of 2 clips.

Scores by clip and source

ClipTrue sourceMatched estimateSI-SDR (dB)SI-SDRi (dB)Mixture SI-SDR (dB)SDR (dB)SIR (dB)SAR (dB)SNR (dB)
as1est111.10310.8810.222412.62814.13018.13211.124
as2est26.03111.674−5.6437.9409.38613.8946.997
as3est36.83311.477−4.6438.2369.61314.3447.580
bs1est311.96610.8401.12713.36815.03218.47511.685
bs2est15.38811.810−6.4236.6537.73113.9106.477
bs3est27.16711.796−4.6308.6629.93915.0197.856
The exact R script · R R version 4.5.1 (2025-06-13)
# Source separation metrics (SI-SDR, SDR, SIR, SAR)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method evaluate.separation 1.0.1 · spec 56f2d5c067a8ae81
# Dataset: aud1_separation (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr)

# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/aud1_separation.parquet", col_select = c("s1", "s2", "s3", "est1", "est2", "est3", "mix", "clip")))
n_input <- nrow(df)
df[["clip"]] <- factor(df[["clip"]], levels = sort(unique(df[["clip"]]), method = "radix"))
df <- df[stats::complete.cases(df[c("s1", "s2", "s3", "est1", "est2", "est3", "mix", "clip")]), , drop = FALSE]  # listwise deletion
df[] <- lapply(df, function(x) if (is.factor(x)) droplevels(x) else x)
n_dropped <- n_input - nrow(df)
warnings <- list()
if (n_dropped > 0) {
  warnings <- c(warnings, cs_warning("CS_W_ROWS_DROPPED", dropped = n_dropped, total = n_input))
}
if (n_input > 0 && nrow(df) == 0) cs_error("CS_E_NO_ROWS")
cs_check_finite_columns(df, c("s1", "s2", "s3", "est1", "est2", "est3", "mix", "clip"))  # infinite values stop the run (registry/errors.yaml)

# %% Signals: one column per true source and per separated signal, samples in row order
REFS <- c("s1", "s2", "s3")
ESTS <- c("est1", "est2", "est3")
MIX <- "mix"
CLIP <- "clip"
PERMUTE <- TRUE
ZERO_MEAN <- TRUE
BSS <- TRUE
FLEN <- 512
if (length(ESTS) != length(REFS)) {
  cs_error("CS_E_INVALID_OPTION", option = "Separated signals", allowed = paste0(length(REFS), " columns, one per true source"), value = length(ESTS))
}
clips <- if (is.null(CLIP)) list(`all rows` = df) else split(df, df[[CLIP]], drop = TRUE)

# %% Scores per clip: permutation-invariant matching on SI-SDR, then SI-SDRi and BSS Eval
rows <- list()
n_permuted <- 0L
for (name in names(clips)) {
  g <- clips[[name]]
  R <- t(as.matrix(g[REFS])); storage.mode(R) <- "double"
  E <- t(as.matrix(g[ESTS])); storage.mode(E) <- "double"
  for (i in seq_along(REFS)) {
    s <- if (ZERO_MEAN) R[i, ] - mean(R[i, ]) else R[i, ]
    if (sum(s * s) == 0) cs_error("CS_E_UNDEFINED", what = "SI-SDR", reason = paste0("the true source ", REFS[i], " is silent in clip ", name))
  }
  m <- if (!is.null(MIX)) as.numeric(g[[MIX]]) else NULL
  r <- cs_sep_evaluate(R, E, m, zero_mean = ZERO_MEAN, bss = BSS, flen = FLEN, permute = PERMUTE)
  if (any(r$perm != seq_along(REFS))) n_permuted <- n_permuted + 1L
  for (i in seq_along(REFS)) {
    rows[[length(rows) + 1]] <- list(
      clip = name, source = REFS[i], estimate = ESTS[r$perm[i]], samples = ncol(R),
      si_sdr = r$si_sdr[i],
      si_sdri = if (!is.null(m)) r$si_sdri[i] else NULL,
      mixture_si_sdr = if (!is.null(m)) r$mixture_si_sdr[i] else NULL,
      sdr = if (BSS) r$sdr[i] else NULL,
      sir = if (BSS) r$sir[i] else NULL,
      sar = if (BSS) r$sar[i] else NULL,
      snr = r$snr[i]
    )
  }
}

mean_of <- function(key, source = NULL) {
  v <- unlist(lapply(rows, function(x) if (!is.null(x[[key]]) && (is.null(source) || x$source == source)) x[[key]] else NULL))
  if (length(v)) mean(v) else NULL
}

si <- vapply(rows, function(x) x$si_sdr, 0)
values <- list(
  n_clips = length(clips), n_sources = length(REFS), n_samples = nrow(df),
  si_sdr_mean = mean_of("si_sdr"), si_sdr_median = stats::median(si), si_sdr_min = min(si),
  si_sdri_mean = mean_of("si_sdri"), mixture_si_sdr_mean = mean_of("mixture_si_sdr"),
  sdr_mean = mean_of("sdr"), sir_mean = mean_of("sir"), sar_mean = mean_of("sar"), snr_mean = mean_of("snr"),
  n_permuted = n_permuted, filter_length = if (BSS) FLEN else NULL
)
for (c in REFS) {
  for (key in c("si_sdr", "si_sdri", "sdr", "sir", "sar", "snr")) {
    v <- mean_of(key, c)
    if (!is.null(v)) values[[sprintf("%s[%s]", key, c)]] <- v
  }
}

# %% Artifact: one row per clip and source
out <- cs_ml_out_dir("target/academy-parity/run-8142/evaluate.separation/three_sources_mixture/out-r")
num_or_na <- function(key) vapply(rows, function(x) if (is.null(x[[key]])) NA_real_ else as.numeric(x[[key]]), 0)
art <- data.frame(
  clip = vapply(rows, function(x) x$clip, ""), source = vapply(rows, function(x) x$source, ""),
  estimate = vapply(rows, function(x) x$estimate, ""), samples = vapply(rows, function(x) as.integer(x$samples), 0L),
  si_sdr = num_or_na("si_sdr"), si_sdri = num_or_na("si_sdri"), mixture_si_sdr = num_or_na("mixture_si_sdr"),
  sdr = num_or_na("sdr"), sir = num_or_na("sir"), sar = num_or_na("sar"), snr = num_or_na("snr"),
  stringsAsFactors = FALSE
)
nanoparquet::write_parquet(art, file.path(out, "separation.parquet"))

# %% Result
cols <- list(list(key = "clip", label = "Clip"), list(key = "source", label = "True source"), list(key = "estimate", label = "Matched estimate"),
             list(key = "si_sdr", label = "SI-SDR (dB)", type = "number"))
if (!is.null(MIX)) cols <- c(cols, list(list(key = "si_sdri", label = "SI-SDRi (dB)", type = "number"), list(key = "mixture_si_sdr", label = "Mixture SI-SDR (dB)", type = "number")))
if (BSS) cols <- c(cols, list(list(key = "sdr", label = "SDR (dB)", type = "number"), list(key = "sir", label = "SIR (dB)", type = "number"), list(key = "sar", label = "SAR (dB)", type = "number")))
cols <- c(cols, list(list(key = "snr", label = "SNR (dB)", type = "number")))
keys <- vapply(cols, function(c) c$key, "")
table_rows <- lapply(rows[seq_len(min(500, length(rows)))], function(x) stats::setNames(lapply(keys, function(k) x[[k]]), keys))
tables <- list(list(key = "scores", title = "Scores by clip and source", columns = cols, rows = table_rows))
fin <- function(v) if (is.finite(v)) v else NA_real_
kind <- character(0); src <- character(0); val <- numeric(0)
for (x in rows) {
  if (!is.null(MIX)) { kind <- c(kind, "Mixture"); src <- c(src, x$source); val <- c(val, fin(x$mixture_si_sdr)) }
  kind <- c(kind, "Separated"); src <- c(src, x$source); val <- c(val, fin(x$si_sdr))
}
charts <- list(cs_chart("si_sdr", "cleveland-dot", paste0("SI-SDR by source", if (!is.null(MIX)) ": mixture and separated" else ""), list(
  category = cs_col("True source", src, "categorical", REFS),
  value = cs_col("SI-SDR (dB)", val, "numeric"),
  group = cs_col("Signal", kind, "categorical", if (!is.null(MIX)) c("Mixture", "Separated") else c("Separated"))
), note = if (!is.null(MIX)) "Mean over clips. The gap between the dots is SI-SDRi, the gain over the unseparated mixture." else "Mean over clips; higher is better."))
if (BSS) {
  metric <- character(0); msrc <- character(0); mval <- numeric(0)
  for (x in rows) {
    for (pair in list(c("sdr", "SDR"), c("sir", "SIR"), c("sar", "SAR"))) {
      metric <- c(metric, pair[2]); msrc <- c(msrc, x$source); mval <- c(mval, fin(x[[pair[1]]]))
    }
  }
  charts[[2]] <- cs_chart("bss_eval", "cleveland-dot", "BSS Eval by source", list(
    category = cs_col("True source", msrc, "categorical", REFS),
    value = cs_col("dB", mval, "numeric"),
    group = cs_col("Metric", metric, "categorical", c("SDR", "SIR", "SAR"))
  ), note = "SDR counts every error; SIR only leakage from the other sources; SAR only artifacts the separation added.")
}
assumptions <- list(
  list(key = "aligned", label = "Signals are aligned in time", status = "info",
       detail = "Rows are read as samples in time order; a delay between a source and its estimate lowers SI-SDR."),
  list(key = "silent_reference", label = "No silent sources", status = "pass", detail = "Every true source varies in every clip."),
  list(key = "same_count", label = "One estimate per source", status = "pass",
       detail = paste0(length(ESTS), " separated signals for ", length(REFS), " true sources",
                       if (PERMUTE) sprintf("; matching reordered them in %d of %d clips.", n_permuted, length(clips)) else ", paired in column order."))
)
stats_list <- list(list(key = "si_sdr_mean", label = "Mean SI-SDR (dB)", value = values$si_sdr_mean))
if (!is.null(MIX)) stats_list[[length(stats_list) + 1]] <- list(key = "si_sdri_mean", label = "Mean SI-SDRi (dB)", value = values$si_sdri_mean)
if (BSS) {
  stats_list <- c(stats_list, list(list(key = "sdr_mean", label = "Mean SDR (dB)", value = values$sdr_mean),
                                   list(key = "sir_mean", label = "Mean SIR (dB)", value = values$sir_mean),
                                   list(key = "sar_mean", label = "Mean SAR (dB)", value = values$sar_mean)))
}
stats_list[[length(stats_list) + 1]] <- list(key = "snr_mean", label = "Mean SNR (dB)", value = values$snr_mean)
cs_publish(list(
  title = "Source separation metrics (SI-SDR, SDR, SIR, SAR)",
  engine = cs_engine_info("codesplashr", "nanoparquet"),
  n = nrow(df),
  summary = sprintf("Mean SI-SDR %.1f dB over %d clip(s) and %d source(s).", values$si_sdr_mean, length(clips), length(REFS)),
  statistics = stats_list,
  tables = tables,
  assumptions = assumptions,
  charts = charts,
  values = values,
  warnings = warnings,
  artifacts = list(list(key = "separation", path = file.path(out, "separation.parquet"), format = "parquet"))
))
Python

Mean SI-SDR 8.1 dB over 2 clip(s) and 3 source(s).

Mean SI-SDR (dB)
8.081
Mean SI-SDRi (dB)
11.413
Mean SDR (dB)
9.581
Mean SIR (dB)
10.972
Mean SAR (dB)
15.629
Mean SNR (dB)
8.620

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

Assumptions

  • Signals are aligned in time — Rows are read as samples in time order; a delay between a source and its estimate lowers SI-SDR.
  • No silent sources — Every true source varies in every clip.
  • One estimate per source — 3 separated signals for 3 true sources; matching reordered them in 1 of 2 clips.

Scores by clip and source

ClipTrue sourceMatched estimateSI-SDR (dB)SI-SDRi (dB)Mixture SI-SDR (dB)SDR (dB)SIR (dB)SAR (dB)SNR (dB)
as1est111.10310.8810.222412.62814.13018.13211.124
as2est26.03111.674−5.6437.9409.38613.8946.997
as3est36.83311.477−4.6438.2369.61314.3447.580
bs1est311.96610.8401.12713.36815.03218.47511.685
bs2est15.38811.810−6.4236.6537.73113.9106.477
bs3est27.16711.796−4.6308.6629.93915.0197.856
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Source separation metrics (SI-SDR, SDR, SIR, SAR)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method evaluate.separation 1.0.1 · spec 56f2d5c067a8ae81
# Dataset: aud1_separation (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 import ml as csml
from codesplash.audio import separation as sep

# %% Data
df = pd.read_parquet("tests/parity/fixtures/aud1_separation.parquet", columns=["s1", "s2", "s3", "est1", "est2", "est3", "mix", "clip"])
n_input = len(df)
df["clip"] = pd.Categorical(df["clip"], categories=sorted(df["clip"].dropna().unique()))
df = df.dropna(subset=["s1", "s2", "s3", "est1", "est2", "est3", "mix", "clip"])  # listwise deletion over the analysis columns
df["clip"] = df["clip"].cat.remove_unused_categories()
n_dropped = n_input - len(df)
warnings = []
if n_dropped:
    warnings.append(cs.cs_warning("CS_W_ROWS_DROPPED", dropped=n_dropped, total=n_input))
if n_input and not len(df):
    cs.cs_error("CS_E_NO_ROWS")
cs.check_finite_columns(df, ["s1", "s2", "s3", "est1", "est2", "est3", "mix", "clip"])  # infinite values stop the run (registry/errors.yaml)

# %% Signals: one column per true source and per separated signal, samples in row order
REFS = ["s1", "s2", "s3"]
ESTS = ["est1", "est2", "est3"]
MIX = "mix"
CLIP = "clip"
PERMUTE = True
ZERO_MEAN = True
BSS = True
FLEN = 512
if len(ESTS) != len(REFS):
    cs.cs_error("CS_E_INVALID_OPTION", option="Separated signals", allowed=f"{len(REFS)} columns, one per true source", value=len(ESTS))
clips = [("all rows", df)] if CLIP is None else [(str(k), g) for k, g in df.groupby(CLIP, observed=True, sort=True)]

# %% Scores per clip: permutation-invariant matching on SI-SDR, then SI-SDRi and BSS Eval
rows = []
n_permuted = 0
for name, g in clips:
    R = g[REFS].to_numpy(dtype=np.float64).T
    E = g[ESTS].to_numpy(dtype=np.float64).T
    for i, c in enumerate(REFS):
        s = R[i] - np.mean(R[i]) if ZERO_MEAN else R[i]
        if float(np.dot(s, s)) == 0.0:
            cs.cs_error("CS_E_UNDEFINED", what="SI-SDR", reason=f"the true source {c} is silent in clip {name}")
    m = g[MIX].to_numpy(dtype=np.float64) if MIX is not None else None
    r = sep.evaluate(R, E, m, zero_mean=ZERO_MEAN, bss=BSS, flen=FLEN, permute=PERMUTE)
    if any(int(r["perm"][i]) != i for i in range(len(REFS))):
        n_permuted += 1
    for i, c in enumerate(REFS):
        rows.append({
            "clip": name, "source": c, "estimate": ESTS[int(r["perm"][i])], "samples": int(R.shape[1]),
            "si_sdr": float(r["si_sdr"][i]),
            "si_sdri": float(r["si_sdri"][i]) if m is not None else None,
            "mixture_si_sdr": float(r["mixture_si_sdr"][i]) if m is not None else None,
            "sdr": float(r["sdr"][i]) if BSS else None,
            "sir": float(r["sir"][i]) if BSS else None,
            "sar": float(r["sar"][i]) if BSS else None,
            "snr": float(r["snr"][i]),
        })


def mean_of(key, source=None):
    v = [x[key] for x in rows if x[key] is not None and (source is None or x["source"] == source)]
    return float(np.mean(v)) if v else None


si = np.array([x["si_sdr"] for x in rows])
values = {
    "n_clips": len(clips), "n_sources": len(REFS), "n_samples": len(df),
    "si_sdr_mean": mean_of("si_sdr"), "si_sdr_median": float(np.median(si)), "si_sdr_min": float(np.min(si)),
    "si_sdri_mean": mean_of("si_sdri"), "mixture_si_sdr_mean": mean_of("mixture_si_sdr"),
    "sdr_mean": mean_of("sdr"), "sir_mean": mean_of("sir"), "sar_mean": mean_of("sar"), "snr_mean": mean_of("snr"),
    "n_permuted": n_permuted, "filter_length": FLEN if BSS else None,
}
for c in REFS:
    for key in ("si_sdr", "si_sdri", "sdr", "sir", "sar", "snr"):
        v = mean_of(key, c)
        if v is not None:
            values[f"{key}[{c}]"] = v

# %% Artifact: one row per clip and source
out = csml.out_dir("target/academy-parity/run-8142/evaluate.separation/three_sources_mixture/out-python")
art = pd.DataFrame(rows, columns=["clip", "source", "estimate", "samples", "si_sdr", "si_sdri", "mixture_si_sdr", "sdr", "sir", "sar", "snr"])
for c in ("clip", "source", "estimate"):
    art[c] = art[c].astype("string")
for c in ("si_sdri", "mixture_si_sdr", "sdr", "sir", "sar"):
    art[c] = pd.to_numeric(art[c], errors="coerce").astype("float64")
art.to_parquet(os.path.join(out, "separation.parquet"), index=False)

# %% Result
cols = [{"key": "clip", "label": "Clip"}, {"key": "source", "label": "True source"}, {"key": "estimate", "label": "Matched estimate"},
        {"key": "si_sdr", "label": "SI-SDR (dB)", "type": "number"}]
if MIX is not None:
    cols += [{"key": "si_sdri", "label": "SI-SDRi (dB)", "type": "number"}, {"key": "mixture_si_sdr", "label": "Mixture SI-SDR (dB)", "type": "number"}]
if BSS:
    cols += [{"key": "sdr", "label": "SDR (dB)", "type": "number"}, {"key": "sir", "label": "SIR (dB)", "type": "number"}, {"key": "sar", "label": "SAR (dB)", "type": "number"}]
cols += [{"key": "snr", "label": "SNR (dB)", "type": "number"}]
tables = [{"key": "scores", "title": "Scores by clip and source", "columns": cols, "rows": [{c["key"]: x[c["key"]] for c in cols} for x in rows[:500]]}]
kind, src, val = [], [], []
for x in rows:
    if MIX is not None:
        kind.append("Mixture"); src.append(x["source"]); val.append(x["mixture_si_sdr"])
    kind.append("Separated"); src.append(x["source"]); val.append(x["si_sdr"])
charts = [cs.chart("si_sdr", "cleveland-dot", "SI-SDR by source" + (": mixture and separated" if MIX is not None else ""), {
    "category": cs.col("True source", src, "categorical", REFS),
    "value": cs.col("SI-SDR (dB)", [v if np.isfinite(v) else None for v in val], "numeric"),
    "group": cs.col("Signal", kind, "categorical", ["Mixture", "Separated"] if MIX is not None else ["Separated"]),
}, note="Mean over clips. The gap between the dots is SI-SDRi, the gain over the unseparated mixture." if MIX is not None else "Mean over clips; higher is better.")]
if BSS:
    metric, msrc, mval = [], [], []
    for x in rows:
        for key, label in (("sdr", "SDR"), ("sir", "SIR"), ("sar", "SAR")):
            metric.append(label); msrc.append(x["source"]); mval.append(x[key] if np.isfinite(x[key]) else None)
    charts.append(cs.chart("bss_eval", "cleveland-dot", "BSS Eval by source", {
        "category": cs.col("True source", msrc, "categorical", REFS),
        "value": cs.col("dB", mval, "numeric"),
        "group": cs.col("Metric", metric, "categorical", ["SDR", "SIR", "SAR"]),
    }, note="SDR counts every error; SIR only leakage from the other sources; SAR only artifacts the separation added."))
assumptions = [
    {"key": "aligned", "label": "Signals are aligned in time", "status": "info",
     "detail": "Rows are read as samples in time order; a delay between a source and its estimate lowers SI-SDR."},
    {"key": "silent_reference", "label": "No silent sources", "status": "pass", "detail": "Every true source varies in every clip."},
    {"key": "same_count", "label": "One estimate per source", "status": "pass",
     "detail": f"{len(ESTS)} separated signals for {len(REFS)} true sources" + (f"; matching reordered them in {n_permuted} of {len(clips)} clips." if PERMUTE else ", paired in column order.")},
]
cs.publish({
    "title": "Source separation metrics (SI-SDR, SDR, SIR, SAR)",
    "engine": cs.engine_info("numpy", "pandas"),
    "n": len(df),
    "summary": f"Mean SI-SDR {values['si_sdr_mean']:.1f} dB over {len(clips)} clip(s) and {len(REFS)} source(s).",
    "statistics": [s for s in [
        {"key": "si_sdr_mean", "label": "Mean SI-SDR (dB)", "value": values["si_sdr_mean"]},
        {"key": "si_sdri_mean", "label": "Mean SI-SDRi (dB)", "value": values["si_sdri_mean"]} if MIX is not None else None,
        {"key": "sdr_mean", "label": "Mean SDR (dB)", "value": values["sdr_mean"]} if BSS else None,
        {"key": "sir_mean", "label": "Mean SIR (dB)", "value": values["sir_mean"]} if BSS else None,
        {"key": "sar_mean", "label": "Mean SAR (dB)", "value": values["sar_mean"]} if BSS else None,
        {"key": "snr_mean", "label": "Mean SNR (dB)", "value": values["snr_mean"]},
    ] if s is not None],
    "tables": tables,
    "assumptions": assumptions,
    "charts": charts,
    "values": values,
    "warnings": warnings,
    "artifacts": [{"key": "separation", "path": os.path.join(out, "separation.parquet"), "format": "parquet"}],
})

Source separation metrics matches each estimate to the true source it fits best, then reports SI-SDR. Here mean SI-SDR is 8.1 dB, while the mixture itself scored −3.3 dB, an improvementSI-SDR improvement (SI-SDRi)The separated signal's SI-SDR minus the mixture's: how much the separation helped compared with doing nothing. of 11.4 dB. Always report the improvement over doing nothing beside the raw value.

06

Where it stands in CodeSplash

Read
EntryIn CodeSplash
WER and CER (EVA039)Runs in CodeSplash: Generated-text metrics, Word and character error rates
SI-SDR (EVA040)Runs in CodeSplash: Source separation metrics, signals as columns
Reference · EVA040 · Runs in CodeSplashScale-invariant signal-to-distortion ratioMeasures waveform reconstruction quality after projecting the estimate onto a reference signal.
07

Check: error rates and SI-SDR

Checkpoint

Check yourself

An alignment finds 4 substitutions, 2 deletions and 3 insertions against 100 reference words. What is the WER, as a proportion?

Show the answer

Answer: 0.09

(4 + 2 + 3) / 100 = 0.09.

Check yourself

How can WER exceed 100%?

Show the answer

Answer: b

S + D can't exceed N, but I can. A babbling system gets a WER above 1.

Check yourself

You evaluate Chinese transcripts. Why report the character error rate?

Show the answer

Answer: b

WER depends on how text is split into words. Where that is ambiguous, CER is the stable unit.

Check yourself

A separated voice is the right signal at half the volume. What happens to its SI-SDR?

Show the answer

Answer: b

Scale invariance is the point: SI-SDR measures shape errors, not loudness. Plain SNR would penalize the volume change.

Check yourself

A separation reports SI-SDR 8 dB. Why also report SI-SDR of the unprocessed mixture?

Show the answer

Answer: a

SI-SDRi, the estimate's SI-SDR minus the mixture's, separates the system's contribution from the difficulty of the input.

08

Recap

Recap
  • WER = (S + D + I) / N from a minimum edit alignment; it can exceed 100%. Use CER where words are ill-defined, and state the normalization.
  • The S, D, I split shows how a system fails; every word counts the same, important or not.
  • SI-SDR compares a waveform estimate with its source, ignoring scale; report the improvement over the mixture.
  • Generated-text metrics computes WER and CER, and Source separation metrics SI-SDR, in Python and R.

Concepts in this lesson