AI Wiki中文/EN

Constituency parsing: which words form a unit?

成分句法分析

Build a probabilistic grammar and CKY parser, distinguish the best tree from total sentence mass, and test a grammar whose finite derivations sum to less than one.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

Who has the telescope?

In the invented sentence I saw the man with a telescope, the final phrase can describe the instrument used for seeing or the man who has the telescope. All seven words stay in the same order. The difference is how they group: does with a telescope attach inside the noun phrase about the man, or to the verb phrase about seeing?

Constituency parsing constructs a hierarchy of phrases. A constituent covers a span of words and has a label such as NP for noun phrase, VP for verb phrase or PP for prepositional phrase. In the ordinary projective trees used here, child spans are contiguous, do not overlap, and together cover the parent. A tree records grouping; it does not independently establish which reading a speaker intended.

This differs from dependency parsing, which assigns head–dependent relations between tokens. Neither representation can be recovered from a flat list of word classes alone. The example’s grouping is precisely what a phrase tree adds.

A useful parser must say what structures it permits and how it chooses among them. A context-free grammar supplies the permitted rewrites; probabilities supply a way to rank trees. Collins’s lecture notes develop this combination and the CKY dynamic program. PCFG notes, §§3.2–3.4

Two parses compete for the same prepositional phrase. The inside probability adds their masses; Viterbi keeps the more probable tree.
Two parses compete for the same prepositional phrase. The inside probability adds their masses; Viterbi keeps the more probable tree.

Rules, trees and the quantity a chart cell stores

A rule is a local choice

A context-free grammar has nonterminal symbols, terminal words, a start symbol S and rewrite rules. A probabilistic context-free grammar, PCFG, adds a nonnegative weight θ_r to each rule r. Rules with the same left-hand symbol sum to one. If a tree T uses a rule multiple times, every occurrence contributes a factor:

∑r:lhs⁡(r)=Aθr=1,P(T)=∏r occurrences in Tθr.\sum_{r:\operatorname{lhs}(r)=A}\theta_r=1,\qquad P(T)=\prod_{r\text{ occurrences in }T}\theta_r.

The context-free assumption here means the rule choice depends on the symbol being expanded, not its parent, surrounding words or position. This makes the dynamic program possible but can discard information important for disambiguation. The product is a tree probability; summing over all trees with the same yield gives that sentence’s mass. PCFG notes, §3.2

If fully annotated training trees are available, count each rule occurrence. Let C_r be the count of rule r and C_A the count of expansions of its left-hand symbol. Maximum-likelihood estimation gives:

θ^r=CrClhs⁡(r).\widehat\theta_r=\frac{C_r}{C_{\operatorname{lhs}(r)}}.

To see why, the corpus log likelihood is the sum of C_r log θ_r. For one left-hand symbol, maximizing this sum subject to the probabilities summing to one gives θ_r proportional to C_r; the constraint supplies the denominator C_A. This estimates parameters from known trees, not from unparsed sentences. Grammar induction or learning with hidden trees is a different problem. PCFG notes, §3.3

For example, two training trees use S→A B and A→a in both cases, but one uses B→b and the other B→c. The first two rule probabilities are one; the two B rules have probability one-half each. The sentence a c has a single tree of probability one-half in this grammar.

Why use Chomsky normal form here?

The parser accepts only binary rules A→B C and lexical rules A→w. This is the nonempty Chomsky normal form, CNF, used in the teaching algorithm. Every non-leaf phrase can be split into exactly two shorter phrases, and every leaf rule consumes one word. There are no empty productions or unary nonterminal chains. PCFG notes, §3.4.1

A real treebank need not arrive in this form. Binarization may introduce artificial symbols, and unary/empty structures require explicit treatment. A conversion must preserve the intended probabilities and provide a way to recover the original tree labels for evaluation. Our program rejects unsupported rules; it does not quietly discard them or claim to implement a general grammar converter.

Best tree: multiply children, maximize alternatives

Use zero-based half-open spans [i,j). Let V(A,i,j) be the largest log probability of a tree rooted at A covering that span. A missing tree has value negative infinity. For a one-word span:

V(A,i,i+1)=max⁡A→wilog⁡θA→wi.V(A,i,i+1)=\max_{A\to w_i}\log\theta_{A\to w_i}.

The input validator combines neither duplicate rules nor conflicting probabilities: duplicate rules must be combined before estimating. Thus a supported lexical rewrite has a single weight. For a longer span, try every split k and every binary rule:

V(A,i,j)=max⁡i<k<jA→BC{log⁡θA→BC+V(B,i,k)+V(C,k,j)}.V(A,i,j)=\max_{\substack{i<k<j\\A\to BC}}\{\log\theta_{A\to BC}+V(B,i,k)+V(C,k,j)\}.

Because both children are shorter than the parent, fill spans in increasing length. Store the winning split and rule as backpointers. The root score V(S,0,n) is a number; following its pointers recovers a tree. A maximum value and its maximizing tree are different outputs. For ties, the code keeps the first successful candidate in its rule/split traversal order. PCFG notes, CKY algorithm

The recurrence is exact under these assumptions: a best parent tree cannot contain a worse child tree when the child’s label and span are fixed, because replacing that child preserves the parent rule and improves the product. That is the reusable subproblem CKY stores.

Inside: sum alternatives instead

Let I(A,i,j) be the total probability mass of all positive-probability trees for the cell. Its recurrence is:

I(A,i,j)=∑i<k<jA→BCθA→BC I(B,i,k) I(C,k,j).I(A,i,j)=\sum_{\substack{i<k<j\\A\to BC}}\theta_{A\to BC}\,I(B,i,k)\,I(C,k,j).

The lexical base is the matching rule weight and a missing cell has mass zero. The implementation keeps log I and adds candidates using stable log-add-exp. It does not approximate the sum by the best tree. For a positive root mass, a tree’s posterior given this sentence is:

P(T∣w0:n)=P(T)I(S,0,n).P(T\mid w_{0:n})=\frac{P(T)}{I(S,0,n)}.

This is defined only for a tree with that yield and nonzero denominator. A small best-tree probability might reflect many rule factors; it is not itself a calibrated “confidence” in the chosen reading. Compare it with the total mass for the same sentence. PCFG notes, inside probabilities

The chart also counts positive-probability trees. Set a matching lexical cell’s count to one, and use:

N(A,i,j)=∑i<k<jA→BC,θA→BC>0N(B,i,k)N(C,k,j).N(A,i,j)=\sum_{\substack{i<k<j\\A\to BC,\;\theta_{A\to BC}>0}}N(B,i,k)N(C,k,j).

Each binary tree has a unique root rule and split, so these cases do not double count it. Zero-weight rules may be syntactically present but contribute no positive tree. Counting every leftmost and rightmost expansion order separately would be another quantity; our count is of trees, equivalently unique leftmost derivations.

Local normalization is not a termination proof

Consider just S→S S with probability 3/4 and S→a with probability 1/4. The rules sum to one, but expansion may continue forever. If q is the probability of eventually producing a finite tree, a lexical expansion succeeds immediately and a binary expansion requires both independent children to finish:

q=14+34q2.q=\frac14+\frac34q^2.

The two fixed points are 1/3 and 1. The relevant value is the least nonnegative fixed point, 1/3: start q_0=0 and repeatedly apply the right-hand side to count finite trees of increasing height. These events increase to the event of any finite tree. Choosing the root 1 merely because “probabilities should sum to one” would assume the conclusion that fails here.

For a sentence consisting of n copies of a, every full binary tree has n lexical rules and n−1 binary rules. The number of ordered shapes is the Catalan number C_(n−1), so:

Cn−1=1n(2n−2n−1),P(an)=Cn−1(34)n−1(14)n.C_{n-1}=\frac1n\binom{2n-2}{n-1},\qquad P(a^n)=C_{n-1}\left(\frac34\right)^{n-1}\left(\frac14\right)^n.

The parser’s masses for lengths one through ten sum to approximately 0.332654, below 1/3. The missing mass is not just longer sentences: two-thirds belongs to non-terminating derivations. This example separates local rule validation from consistency of the whole generative grammar. It is an original calculation, not a claim that the cited lecture notes’ example grammar has this problem.

Build both telescope readings

Save the following program as constituency.py and run python constituency.py with Python 3.12.4. It uses only the standard library. The complete invented grammar has 13 rules: six binary and seven lexical. NP can expand as I, DET N, or NP PP; VP can expand as V NP or VP PP. These choices permit both attachments in the seven-token example.

"""Original CNF PCFG example: Viterbi tree, inside mass and positive parse count.

Local rule normalization does not certify almost-sure finite derivation.
No unary/epsilon rules, grammar conversion, lexical backoff or treebank data.
"""
from collections import Counter
import json,math


def symbol(value):
    if not isinstance(value,str) or not value or any(c.isspace() or 0xD800<=ord(c)<=0xDFFF for c in value):raise ValueError('Nonempty grammar symbol without whitespace required')
    return value


def grammar(rules,start='S'):
    symbol(start)
    if not isinstance(rules,(list,tuple)) or not rules:raise ValueError('Rule collection required')
    rows=[];seen=set();totals=Counter()
    for rule in rules:
        if not isinstance(rule,(list,tuple)) or len(rule)!=3:raise ValueError('Rule is lhs, rhs, probability')
        lhs,rhs,p=rule;symbol(lhs)
        if not isinstance(rhs,(list,tuple)) or len(rhs) not in (1,2):raise ValueError('Only CNF binary or terminal rules supported')
        rhs=tuple(symbol(x) for x in rhs)
        if isinstance(p,bool) or not isinstance(p,(int,float)) or not math.isfinite(p) or not 0<=p<=1:raise ValueError('Probability in [0,1] required')
        if (lhs,rhs) in seen:raise ValueError('Duplicate rule; combine counts before estimating')
        rows.append((lhs,rhs,float(p)));seen.add((lhs,rhs));totals[lhs]+=p
    nonterminals=set(totals)
    if start not in nonterminals or any(not math.isclose(v,1,rel_tol=0,abs_tol=1e-12) for v in totals.values()):raise ValueError('Start symbol and locally normalized rules required')
    for _,rhs,_ in rows:
        if len(rhs)==1 and rhs[0] in nonterminals:raise ValueError('Unary nonterminal rule is not CNF')
        if len(rhs)==2 and any(x not in nonterminals for x in rhs):raise ValueError('Binary children must be nonterminals')
    return {'start':start,'rules':rows,'nonterminals':sorted(nonterminals)}


def estimate(trees,start='S'):
    if not isinstance(trees,(list,tuple)) or not trees:raise ValueError('Annotated trees required')
    counts=Counter();totals=Counter()
    def visit(tree):
        if not isinstance(tree,(list,tuple)) or len(tree) not in (2,3):raise ValueError('CNF tree node required')
        lhs=symbol(tree[0])
        if len(tree)==2:rhs=(symbol(tree[1]),)
        else:rhs=(visit(tree[1]),visit(tree[2]))
        counts[lhs,rhs]+=1;totals[lhs]+=1;return lhs
    for tree in trees:
        if visit(tree)!=start:raise ValueError('Every training tree must have the declared root')
    return grammar([(lhs,rhs,count/totals[lhs]) for (lhs,rhs),count in sorted(counts.items())],start)


def logadd(a,b):
    if a==-math.inf:return b
    if b==-math.inf:return a
    return max(a,b)+math.log1p(math.exp(-abs(a-b)))


def parse(model,words,max_tokens=60):
    model=grammar(model['rules'],model['start'])
    if not isinstance(words,(list,tuple)) or type(max_tokens) is not int or max_tokens<1:raise ValueError('Tokens and positive budget required')
    words=[symbol(w) for w in words];n=len(words)
    if n>max_tokens:raise ValueError('Explicit teaching token budget exceeded; input was not truncated')
    chart={};back={};attempts=0
    lexical=[r for r in model['rules'] if len(r[1])==1 and r[2]>0]
    binary=[r for r in model['rules'] if len(r[1])==2 and r[2]>0]
    for i,word in enumerate(words):
        for lhs,(terminal,),p in lexical:
            if word==terminal:chart[i,i+1,lhs]=(math.log(p),math.log(p),1);back[i,i+1,lhs]=word
    for width in range(2,n+1):
        for i in range(n-width+1):
            j=i+width
            for split in range(i+1,j):
                for lhs,(left,right),p in binary:
                    attempts+=1;a=chart.get((i,split,left));b=chart.get((split,j,right))
                    if a is None or b is None:continue
                    key=(i,j,lhs);old=chart.get(key,(-math.inf,-math.inf,0));weight=math.log(p)
                    best=weight+a[0]+b[0];mass=weight+a[1]+b[1]
                    chart[key]=(max(old[0],best),logadd(old[1],mass),old[2]+a[2]*b[2])
                    if best>old[0]:back[key]=(split,left,right)
    root=(0,n,model['start']);value=chart.get(root)
    cells=[{'start':i,'end':j,'label':x,'best_log_probability':v[0],'inside_log_probability':v[1],'positive_tree_count':v[2]} for (i,j,x),v in sorted(chart.items())]
    if value is None:return {'status':'no_positive_parse','tree':None,'best_log_probability':None,'inside_log_probability':None,'positive_tree_count':0,'chart':cells,'binary_rule_attempts':attempts}
    def recover(i,j,lhs):
        entry=back[i,j,lhs]
        if j==i+1:return (lhs,entry)
        split,left,right=entry;return (lhs,recover(i,split,left),recover(split,j,right))
    return {'status':'ok','tree':recover(*root),'best_log_probability':value[0],'inside_log_probability':value[1],
            'positive_tree_count':value[2],'chart':cells,
            'binary_rule_attempts':attempts}


def tree_probability(model,tree):
    model=grammar(model['rules'],model['start']);weights={(lhs,rhs):p for lhs,rhs,p in model['rules']}
    def visit(node):
        if not isinstance(node,(list,tuple)) or len(node) not in (2,3):raise ValueError('CNF tree required')
        if len(node)==2:
            lhs,word=map(symbol,node);return lhs,[word],weights.get((lhs,(word,)),0.)
        lhs,a,b=node;symbol(lhs);left,lwords,lp=visit(a);right,rwords,rp=visit(b)
        return lhs,lwords+rwords,weights.get((lhs,(left,right)),0.)*lp*rp
    label,words,p=visit(tree)
    if label!=model['start']:raise ValueError('Wrong root')
    return {'words':words,'probability':p}


def demo():
    rules=[('S',('NP','VP'),1),('NP',('I',),.2),('NP',('DET','N'),.5),('NP',('NP','PP'),.3),
           ('VP',('V','NP'),.6),('VP',('VP','PP'),.4),('PP',('P','NP'),1),('DET',('the',),.5),('DET',('a',),.5),
           ('N',('man',),.5),('N',('telescope',),.5),('V',('saw',),1),('P',('with',),1)]
    model=grammar(rules);words=['I','saw','the','man','with','a','telescope'];result=parse(model,words)
    branching=grammar([('S',('S','S'),.75),('S',('a',),.25)])
    masses=[math.exp(parse(branching,['a']*n)['inside_log_probability']) for n in range(1,11)]
    extinction=[0.]
    for _ in range(30):extinction.append(.25+.75*extinction[-1]**2)
    return {'rules':rules,'words':words,'result':result,'tree_check':tree_probability(model,result['tree']),
            'unknown':parse(model,['I','saw','birds']),'empty':parse(model,[]),
            'branching_counterexample':{'binary_probability':.75,'terminal_probability':.25,'length_masses_1_to_10':masses,'partial_mass':sum(masses),'finite_height_probabilities':extinction,'least_fixed_point':1/3},
            'scope':'Original CNF grammar and seven-token attachment ambiguity; exact positive derivation count, log-space Viterbi and inside. No epsilon/unary closure, treebank preprocessing or benchmark. Locally normalized rules may leave probability on infinite derivations.'}
if __name__=='__main__':print(json.dumps(demo(),ensure_ascii=False,indent=2,allow_nan=False))

The two trees have the following masses under the stated grammar:

AttachmentJoint tree probabilityPosterior among these two trees
PP attaches to VP3/4000 = 0.000754/7
PP attaches within NP9/16000 = 0.00056253/7

Their sum is 21/16000=0.0013125. The preferred VP structure allows the instrument reading, but the preference comes from the supplied rule weights, not visual evidence that a telescope was used. The program returns the complete nested tree, its independently recomputed yield and probability, the inside mass and the count two.

The estimate function can instead derive a grammar from supplied CNF trees. It counts each expansion under its parent symbol, as in the two-tree example above. It does not smooth unseen words or rules. An unknown word can prevent any full parse even when other cells in the chart are valid. no_positive_parse therefore keeps the partial chart for diagnosis; it does not imply that the input is ungrammatical English.

For n words, B positive binary rules and L positive lexical rules, this implementation makes B×binomial(n+1,3) binary attempts and O(nL) lexical checks. Thus its chart computation takes O(n³B+nL) arithmetic operations and O(n²|N|) cell storage, with N the nonterminal set. The seven-word demo makes 6×56=336 binary attempts. Exact Python integer tree counts can grow large, so treating each integer operation as unit cost is not a bit-complexity bound.

The default token budget is 60. Longer input raises an error and is not truncated. Empty input has no tree under this no-empty-rule grammar. Log space preserves finite log masses even when converting a tiny probability back with exp underflows to zero; the existence of a positive tree is tracked separately from that conversion.

Grammar coverage and annotation are part of the result

A treebank records an annotation scheme, not every conceivable analysis of language. The Penn Treebank paper describes an automatic first parse followed by human correction, including attachment of initially unconnected chunks. Its syntactic categories were shaped partly by practical annotation constraints. That history matters when deciding which structure a parser is expected to reproduce. Penn Treebank, §4.1–4.2 opening

Our seven-word grammar covers only a few supplied words and constructions. It has no lexical backoff, parent annotation, learned contextual scores, discontinuous constituents or general CNF conversion. A probabilistic preference can be linguistically wrong because the grammar omits an analysis or because its independence assumptions discard relevant evidence. Adding richer context changes model assumptions; it should be tested against the same tree and token conventions.

For evaluation, a simple declared measure compares labeled brackets (start,end,label) between predicted and gold trees. Precision and recall depend on which brackets are included: root, preterminal labels, punctuation and artificial binarization nodes all require a policy. Keep tokenization and these choices fixed before comparing numbers. The demonstration does not implement an official treebank scorer or claim a bracket F1 result.

Parsing can help inspect sentence structure or supply features to later extraction and interpretation. Whether it helps an application should be tested against a simpler baseline on that application’s errors. A parse is not a complete semantic representation: the preferred attachment alone does not resolve every word sense, referent or real-world fact.

Ask what has been counted

  1. Understanding. What changes between the two telescope readings if the words and their order are identical?

Answer: The PP’s attachment changes. It either groups with the VP about seeing or inside the NP about the man. The structure changes the possible interpretation; no word needs to move or acquire a new spelling.

  1. Hand calculation. Given tree masses 3/4000 and 9/16000, what are the sentence mass and best-tree posterior?

Answer: Convert the first to 12/16000 and add to obtain 21/16000. The best-tree posterior is 12/21=4/7. Returning 3/4000 as the conditional confidence would omit normalization over the competing tree.

  1. Counterexample. Both 1/3 and 1 solve q=1/4+3q²/4. Why is 1/3 the finite-derivation probability?

Answer: Starting at zero and iterating the expansion equation counts success within increasing finite heights. The resulting probabilities rise toward 1/3, the least fixed point. The other solution does not describe the union of those finite events; local normalization does not force termination.

  1. Transfer. A treebank contains A→B unary rules and words absent from the training vocabulary. Can this program silently drop unary nodes and replace every unknown word to produce a comparable score?

Answer: No. Both changes alter the grammar or tree representation. Define a conversion that handles unary structure, preserves the intended probability mass and recovers evaluation labels; learn an explicit unknown-word policy from allowed data. Use the same transformation for training and evaluation and document which brackets are scored. The current implementation rejects unsupported rules rather than doing that work invisibly.

From annotated trees to auditable chart entries

Michael Collins’s PCFG notes, accessed through a Cornell course copy, support local rule probabilities, supervised estimation, CNF, CKY and inside computation. This chapter inspected those specific sections, including the page containing the CKY recurrence; the copy’s exact original publication date has not been verified. The year in a course URL is not used as a substitute for that date. Lecture notes

Mitchell P. Marcus, Beatrice Santorini and Mary Ann Marcinkiewicz’s 1993 Penn Treebank paper supports the annotation-workflow discussion. The newly inspected scope is the introduction and §4.1–4.2 opening, not a full review of corpus statistics, annotation manuals or distributions. No treebank data was downloaded or used by this program. Corpus paper

Independent checks enumerate leftmost derivations without a span chart, compare Catalan counts and probabilities, reconstruct tree yields, verify the two attachment masses, and test missing words, zero weights, empty input, non-CNF rejection and numerical underflow. Those checks establish this parser’s stated behavior. They do not turn a small grammar into a full natural-language parser.

Make a prediction, then check

Two trees have masses 3/4000 and 9/16000. What is the best tree posterior given this sentence?

Choose one answer

Learning objectives

  • Represent attachment ambiguity with labeled phrase trees.
  • Estimate PCFG rule probabilities from annotated CNF trees.
  • Distinguish Viterbi tree, inside mass and positive-tree count.
  • Explain why locally normalized rules can have nonterminating derivations.

Prerequisites & connections

Explore related knowledge →

References

  1. Probabilistic Context-Free Grammars, Cornell-hosted Michael Collins lecture notes
    Michael Collins
  2. Building a Large Annotated Corpus of English: The Penn Treebank
    Mitchell P. Marcus; Beatrice Santorini; Mary Ann Marcinkiewicz · 1993

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-12 · Codex single-AI-author technical check: scoped Collins PCFG notes and Penn Treebank introduction/annotation; nine paired equations and four explained exercises. CNF binary/lexical CKY, log-space Viterbi/inside, positive tree counts and partial chart semantics. Independent derivation/Catalan oracle, 4/7 attachment posterior, local rule normalization versus finite-tree mass 1/3, boundaries and underflow. No real-treebank or full grammar conversion implementation.

  • Codex single-AI-author technical check: scoped Collins PCFG notes and Penn Treebank introduction/annotation; nine paired equations and four explained exercises. CNF binary/lexical CKY, log-space Viterbi/inside, positive tree counts and partial chart semantics. Independent derivation/Catalan oracle, 4/7 attachment posterior, local rule normalization versus finite-tree mass 1/3, boundaries and underflow. No real-treebank or full grammar conversion implementation.
  • Four original SVGs bind the exact MDX program. Nine figure tests validate numeric results, encodings and dependency arc geometry. Thirty standalone language/width cases and four fallback fonts passed; ten desktop/mobile screenshots were actually inspected. The original false arc crossing and its correction evidence are preserved. Complete article browser acceptance is separate; no human peer review or upstream execution.

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.