Skip to content

GAgreement & reliability · evaluate.text

Generated-text metrics (BLEU, chrF, ROUGE)

How closely does generated text match reference texts, and is one system better than another?

Scores generated text (summaries, translations, model answers) against one or more references per row: corpus BLEU as sacreBLEU reports it (mteval-v13a tokens), chrF or chrF++ and ROUGE-1, ROUGE-2 and ROUGE-L F1, with paired-bootstrap intervals over rows on the shared random stream. With several candidate columns (one per system), each system is compared with the first by a paired bootstrap. Optionally adds word and character error rates (WER, CER: edits to reach the closest reference), as used for speech transcripts. Identical in Python and R; overlap metrics reward wording, not meaning, so read them beside a human or LLM-as-judge review.

Verified in Python and R Python and R agree to 10 decimals Seeded Also called BLEU, sacreBLEU, chrF…

A real result

Example “One system two refs”, recorded in both engines. In the app, “Try this example” loads it into Analyze.

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

system_a: BLEU 68.8, chrF 82.9, ROUGE-L F1 85.6 on 30 rows.

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

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)
BLEU100
BLEU71.894
BLEU59.695
BLEU52.474
BLEU70.711
BLEU68.037
BLEU53.077
BLEU61.020
BLEU73.111
BLEU100
BLEU69.144
BLEU33.913
BLEU100
BLEU15.881
BLEU35.495
BLEU51.311
BLEU58.143
BLEU65.804
BLEU100
BLEU34.192
BLEU48.110
BLEU100
BLEU100
BLEU84.090
BLEU100
BLEU35.084
BLEU100
BLEU61.020
BLEU52.474
BLEU79.527
chrF100
chrF85.516
chrF80.294
chrF74.648
chrF80.006
chrF91.414
chrF70.693
chrF89.889
chrF83.741
chrF100
chrF78.501
chrF67.629
chrF100
chrF54.242
chrF67.280
chrF75.106
chrF75.818
chrF77.961
chrF100
chrF70.190
chrF88.069
chrF100
chrF100
chrF86.455
chrF100
chrF60.563
chrF100
chrF72.993
chrF69.859
chrF85.124

First 60 of 150 rows.

Corpus scores with 95% bootstrap intervalsWhich system scores higher on each metric, and is the gap larger than the resampling noise?
View data
ScoreUpperLowerMetric
68.78077.07160.177BLEU
82.89687.67578.108chrF
90.32393.34287.263ROUGE-1
74.15581.07467.479ROUGE-2
85.56689.47981.503ROUGE-L

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 — One system: nothing to pair.
  • 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-L
system_a68.78082.89690.32374.15585.566
  • 2 rows have a missing output or no reference and are left out.
Python

system_a: BLEU 68.8, chrF 82.9, ROUGE-L F1 85.6 on 30 rows.

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

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 — One system: nothing to pair.
  • 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-L
system_a68.78082.89690.32374.15585.566
  • 2 rows have a missing output or no reference and are left out.

Do it in CodeSplash Run it on your own data, in Python or R, with the code to prove it.

Worked examples in the app

  • One system two refsml_gentext · candidate: system_a · reference: ref1, ref2
  • Two systems pairedml_gentext · candidate: system_a, system_b · reference: ref1, ref2
  • Single ref chrfpp lowerml_gentext · candidate: system_b · reference: ref1
  • Char tokens no bootstrapml_gentext · candidate: system_a, system_b · reference: ref2
  • Pre tokenizedml_gentext · candidate: system_b · reference: ref1, ref2
  • Wer cer two systemsml_gentext · candidate: system_a, system_b · reference: ref1, ref2
  • Wer cer single lowerml_gentext · candidate: system_b · reference: ref1
  • Degenerate all naml_gentext · candidate: system_a · reference: ref1, ref2

In the guides

Where it sits in the decision guides

  • Generate: quality (human or automated); relevance, safety, bias; task-specific metrics (BLEU, ROUGE, LLM-as-judge) · DS & ML Decision Guide · How to evaluate — common metrics by question type

What you need

Generated textcategorical · 1–8 columns
The text to score. Several columns = several systems on the same rows; the first is the baseline the others are compared with.
Referencescategorical · 1–4 columns
What a good output says. Several columns give each row several references; empty cells are skipped.

Choices you make

statistics

BLEU tokensdefault 13a

The tokenization changes BLEU a lot, so report it. 13a is the WMT standard behind most published BLEU numbers.

  • 13a (WMT standard)(default) — Splits off punctuation as the NIST mteval-v13a script does; use it for European languages and to match papers.
  • Characters — Every character is a token; for Chinese, Japanese and other text written without spaces.
  • None (already tokenized) — Splits on spaces only; use it when the text was tokenized before it reached the app.
Ignore casedefault off

Lower-case before BLEU, chrF, WER and CER (ROUGE always ignores case). Published BLEU is usually case-sensitive.

chrF variantdefault 0

chrF compares character n-grams; chrF++ adds word unigrams and bigrams, which correlates a little better with people.

  • chrF(default) — Character n-grams of length 1–6 with β = 2 (recall weighted twice as much as precision).
  • chrF++ — Character n-grams plus word unigrams and bigrams (Popović 2017).
Word and character error ratesdefault off

Also report WER and CER: the edits needed to turn each output into its closest reference, per word and per character (speech transcripts).

Bootstrap resamplesdefault 1000

Rows resampled with replacement for the intervals and the system comparison. 0 skips them.

Confidence leveldefault 0.95

How sure the bootstrap intervals should be: 0.95 gives 95% intervals.

Checks and remedies

CodeSplash checks each testable assumption on every run and shows the result on the card; premises the data can’t test are marked. If a check fails, these are the ways forward.

  • Good references

    Overlap metrics are only as good as the references; a correct answer worded differently scores low.

  • Same rows for every system

    Systems are compared row by row, so every candidate column must answer the same inputs.

  • Wording, not meaning

    BLEU, chrF and ROUGE count shared words or characters; they miss meaning, facts and safety. Pair them with a human or LLM-as-judge review.

What it reports

n
How many independent units the analysis used; it sets precision and power.
n_dropped
Rows where every system has an output and at least one reference exists; the others are dropped and counted.
n_systems
Rows where every system has an output and at least one reference exists; the others are dropped and counted.
n_refs
Rows where every system has an output and at least one reference exists; the others are dropped and counted.
bleu
A 0–100 score of how many of a generated text's word n-grams (1 to 4 words) appear in the references, with a penalty for being too short.
bleu_bp
A 0–100 score of how many of a generated text's word n-grams (1 to 4 words) appear in the references, with a penalty for being too short.
bleu_ratio
A 0–100 score of how many of a generated text's word n-grams (1 to 4 words) appear in the references, with a penalty for being too short.
bleu_p1
A 0–100 score of how many of a generated text's word n-grams (1 to 4 words) appear in the references, with a penalty for being too short.
bleu_p2
A 0–100 score of how many of a generated text's word n-grams (1 to 4 words) appear in the references, with a penalty for being too short.
bleu_p3
A 0–100 score of how many of a generated text's word n-grams (1 to 4 words) appear in the references, with a penalty for being too short.
bleu_p4
A 0–100 score of how many of a generated text's word n-grams (1 to 4 words) appear in the references, with a penalty for being too short.
hyp_len
A 0–100 score of how many of a generated text's word n-grams (1 to 4 words) appear in the references, with a penalty for being too short.
ref_len
A 0–100 score of how many of a generated text's word n-grams (1 to 4 words) appear in the references, with a penalty for being too short.
chrf
A 0–100 F-score over character n-grams (plus word n-grams in chrF++) shared with the references, weighting recall above precision.
rouge1
Overlap with a reference: shared words (ROUGE-1), word pairs (ROUGE-2) or the longest common word run (ROUGE-L), as F1 on 0–100.
rouge1_p
Overlap with a reference: shared words (ROUGE-1), word pairs (ROUGE-2) or the longest common word run (ROUGE-L), as F1 on 0–100.
rouge1_r
Overlap with a reference: shared words (ROUGE-1), word pairs (ROUGE-2) or the longest common word run (ROUGE-L), as F1 on 0–100.
rouge2
Overlap with a reference: shared words (ROUGE-1), word pairs (ROUGE-2) or the longest common word run (ROUGE-L), as F1 on 0–100.
rouge2_p
Overlap with a reference: shared words (ROUGE-1), word pairs (ROUGE-2) or the longest common word run (ROUGE-L), as F1 on 0–100.
rouge2_r
Overlap with a reference: shared words (ROUGE-1), word pairs (ROUGE-2) or the longest common word run (ROUGE-L), as F1 on 0–100.
rougeL
Overlap with a reference: shared words (ROUGE-1), word pairs (ROUGE-2) or the longest common word run (ROUGE-L), as F1 on 0–100.
rougeL_p
Overlap with a reference: shared words (ROUGE-1), word pairs (ROUGE-2) or the longest common word run (ROUGE-L), as F1 on 0–100.
rougeL_r
Overlap with a reference: shared words (ROUGE-1), word pairs (ROUGE-2) or the longest common word run (ROUGE-L), as F1 on 0–100.
sent_bleu_mean
A 0–100 score of how many of a generated text's word n-grams (1 to 4 words) appear in the references, with a penalty for being too short.
sent_chrf_mean
A 0–100 F-score over character n-grams (plus word n-grams in chrF++) shared with the references, weighting recall above precision.
tokenize
A 0–100 score of how many of a generated text's word n-grams (1 to 4 words) appear in the references, with a penalty for being too short.
chrf_label
A 0–100 F-score over character n-grams (plus word n-grams in chrF++) shared with the references, weighting recall above precision.

Per group, level or term: wer, cer, wer_sub, wer_del, wer_ins, wer_ref_words, cer_ref_chars, wer_ci_low, wer_ci_high, cer_ci_low, cer_ci_high, bleu_ci_low, bleu_ci_high, chrf_ci_low, chrf_ci_high, rouge1_ci_low, rouge1_ci_high, rouge2_ci_low, rouge2_ci_high, rougeL_ci_low, rougeL_ci_high, <metric>[<system>], diff_<metric>[<system>], p_<metric>[<system>], system[<i>]

Python and R

Python and R agree to 10 decimals (relative tolerance 1e-10). Python uses pandas, numpy, codesplash; R uses nanoparquet, codesplashr.

Default traps between the two languages

  • Both engines run the same twins (codesplash.text.metrics ↔ codesplashr R/text_metrics.R) and draw the bootstrap rows from the shared Wichmann–Hill stream. sacreBLEU (BLEU, chrF) and rouge-score (ROUGE, no stemmer) are the oracles in tests/crosscheck/w3ds2b_text.py.
  • WER and CER come from the twins codesplash.text.error_rates ↔ codesplashr R/text_error_rates.R (one alignment rule, so substitution, deletion and insertion counts agree); jiwer is the oracle (tests/crosscheck/w5txt1_error_rates.py).
  • Case folding uses each language's own lower-casing (Python str.lower, R tolower), which agree on Latin, Greek and Cyrillic letters; rare special cases such as the German ẞ can differ.
Python

The exact script CodeSplash ran for example “One system two refs” · 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 1c25652f22c958c9
# 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"]
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 = 1000
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 = False
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/one_system_two_refs/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"}],
})
R

The exact script CodeSplash ran for example “One system two refs” · 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 1c25652f22c958c9
# 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")
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 <- 1000
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 <- FALSE
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/one_system_two_refs/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"))
))

Sources

  • Papineni K, Roukos S, Ward T, Zhu W-J (2002). BLEU: a method for automatic evaluation of machine translation. ACL 2002, 311–318.
  • Post M (2018). A call for clarity in reporting BLEU scores. WMT 2018, 186–191.
  • Chen B, Cherry C (2014). A systematic comparison of smoothing techniques for sentence-level BLEU. WMT 2014, 362–367.
  • Popović M (2015). chrF: character n-gram F-score for automatic MT evaluation. WMT 2015, 392–395.
  • Popović M (2017). chrF++: words helping character n-grams. WMT 2017, 612–618.
  • Lin C-Y (2004). ROUGE: a package for automatic evaluation of summaries. Text Summarization Branches Out, ACL 2004, 74–81.
  • Koehn P (2004). Statistical significance tests for machine translation evaluation. EMNLP 2004, 388–395.
  • Levenshtein VI (1966). Binary codes capable of correcting deletions, insertions, and reversals. Soviet Physics Doklady, 10(8), 707–710.
  • NIST (2009). Speech recognition scoring toolkit (SCTK), sclite: word error rate as substitutions, deletions and insertions over reference words.

From the CodeSplash method registry · evaluate.text v1.1.1.