AI Wiki中文/EN

Evaluating generated language: which question does the score answer?

语言生成评测

Implement explicit character-overlap scoring, compare aggregation and paired resampling, and examine meaning errors and human judgment.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

A different average can reverse the ranking

Imagine a tiny generation test with two references: one has 10 characters, the other 2. System A reproduces the long item perfectly and misses the short one completely; system B matches only 4 characters of the long item but gets the short one right. Scoring each sentence and averaging favors B. Pooling character counts before scoring favors A. The outputs stayed fixed; the evaluation changed how examples were weighted.

Evaluation of generated language asks whether outputs fulfill a specified task, how strong the evidence is, and what mistakes cost. Translation can emphasize adequacy of meaning and fluency; summarization must also preserve important content and remain faithful to its source; task-oriented answers must satisfy questions and constraints. Koehn discusses adequacy, fluency and sampling uncertainty when automatic scores compare translation systems. A metric name is not a complete definition of those requirements. Evaluation goals and sampling

Before comparing systems, specify the task, inputs, references or judgment evidence, split and primary metric. Retain a simple baseline, such as fixed-format responses or sentences extracted from the input, to make improvement concrete. For human inspection, provide a rubric and contrasting examples before hiding system identity and presentation order, and preserve disagreements. These are experimental-design recommendations, not a human annotation study already conducted by this project.

Automatic scoring offers frequent, reproducible measurement of one aspect. Post shows that even BLEU depends on reference count, smoothing, tokenization and preprocessing settings; unspecified settings frustrate comparisons between papers. Reproducing a number still leaves the question of what the number represents. Parameters and reference processing, section 2

A fixed pair of outputs reverses ranking under sentence averaging and pooled counts. Four paired resamples show signed score differences; neither a positive fraction nor high overlap establishes real-world superiority or correct meaning.
A fixed pair of outputs reverses ranking under sentence averaging and pooled counts. Four paired resamples show signed score differences; neither a positive fraction nor high overlap establishes real-world superiority or correct meaning.

Separate measurement, aggregation and sampling

We implement a single-reference character-overlap metric with the chrF form. Each sentence first retains or removes whitespace according to configuration and optionally applies Unicode casefold. Character nn-grams are then extracted separately from hypothesis hh and reference rr. At each order kk, clipping repeat counts prevents a repeated output fragment from earning unlimited credit:

mk=∑gmin⁡{ch,k(g),cr,k(g)},Hk=∑gch,k(g),Tk=∑gcr,k(g).m_k=\sum_g\min\{c_{h,k}(g),c_{r,k}(g)\},\qquad H_k=\sum_gc_{h,k}(g),\quad T_k=\sum_gc_{r,k}(g).

Hk,TkH_k,T_k count hypothesis and reference occurrences at that order. Let AA contain orders for which both counts are positive. Compute precision and recall by order, then average each arithmetically. With no effective order, this program defines the score as zero.

A={k:Hk>0, Tk>0},P=1∣A∣∑k∈AmkHk,R=1∣A∣∑k∈AmkTk.A=\{k:H_k>0,\ T_k>0\},\qquad P=\frac{1}{|A|}\sum_{k\in A}\frac{m_k}{H_k},\quad R=\frac{1}{|A|}\sum_{k\in A}\frac{m_k}{T_k}.

Finally, β\beta controls the precision–recall tradeoff; the formula contains β2\beta^2. This is the form of Popović’s chrF equation. Our empty-input, effective-order and preprocessing rules are stated separately rather than claimed compatible with every chrF implementation version. Equation 1 and its definitions

Fβ=(1+β2)PRβ2P+R(β2P+R>0);Fβ=0(β2P+R=0).F_\beta=\frac{(1+\beta^2)PR}{\beta^2P+R}\quad (\beta^2P+R>0);\qquad F_\beta=0\quad(\beta^2P+R=0).

For h=aaah=\texttt{aaa} and r=abr=\texttt{ab} using only order one, the matching count is 1, so P=1/3,R=1/2P=1/3,R=1/2. At β=2\beta=2, Fβ=5/11F_\beta=5/11. Identical nonempty strings score 1; two strings that both become empty after processing score 0 here. Report this convention explicitly instead of assuming that identical inputs always receive full credit.

Averaging sentence scores generally differs from pooling per-order counts before scoring. Let sis_i be sentence ii‘s count array and ff the function converting counts to a score:

Fmacro=1N∑i=1Nf(si),Fpooled=f ⁣(∑i=1Nsi).F_{\mathrm{macro}}=\frac{1}{N}\sum_{i=1}^{N}f(s_i),\qquad F_{\mathrm{pooled}}=f\!\left(\sum_{i=1}^{N}s_i\right).

The opening example uses order one, β=1\beta=1 and equal hypothesis/reference lengths within each sentence. A has sentence mean 0.5 and B has 0.7, whereas pooled scores are 10/1210/12 for A and 6/126/12 for B. A corpus score should not casually be called “average accuracy”: equal character counts, sentences, documents and languages answer different questions.

When comparing two systems, both must face the same sampled instances. For NN aligned test items, resample both systems with the same with-replacement index sequence II and record the score difference. Koehn’s paired bootstrap uses this shared-index idea. Sections 5–6

I=(I1,…,IN),Ij∼iidUniform⁡{1,…,N},ΔI=f ⁣(∑jsIjA)−f ⁣(∑jsIjB).I=(I_1,\ldots,I_N),\quad I_j\overset{\mathrm{iid}}\sim\operatorname{Uniform}\{1,\ldots,N\},\qquad \Delta_I=f\!\left(\sum_js^A_{I_j}\right)-f\!\left(\sum_js^B_{I_j}\right).

We enumerate every one of the NNN^N index sequences. All are equally probable, allowing exact computation of this finite empirical distribution and its quantiles:

F^(t)=1NN∑I∈{1,…,N}N1{ΔI≤t},Q(q)=inf⁡{t:F^(t)≥q},0<q<1.\widehat F(t)=\frac{1}{N^N}\sum_{I\in\{1,\ldots,N\}^N}\mathbf1\{\Delta_I\le t\},\qquad Q(q)=\inf\{t:\widehat F(t)\ge q\},\quad 0<q<1.

The two-item example has index sequences 00, 01, 10 and 11, giving differences 0.6, 1/31/3, 1/31/3 and −1. The observed difference is 1/31/3, the resampling mean 1/151/15, the 2.5% and 97.5% quantiles −1 and 0.6, and the strictly positive fraction 3/4. That fraction is neither a p-value nor the probability that A is superior in the real world. These quantiles exactly describe the empirical distribution of the supplied tiny dataset; two samples do not establish future coverage guarantees.

A scorer with traceable settings

The complete program needs Python and NumPy. It retains matching and total counts for each sentence and order; corpus aggregation never forms character n-grams across sentence boundaries. Its signature records order, β\beta, whitespace, casefold, effective-order and empty rules, scale and Unicode version. SacreBLEU’s signatures and options informed this design, while teaching-chrf-v1 explicitly identifies our original teaching conventions. Reproducible reporting Pinned tool documentation

"""Explicit chrF-style scoring, aggregation and exact paired empirical resampling.

Not SacreBLEU-compatible: one reference, stated empty/order rules and 0–1 scale.
No statistical guarantee follows from tiny invented examples.
"""
from collections import Counter
from itertools import product
import json
import math
import unicodedata
import numpy as np


def config(order=3,beta=2.,whitespace=False,lowercase=False):
    if type(order) is not int or not 1<=order<=6:raise ValueError('Order must be 1–6')
    if isinstance(beta,bool) or not isinstance(beta,(int,float)) or not math.isfinite(beta) or not 0<beta<=10:raise ValueError('Beta must be in (0,10]')
    if type(whitespace) is not bool or type(lowercase) is not bool:raise ValueError('Flags must be boolean')
    return dict(order=order,beta=float(beta),whitespace=whitespace,lowercase=lowercase)


def sentence_stats(hypothesis,reference,options):
    options=config(**options)
    def clean(s):
        if not isinstance(s,str) or len(s)>200:raise ValueError('Use text of at most 200 code points')
        if options['lowercase']:s=s.casefold()
        return s if options['whitespace'] else ''.join(s.split())
    h=clean(hypothesis);r=clean(reference);rows=[]
    for n in range(1,options['order']+1):
        a=Counter(h[i:i+n] for i in range(len(h)-n+1));b=Counter(r[i:i+n] for i in range(len(r)-n+1))
        rows.append([sum((a & b).values()),sum(a.values()),sum(b.values())])
    return np.array(rows,dtype=np.int64)


def from_stats(rows,beta):
    # Rows are internal validated integer counts; orders lacking either side are excluded.
    active=rows[(rows[:,1]>0)&(rows[:,2]>0)]
    if not len(active):return dict(precision=0.,recall=0.,score=0.,effective_order=0)
    p=float(np.mean(active[:,0]/active[:,1]));r=float(np.mean(active[:,0]/active[:,2]));den=beta*beta*p+r
    return dict(precision=p,recall=r,score=(1+beta*beta)*p*r/den if den else 0.,effective_order=len(active))


def corpus(hypotheses,references,options=None):
    c=config(**({} if options is None else options))
    if not isinstance(hypotheses,(list,tuple)) or not isinstance(references,(list,tuple)) or len(hypotheses)!=len(references) or not 1<=len(hypotheses)<=64:raise ValueError('Use 1–64 aligned sentence pairs')
    rows=np.array([sentence_stats(h,r,c) for h,r in zip(hypotheses,references)])
    result=from_stats(rows.sum(axis=0),c['beta']);result['macro']=float(np.mean([from_stats(row,c['beta'])['score'] for row in rows]))
    result['signature']=f"teaching-chrf-v1|nrefs:1|order:{c['order']}|beta:{c['beta']}|space:{c['whitespace']}|casefold:{c['lowercase']}|eff:both-nonempty|empty:0|scale:0-1|unicode:{unicodedata.unidata_version}"
    result['counts']=rows.tolist();return result


def paired_bootstrap(a,b,references,options=None):
    if not 1<=len(references)<=5:raise ValueError('Exact enumeration is limited to 1–5 aligned items')
    c=config(**({} if options is None else options));ra=corpus(a,references,c);rb=corpus(b,references,c)
    sa=np.array(ra['counts']);sb=np.array(rb['counts']);n=len(references);deltas=[]
    for indices in product(range(n),repeat=n):
        counts=np.bincount(indices,minlength=n)
        x=np.einsum('i,ijk->jk',counts,sa);y=np.einsum('i,ijk->jk',counts,sb)
        deltas.append(from_stats(x,c['beta'])['score']-from_stats(y,c['beta'])['score'])
    values=sorted(deltas)
    def quantile(q):return values[max(0,math.ceil(q*len(values))-1)]
    return dict(observed=ra['score']-rb['score'],resamples=n**n,mean=float(np.mean(values)),
                interval95=[quantile(.025),quantile(.975)],positive_fraction=sum(x>0 for x in values)/len(values),
                minimum=values[0],maximum=values[-1],
                scope='Exact empirical paired resampling distribution; positive_fraction is not a p-value or probability of real-world superiority.')


def demo():
    refs=['abcdefghij','xy'];a=['abcdefghij','zz'];b=['abcdxxxxxx','xy'];c=config(order=1,beta=1)
    # A preserves the long item; B preserves the short item. Same lengths on both sides.
    reference='The room is not open.';wrong='The room is open.'
    return dict(aggregation=dict(references=refs,a=a,b=b,A=corpus(a,refs,c),B=corpus(b,refs,c)),
                negation=dict(reference=reference,candidate=wrong,score=corpus([wrong],[reference])),
                settings=[corpus(['A B'],['ab'],config(order=2,whitespace=space,lowercase=case)) for space,case in [(False,False),(False,True),(True,True)]],
                paired=paired_bootstrap(a,b,refs,c),identical=paired_bootstrap(a,a,refs,c))


if __name__=='__main__':print(json.dumps(demo(),indent=2,allow_nan=False))

Run python language_evaluation.py. aggregation should show opposite rankings, and paired should report four enumerated resamples with the difference range above. settings compares “A B” with “ab”: no casefold scores 0; casefold plus whitespace removal scores 1; casefold with spaces retained and maximum order two scores 5/115/11. The same raw strings receive different scores under reasonable but distinct settings.

negation changes “The room is not open.” into “The room is open.” The default maximum order three with β=2\beta=2 still yields approximately 0.775790, despite the reversal of a crucial meaning. This is a metric counterexample, not a human quality rating or a real model result.

Ordinary scoring accepts at most 64 pairs, each original string at most 200 code points, and maximum order 6. Counting Python substring-copy costs, statistics for NN sentences of length LL and maximum order KK take O(NLK2)O(NLK^2) time. Cached arrays use O(NK)O(NK) space; dictionaries hold at most O(LK)O(LK) entries with O(LK2)O(LK^2) total key characters. Exact resampling is limited to N≤5N\le5, taking O(NN+1(K+log⁡N))O(N^{N+1}(K+\log N)) time after caching counts, including sorting for quantiles, and O(NN)O(N^N) stored differences. A large real test set needs a separately validated sampling implementation and fixed random seed; this small program does not silently switch to approximation.

A stable number can measure the wrong question

Character overlap does not understand negation, entity relations or source support. Multiple references can reduce some penalties for valid paraphrases but cannot enumerate every correct output. Learned evaluators can use richer representations, yet their criteria, calibration and failure slices still need validation. Changing the scoring model does not automatically provide an arbiter of factual truth. What chrF measures

Decompose human inspection into judgments such as source support, important omissions and comprehensibility. Ask judges to retain evidence and uncertainty, and inspect whether disagreement comes from the rubric or the examples rather than immediately compressing opinions into an average. Apply the same rubric to a non-AI task baseline instead of changing criteria for a new model. This is experimental advice, not a measured annotator-agreement result.

The resampling unit must match dependencies. When sentences share a document, independently resampling sentences can understate document-level variation; duplicates do not create independent evidence either. Resampling addresses variation under the supplied data and measure. It does not remove contamination, reference errors or differences between the test task and deployment. Paired-sampling assumptions Bootstrap resampling

A report should preserve raw outputs, data version, settings, aggregation and environment, along with language/domain or critical-error slices. SacreBLEU supports signatures and paired statistical tools, but their outputs still require correct interpretation. Statistical significance and practical utility also require separate judgments. Reporting requirements Pinned project reference

Four evaluation decisions

  1. Why does high character overlap fail to establish factual correctness?

Answer: It compares counts of character fragments rather than judging the expressed proposition. Removing a negation preserves many fragments; the example’s approximately 0.775790 cannot establish that “not open” and “open” are compatible. Add checks tied to task evidence and error types.

  1. Calculate sentence means and pooled corpus scores for the two opening systems.

Answer: With order one, equal lengths and β=1\beta=1, each sentence score is its matching fraction. A gives (1+0)/2=0.5(1+0)/2=0.5, B gives (0.4+1)/2=0.7(0.4+1)/2=0.7, while pooled scores are 10/1210/12 and 6/126/12. The long item contributes more to pooled counts, reversing the ranking.

  1. What is the paired resampling difference distribution when A and B are identical? Does a positive fraction of zero mean B is better?

Answer: Every index sequence gives difference zero, and the quantile interval is [0,0]. Strictly positive differences never occur, so their fraction is zero. This describes ties everywhere rather than victories for B. Inspect differences and ties together instead of reading only one fraction.

  1. Does splitting one document into 100 sentences provide 100 independent test observations?

Answer: The sentence count alone does not justify independence. Shared topic, source and generation conditions can correlate errors. Choose a resampling unit such as documents according to the inferential target, retaining alignment between systems. Duplicating sentences changes counts without supplying equally many independent observations.

From comparable numbers to interpretable conclusions

Popović supplies a simple character measure, Post focuses on comparable settings and reference preprocessing, and Koehn discusses comparisons on small test sets. These address different layers: metric definition, experimental records and sampling uncertainty. Doing one layer well cannot substitute for the others. Metric paper Reporting paper Statistical paper

Read permutation tests to distinguish null distributions from empirical resampling, and text summarization for a task-specific contrast between overlap and faithfulness. This program reports no formal significance p-value and has not conducted real-corpus or human-evaluation experiments.

Make a prediction, then check

A has higher pooled character F1 while B has higher mean sentence F1. What follows?

Choose one answer

Learning objectives

  • Define the task judgment before choosing a metric.
  • Compute clipped character overlap with explicit settings.
  • Explain ranking reversals caused by aggregation.
  • Interpret paired empirical resampling without inventing a p-value.

Prerequisites & connections

Explore related knowledge →

References

  1. chrF: character n-gram F-score for automatic MT evaluation
    Maja Popović · 2015
  2. A Call for Clarity in Reporting BLEU Scores
    Matt Post · 2018
  3. Statistical Significance Tests for Machine Translation Evaluation
    Philipp Koehn · 2004
  4. SacreBLEU: pinned metric options, signatures and paired tests
    Matt Post and SacreBLEU contributors · 2026

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-13 · Single AI author checked metric/reporting/sampling distinctions against scoped chrF, Post, Koehn and pinned SacreBLEU documentation. Six paired equations and four explained exercises derive clipped counts, averaged precision/recall, squared beta, macro versus pooled ranking and exact paired empirical resampling. Sorting complexity corrected with original drafts retained. Positive fractions and quantiles are not formal p-values or real-world guarantees.

  • Checked clipping, casefold/whitespace, empty/effective-order rules, no cross-sentence ngrams, opposite aggregation rankings and four paired resamples. Exact output and 0.775790 negation counterexample checked. Preserve the sorting-cost correction and distinguish metric meaning from human judgments.
  • Four computed SVGs bind exact bilingual MDX. The three-topic group passed eight numeric/encoding checks and 18 isolated language/width cases with four fallback fonts; six actual screenshots inspected by the AI author. Literal-prose AST checked before freezing. Full article browser acceptance is separate; no human peer review.

Source locations checked:

  • chrF: character n-gram F-score for automatic MT evaluation · Visually read page 1/392, section 2 equation 1 and order-averaged precision/recall definitions. Use the squared beta in the formula; our effective-order, empty and normalization conventions are explicitly additional. No human-correlation results adopted.
  • A Call for Clarity in Reporting BLEU Scores · Read abstract, sections 2.1–2.2 on parameters/reference preprocessing, section 2.5 and scoped 3.3 tool description. Preserve PDF/footer DOI discrepancy in research; use this verified URL, not the conflicting footer DOI.
  • Statistical Significance Tests for Machine Translation Evaluation · Read section 2.2 adequacy/fluency and sections 5–6 resampling assumptions and shared samples for two systems. Formula OCR is damaged and not used. Our exact empirical quantiles/positive fraction are not a p-value or a real-world superiority probability.
  • SacreBLEU: pinned metric options, signatures and paired tests · Commit 2026-08-20. Read README 1–26,187–207,215–247,407–453. Apache 2.0 header inspected, not complete reuse review. The Type-I explanation at line446 is wrong and not adopted. Reference only, no upstream execution or compatibility claim.

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.