AI Wiki中文/EN

Text summarization: decide what survives the word budget

文本摘要

Compare extraction and generation, compute a sentence graph, and test why overlap scores cannot certify faithful summaries.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

A shorter text still has to preserve the right information

An invented observatory notice says that it opened on Monday, a telescope was repaired on Tuesday, and no public visits would happen on Tuesday. A two-sentence summary could preserve two perfectly accurate sentences and still omit the visit restriction that a visitor needed. Summarization therefore requires a choice about importance, not just deletion of words.

Define the audience, purpose and budget first. A generic summary asks for the document’s main points; a query-focused summary selects information relevant to a question. Summarizing several documents also requires handling repeated claims, conflicting accounts and source attribution. A sensible baseline is to retain complete opening sentences until the budget is exhausted. Its usefulness depends on how the source orders information.

Extractive summarization selects existing units, often sentences. Abstractive summarization generates new wording and may combine information across units. Extraction makes the selected wording traceable, but removing context can still mislead. Generation allows compression and paraphrase, but a fluent sentence may introduce unsupported content. Maynez and colleagues distinguish support by the source from correctness outside the source: an added fact can be true in the world yet absent from the document. Definitions, §§2.1–2.2

The sentence-graph example selects opening and repair information but omits the visit restriction. Deleting a negation still earns unigram F1 of 12/13; overlap cannot certify source faithfulness.
The sentence-graph example selects opening and repair information but omits the visit restriction. Deleting a negation still earns unigram F1 of 12/13; overlap cannot certify source faithfulness.

Ranking sentences is one component of summary selection

For candidate sentences indexed by i, let c-i be token cost and B the budget. An extractive formulation selects a subset A that maximizes an explicitly chosen utility:

max⁡AU(A)subject to∑i∈Aci≤B.\max_A U(A)\quad\text{subject to}\quad\sum_{i\in A}c_i\le B.

Utility might account for information coverage, relevance and redundancy. It is not supplied by the budget constraint itself. A score that rewards repeated vocabulary may favor boilerplate; a rule that chooses individually strong sentences may waste space on duplicates.

TextRank represents sentences as graph vertices and uses content overlap to connect them. Our original teaching variant uses Jaccard similarity between distinct token sets S-i, rather than reproducing the paper’s overlap/log-length weights:

Wij=∣Si∩Sj∣∣Si∪Sj∣(i≠j),Wii=0.W_{ij}=\frac{|S_i\cap S_j|}{|S_i\cup S_j|}\quad(i\ne j),\qquad W_{ii}=0.

An empty union gives weight zero. Repeated words do not multiply this set similarity, though they still contribute to a sentence’s token cost. The original paper supports the sentence-graph and recursive-ranking idea; these particular edge weights are our modeling choice. Weighted graphs and sentence extraction, §§2.2,4.1

Normalize each nonzero row of W to obtain a transition matrix T. Replace a zero row by the uniform distribution so isolated sentences do not lose probability mass. With N sentences and damping 0≤d<1 (the program caps d at0.99), add uniform restart and iterate a row distribution r:

P=dT+(1−d)11TN,r(k+1)=r(k)P.P=dT+(1-d)\frac{\mathbf1\mathbf1^T}{N},\qquad r^{(k+1)}=r^{(k)}P.

This implementation uses normalized probability scores. The paper writes its score update on a different scale. Neither convention turns a sentence’s centrality into its probability of being important to this reader. To avoid overflow on large finite weights, the code first divides each row by its largest weight before normalizing the row sum; this preserves its relative weights.

Uniform restart makes the update contract differences between equal-mass distributions by at most d in L1. If pi is the stationary distribution, the triangle inequality yields an inspectable error bound:

∥r−π∥1≤∥rP−r∥11−d.\|r-\pi\|_1\le\frac{\|rP-r\|_1}{1-d}.

The numerator is the residual of the current vector. Writing this residual as epsilon, the triangle inequality and contraction give error≤epsilon+d×error, which yields the bound after rearranging. The program reports this bound and whether it met tolerance; reaching the iteration cap is not reported as convergence. On a three-vertex star with d=0.85, the stationary scores are [18/37,19/74,19/74], which can also be obtained from linear equations.

Normalize centrality by its maximum to get relevance R-i. The program then repeatedly selects the feasible sentence with the highest positive score:

G(i∣A)=αRi−(1−α)max⁡j∈AWij,Ri=ri/max⁡jrj.G(i\mid A)=\alpha R_i-(1-\alpha)\max_{j\in A}W_{ij},\qquad R_i=r_i/\max_jr_j.

The redundancy term is zero before any selection. Stop if nothing fits or no positive score remains, and present selected sentences in source order. This is a specified greedy heuristic, not a proof that the budgeted utility optimum was found. Its relevance scaling matters because it makes the two terms comparable on a zero-to-one scale.

Watch what the budget leaves out

The complete original program uses Python 3.12 and NumPy 1.26.4. It takes already split English sentences, uses lowercase alphanumeric regex tokens, and handles at most 64 sentences. It does not implement multilingual segmentation or an abstractive language model.

"""Original extractive teaching baseline: sentence graph and redundancy penalty.

Jaccard edges deliberately differ from the original TextRank overlap/log-length
weights. No abstractive generator, semantic truth checker or corpus benchmark.
"""
from collections import Counter
import json
import re
import numpy as np


def tokens(text):
    if not isinstance(text,str) or len(text)>10000:raise ValueError('Use a short English teaching string')
    return re.findall(r'[a-z0-9]+',text.lower())


def sentences(values):
    if isinstance(values,str):raise ValueError('Supply a list of already split sentences')
    values=list(values)
    if len(values)>64:raise ValueError('At most64 sentences')
    for value in values:tokens(value)
    return values


def similarity(values):
    values=sentences(values);sets=[set(tokens(x)) for x in values];w=np.zeros((len(values),len(values)))
    for i in range(len(values)):
        for j in range(i):
            union=sets[i]|sets[j]
            w[i,j]=w[j,i]=len(sets[i]&sets[j])/len(union) if union else 0.
    return w


def rank(w,damping=.85,tolerance=1e-10,max_steps=5000):
    w=np.asarray(w,dtype=float)
    if w.ndim!=2 or w.shape[0]!=w.shape[1] or not 1<=len(w)<=64 or not np.isfinite(w).all() or (w<0).any():
        raise ValueError('Use a finite nonnegative square graph with1..64 vertices')
    if isinstance(damping,bool) or not np.isfinite(damping) or not 0<=damping<=.99:raise ValueError('Damping must be in[0,.99]')
    if not np.isfinite(tolerance) or not 1e-14<=tolerance<=1e-3:raise ValueError('Tolerance must be in[1e-14,1e-3]')
    if isinstance(max_steps,bool) or not isinstance(max_steps,int) or not 1<=max_steps<=10000:raise ValueError('Use1..10000 iterations')
    n=len(w);scale=w.max(1,keepdims=True)
    scaled=np.divide(w,scale,out=np.zeros_like(w),where=scale>0);mass=scaled.sum(1,keepdims=True)
    transition=np.divide(scaled,mass,out=np.full_like(w,1/n),where=mass>0)
    transition=damping*transition+(1-damping)/n;score=np.full(n,1/n)
    for step in range(1,max_steps+1):
        score=score@transition
        residual=float(np.abs(score@transition-score).sum());bound=residual/(1-damping)
        if bound<=tolerance:break
    return dict(scores=score,transition=transition,iterations=step,residual=residual,l1_error_bound=bound,converged=bound<=tolerance)


def select(values,scores,w,budget=20,relevance_weight=.7):
    values=sentences(values);scores=np.asarray(scores,dtype=float);w=np.asarray(w,dtype=float);n=len(values)
    if scores.shape!=(n,) or w.shape!=(n,n) or not np.isfinite(scores).all() or (scores<0).any() or not np.isfinite(w).all() or ((w<0)|(w>1)).any():raise ValueError('Invalid sentence scores/similarities')
    if isinstance(budget,bool) or not isinstance(budget,int) or not 0<=budget<=4096:raise ValueError('Use a token budget in0..4096')
    if isinstance(relevance_weight,bool) or not np.isfinite(relevance_weight) or not 0<=relevance_weight<=1:raise ValueError('Weight must be in[0,1]')
    relevance=scores/scores.max() if n and scores.max()>0 else np.zeros(n)
    costs=[len(tokens(x)) for x in values];selected=[];steps=[];remaining=budget
    while True:
        choices=[]
        for i in range(n):
            if i in selected or costs[i]==0 or costs[i]>remaining:continue
            redundancy=max((w[i,j] for j in selected),default=0.)
            gain=float(relevance_weight*relevance[i]-(1-relevance_weight)*redundancy)
            choices.append((-gain,i,redundancy))
        if not choices:break
        negative,i,redundancy=min(choices)
        if -negative<=0:break
        selected.append(i);remaining-=costs[i];steps.append(dict(sentence=i,gain=-negative,redundancy=float(redundancy),cost=costs[i]))
    order=sorted(selected)
    return dict(selection_order=selected,source_order=order,text=' '.join(values[i] for i in order),used_tokens=budget-remaining,steps=steps)


def rouge1(prediction,reference):
    """Single-reference unigram overlap only; not the complete ROUGE package."""
    p=Counter(tokens(prediction));r=Counter(tokens(reference));npred=sum(p.values());nref=sum(r.values())
    if not nref:raise ValueError('The reference must contain tokens')
    overlap=sum((p&r).values());precision=overlap/npred if npred else 0.;recall=overlap/nref
    return dict(overlap=overlap,predicted_tokens=npred,reference_tokens=nref,precision=precision,recall=recall,f1=2*overlap/(npred+nref))


def demo():
    docs=['Ada opened the observatory on Monday.',
          'The observatory opened on Monday for school visitors.',
          'Bo repaired the telescope on Tuesday.',
          'The telescope repair was delayed by rain.',
          'Ada said no public visits would happen on Tuesday.']
    w=similarity(docs);r=rank(w);chosen=select(docs,r['scores'],w,budget=18)
    reference='The observatory opened on Monday. No public visits would happen on Tuesday.'
    # A deliberately bad negation deletion can retain substantial unigram overlap.
    faithful='No public visits would happen on Tuesday.';negation_deleted='Public visits would happen on Tuesday.'
    return dict(sentences=docs,weights=w.tolist(),scores=r['scores'].tolist(),iterations=r['iterations'],
        residual=r['residual'],l1_error_bound=r['l1_error_bound'],converged=r['converged'],
        summary=chosen,rouge1=rouge1(chosen['text'],reference),
        negation_example=dict(reference=faithful,candidate=negation_deleted,rouge1=rouge1(negation_deleted,faithful)),
        conditions='Five invented sentences; Jaccard graph; English regex tokens;18-token budget; no semantic correctness score')


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

For the five invented sentences, a budget of 18 tokens selects source sentences 0 and 2, totaling 12 tokens. They mention the opening and repair, while the visit restriction is omitted. The result illustrates a centrality-based selection rule; it does not certify that the reader’s priorities were met. The remaining budget is too small for any of the other complete sentences.

Checks compare the graph computation with an independent stationary linear solve, verify the error bound and dangling rows, and test redundancy, deterministic ties and source-order restoration. A one-iteration run can explicitly report nonconvergence. The program also handles very large finite edge weights without overflowing their row sums.

With N sentences and at most L token-set work per comparison, dense graph construction costs O(N²L), and K ranking iterations cost O(KN²). Graph storage is O(N²). This simple selector recomputes redundancy against all selected sentences, giving O(N³) worst-case selection work; an incremental implementation could do less. Bounds also include a 4,096-token selection budget and 10,000 characters per sentence.

Measure coverage without mistaking it for truth

ROUGE-N counts n-gram overlap with reference summaries. The program implements only a single-reference unigram variant, with overlap count C obtained by summing the smaller prediction/reference frequency separately for each word. It reports precision, recall and F1:

P1=C/Lpred,R1=C/Lref,F1=2CLpred+Lref.P_1=C/L_{\mathrm{pred}},\qquad R_1=C/L_{\mathrm{ref}},\qquad F_1=\frac{2C}{L_{\mathrm{pred}}+L_{\mathrm{ref}}}.

An empty prediction scores zero; an empty reference is rejected here. This is not the complete ROUGE package or a claim about its multi-reference or sequence-based variants. ROUGE-N definition, §2

Deleting “No” from the invented reference “No public visits would happen on Tuesday” leaves six of seven reference tokens. Unigram precision becomes 1, recall 6/7 and F1 12/13, despite reversing the restriction. The selected two-sentence summary has unigram F1 7/12 against its supplied reference; neither number is a semantic truth score.

For generated summaries, sequence-to-sequence learning gives an executable example of conditional likelihood training. Such an objective does not directly enforce the source-support criterion defined by Maynez and colleagues. This difference motivates checking support separately from the training loss. Source-support definition, §§2.1–2.2

Evaluate important claims, omissions, attribution, negation and entity/number changes in addition to automatic overlap. Keep the document split, reference summaries, tokenization and length budget fixed when comparing methods. If source documents disagree, a summary that silently chooses one claim may need attribution rather than more aggressive compression. Human assessment should state the task criteria and agreement procedure; a high score alone cannot provide those judgments.

Predict the failure before reading the score

  1. Does copying two source sentences guarantee that an extractive summary is useful and faithful in context?

Answer: No. It preserves their wording, but may omit a restriction, antecedent or attribution needed to interpret them. The observatory example drops the visitor-relevant restriction even though the selected sentences occur in the source.

  1. On the three-vertex star with damping 0.85, what is the central vertex’s stationary mass?

Answer: Let it be x. Uniform restart contributes 0.05, and the two leaves send their combined mass 1−x to the center. Thus x=0.05+0.85(1−x), giving x=18/37; the symmetric leaves each get 19/74.

  1. A six-token prediction matches six tokens of a seven-token reference after deleting its only negation. Compute unigram F1 and interpret it.

Answer: F1=2×6/(6+7)=12/13. This measures word overlap and misses the meaning change; it cannot establish faithful summarization.

  1. A generated summary includes a correct background fact absent from the source. How should its quality be discussed?

Answer: Separate world factuality from source support. The fact may be correct yet unsupported by this document. Whether adding it is acceptable depends on the summary task; label or source the addition rather than silently treating it as extracted evidence.

Connect selection, generation and evaluation

TextRank supplies a graph-ranking approach to extraction, Lin’s ROUGE paper supplies an overlap-based evaluation family, and Maynez and colleagues clarify different ways a generated summary can depart from its source. The graph weights, redundancy rule, corpus and counterexamples here are original teaching choices. No paper’s benchmark results or human-evaluation percentages are reproduced.

Make a prediction, then check

A summary drops “No” and receives ROUGE-1 F1 of12/13. What follows?

Choose one answer

Learning objectives

  • Distinguish compression utility, source faithfulness and world factuality.
  • Derive normalized graph ranking and its residual error bound.
  • Trace word-budget selection and redundancy penalties.
  • Explain why high unigram overlap can miss a negation error.

Prerequisites & connections

Explore related knowledge →

References

  1. TextRank: Bringing Order into Texts
    Rada Mihalcea, Paul Tarau · 2004
  2. ROUGE: A Package for Automatic Evaluation of Summaries
    Chin-Yew Lin · 2004
  3. On Faithfulness and Factuality in Abstractive Summarization
    Joshua Maynez, Shashi Narayan, Bernd Bohnet, Ryan McDonald · 2020

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-12 · Single AI author checked extraction/generation, source faithfulness versus world factuality against scoped TextRank, ROUGE and Maynez definitions. Six paired equations and four explained exercises verified: Jaccard variant, normalized restart, contraction residual bound, independent star solution, greedy budget/redundancy and per-word clipped unigram overlap. Negation deletion F1 of12/13 is an original counterexample, not a benchmark result.

  • Single AI author checked extraction/generation, source faithfulness versus world factuality against scoped TextRank, ROUGE and Maynez definitions. Six paired equations and four explained exercises verified: Jaccard variant, normalized restart, contraction residual bound, independent star solution, greedy budget/redundancy and per-word clipped unigram overlap. Negation deletion F1 of12/13 is an original counterexample, not a benchmark result.
  • Four computed SVGs bind exact bilingual MDX. The four-topic group passed eight numeric/encoding checks and24 isolated language/width cases with four fallback fonts; eight 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:

Related topics

No matches. Try a synonym or acronym.

0 results shown

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