AI Wiki中文/EN

Chinese NLP: how characters, words and training units change results

中文 NLP 的特有问题

Connect annotation standards, glyphs and pinyin to span scoring, then derive how word expansion changes masking budgets.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

Decide what counts as a word

Imagine two teaching annotations of 南京市长江大桥, the name of a bridge in Nanjing. One groups it as 南京市 / 长江大桥; the other uses 南京市 / 长江 / 大桥. Every character survives, but the word spans differ. If a scorer accepts only the first annotation, the second loses points. That establishes agreement with an annotation policy; the score alone cannot decide which granularity suits every purpose. These are invented teaching policies, not official gold annotations from a SIGHAN corpus.

Chinese NLP must distinguish characters, words and model tokens. A word can contain several Chinese characters, while a model can consume characters or other subwords. Segmentation affects dictionary matching, annotation alignment, span scoring and whole-word masking. Emerson’s report on the 2005 SIGHAN bakeoff discusses the difficulty of defining word boundaries and records different annotation standards used by corpus providers. Word boundaries and annotation standards

Written representation has several layers too: encoding determines how characters are stored; normalization changes selected surface representations; segmentation groups the resulting text. These are different operations. The report describes practical problems with transcoding, extension characters and spaces in mixed Chinese and non-Chinese text. A pipeline should retain the original text, processing version and position unit; otherwise its predicted spans may not map back to what a reader sees. Concrete data-preparation problems Text normalization

Glyphs, pronunciation and meaning are another distinction. ChineseBERT combines character, glyph and pinyin representations, discussing different readings of 乐 and the uses of 还 meaning “return” or “also.” A glyph can provide evidence, but the same character ID cannot distinguish every pronunciation; supplying pinyin does not replace understanding the sentence either. These mechanisms illustrate representation choices here. The paper’s model results are not presented as this project’s results. Roles of glyph and pinyin information

The same seven-character text has two invented annotation granularities. Word and boundary F1 differ, while expanding character seeds to whole words increases the expected selection budget. Positions use code points.
The same seven-character text has two invented annotation granularities. Word and boundary F1 differ, while expanding character seeds to whole words increases the expected selection budget. Positions use code points.

How annotation granularity enters scoring and training

Let the text have nn positions, with left-closed, right-open spans. Both segmentations must reconstruct exactly the same source; they cannot independently rewrite it before comparison. PP is the predicted word-span set and GG the reference set. Repeated occurrences of the same word at different positions are different instances.

P={[aj,bj)}j=1∣P∣,0=a1<b1=a2<⋯<b∣P∣=n.P=\{[a_j,b_j)\}_{j=1}^{|P|},\qquad 0=a_1<b_1=a_2<\cdots<b_{|P|}=n.

Write m=∣P∩G∣m=|P\cap G|. Word precision asks how many predicted words match completely; recall asks how many reference words were recovered; F1 combines them. Here ∣P∣=3,∣G∣=2,m=1|P|=3,|G|=2,m=1, giving word F1 of 2/52/5. These word metrics connect to the P/R/F measures listed in the report; the span implementation and invented data here are original examples. Word and OOV evaluation measures

Prec⁡=m∣P∣,Rec⁡=m∣G∣,F1=2m∣P∣+∣G∣.\operatorname{Prec}=\frac{m}{|P|},\qquad \operatorname{Rec}=\frac{m}{|G|},\qquad F_1=\frac{2m}{|P|+|G|}.

For internal boundaries alone, the prediction places boundaries at positions 3 and 5 while the reference places one at 3, giving boundary F1 of 2/32/3. Sharing a boundary does not mean that the complete words on either side match. A one-word text has no internal boundary: the program returns None for relevant zero denominators rather than assigning full credit.

Granularity also enters pretraining objectives. ChineseBERT distinguishes character masking from whole-word masking: both can use character inputs, but the latter selects characters of the same word together. Identical input units do not imply identical hidden information during training. Masking strategies, section 4.2

Consider an easy implementation mistake: independently select each character with probability pp, then select every character of each word touched by a seed. Let BiB_i indicate whether character ii is initially selected and KK count seeds. Independence determines the distribution; linearity supplies the expectation.

Bi∼Bernoulli⁡(p) independently,K=∑i=1nBi,E[K]=np.B_i\sim\operatorname{Bernoulli}(p)\ \text{independently},\qquad K=\sum_{i=1}^{n}B_i,\qquad \mathbb E[K]=np.

A word of length ℓ\ell receives no seed with probability (1−p)ℓ(1-p)^\ell, so its probability of being selected after expansion is:

qℓ=Pr⁡(at least one seed in a word)=1−(1−p)ℓ.q_\ell=\Pr(\text{at least one seed in a word})=1-(1-p)^\ell.

Let word lengths be ℓj\ell_j, and let KwordK_{\mathrm{word}} count selected characters after expansion. Once a word is triggered, all its ℓj\ell_j characters contribute, giving:

E[Kword]=∑jℓj[1−(1−p)ℓj].\mathbb E[K_{\mathrm{word}}]=\sum_j\ell_j\bigl[1-(1-p)^{\ell_j}\bigr].

Longer words are more likely to receive at least one seed. At p=0.15p=0.15, the seven-character text initially has an expected 1.05 selected characters. Coarse lengths 3 and 4 produce 3.0696 after expansion; finer lengths 3, 2 and 2 produce 2.267625. This procedure cannot simply be described as “still masking 15%.” It also does not reproduce ChineseBERT’s stated procedures for sampling characters or words separately.

The original character selection can select only part of a word. Excluding the mutually exclusive events of selecting none and selecting all gives the partial-selection probability; JJ counts such words:

Pr⁡(partially selected word of length ℓ)=1−pℓ−(1−p)ℓ,E[J]=∑j[1−pℓj−(1−p)ℓj].\Pr(\text{partially selected word of length }\ell)=1-p^\ell-(1-p)^\ell,\qquad \mathbb E[J]=\sum_j\bigl[1-p^{\ell_j}-(1-p)^{\ell_j}\bigr].

For the coarse policy, E[J]=0.8599875\mathbb E[J]=0.8599875. That leaves other characters of the word available as clues; it does not guarantee a correct model prediction. The probability model describes an opportunity to expose information, not a language-understanding score.

Make position conventions executable

This complete Python program uses only the standard library. partition verifies source reconstruction; compare separately scores words and internal boundaries; expand computes the whole-word closure of selected positions; masking enumerates every character-selection mask and weights it by its actual probability. It trains no segmenter, pinyin model, glyph encoder or language model, and does not implement BERT’s 80/10/10 replacement rule.

"""Given Chinese annotation policies: span scores and exact masking consequences.

No tokenizer, pinyin resolver, glyph encoder or pretrained model is trained.
All positions count Python Unicode code points, not UTF-16 units or graphemes.
"""
from itertools import product
import json
import math


def partition(text, words):
    if not isinstance(text, str) or not 1 <= len(text) <= 12:
        raise ValueError('Use 1–12 Unicode code points')
    if not isinstance(words, (list, tuple)) or not words or any(not isinstance(w, str) or not w for w in words):
        raise ValueError('Use nonempty words')
    if ''.join(words) != text:
        raise ValueError('Words must reproduce the exact source')
    ends=[];offset=0
    for word in words:
        ends.append((offset,offset+len(word)));offset+=len(word)
    return tuple(ends)


def compare(text, predicted, gold):
    p=set(partition(text,predicted));g=set(partition(text,gold));matched=len(p & g)
    def score(hits, npred, ngold):
        precision=hits/npred if npred else None;recall=hits/ngold if ngold else None
        f1=2*hits/(npred+ngold) if npred+ngold else None
        return dict(matches=hits,predicted=npred,gold=ngold,precision=precision,recall=recall,f1=f1)
    pb={end for _,end in p if end<len(text)};gb={end for _,end in g if end<len(text)}
    return dict(word=score(matched,len(p),len(g)),boundary=score(len(pb & gb),len(pb),len(gb)))


def expand(text, words, selected):
    spans=partition(text,words)
    if not isinstance(selected, (list,tuple,set,frozenset)) or any(type(i) is not int or not 0<=i<len(text) for i in selected):
        raise ValueError('Selected code-point indices must be in range')
    selected=set(selected)
    return sorted(i for start,end in spans if any(j in selected for j in range(start,end)) for i in range(start,end))


def masking(text, words, probability=.15):
    spans=partition(text,words)
    if isinstance(probability,bool) or not isinstance(probability,(int,float)) or not math.isfinite(probability) or not 0<=probability<=1:
        raise ValueError('A finite probability in [0,1] is required')
    n=len(text);p=probability;expected_chars=expected_expanded=expected_partial=mass=0.
    # Enumerate every independent character-selection mask, then expand its words.
    for bits in product((0,1),repeat=n):
        k=sum(bits);weight=p**k*(1-p)**(n-k);mass+=weight
        selected={i for i,b in enumerate(bits) if b};grown=expand(text,words,selected)
        partial=sum(0<sum(bits[start:end])<end-start for start,end in spans)
        expected_chars+=weight*k;expected_expanded+=weight*len(grown);expected_partial+=weight*partial
    lengths=[end-start for start,end in spans]
    return dict(states=2**n,mass=mass,expected_selected=expected_chars,expected_expanded=expected_expanded,
                expected_partial_words=expected_partial,closed_selected=n*p,
                closed_expanded=sum(length*(1-(1-p)**length) for length in lengths),
                closed_partial=sum(1-p**length-(1-p)**length for length in lengths),
                scope='Independent character selection followed by word closure, not the ChineseBERT sampling algorithm or BERT 80/10/10 replacement.')


def demo():
    text='南京市长江大桥';coarse=['南京市','长江大桥'];fine=['南京市','长江','大桥']
    return dict(text=text,policies=dict(coarse=coarse,fine=fine),scores=compare(text,fine,coarse),
                single_seed=dict(index=3,coarse=expand(text,coarse,[3]),fine=expand(text,fine,[3])),
                coarse=masking(text,coarse),fine=masking(text,fine),
                code_points=dict(text='𠮷野家',python_length=len('𠮷野家'),utf16_units=len('𠮷野家'.encode('utf-16-le'))//2))


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

The program accepts at most 12 Python Unicode code points, yielding 2n2^n masks. Closure and counting take O(n)O(n) per mask, so total time is O(n2n)O(n2^n) with O(n)O(n) working space. This checks small examples; training corpora should generate instances with a stated sampling procedure instead of enumerating every mask.

Run python chinese.py. First inspect word F1 of 0.4 and boundary F1 of approximately 0.666667. Then inspect seed position 3: the coarse policy expands it to 3, 4, 5 and 6, whereas the fine policy expands it only to 3 and 4. Enumerated expectations should match the closed_* expressions. The string 𠮷野家 has 3 Python code points but 4 UTF-16 code units, reminding us that front-end and back-end positions cannot be interchanged directly; neither number is a byte count.

Character inputs still require linguistic conventions

Character models reduce some dependencies on explicit word-vocabulary segmentation, but text processing, supervision granularity and evaluation protocols still require choices. Select glyph, pinyin or whole-word features through error analysis: adding glyph information may not repair broken position mapping, while hard-coding one dictionary pronunciation loses information when a character’s reading depends on context. Contextual pronunciation and representation fusion

Successful transcoding does not establish that all task information survived. Preserve a traceable connection to the source, then align prediction and reference granularity. When annotations cannot be compared under one protocol, explain the difference before scoring; changing a scorer merely to raise the number is uninformative. Open vocabulary, names, domain shifts and mixed-language text also deserve separate diagnostic slices. Aggregate F1 cannot replace them. Preparation and in-/out-of-vocabulary measures

The masking calculation isolates one causal chain: segmentation, selection unit and exposed information. It does not establish which segmentation trains a better model. A training comparison must also control data, steps and actual prediction budgets, then evaluate downstream tasks under the same protocol. The official ChineseBERT project illustrates how a real pipeline is organized; its model code was neither copied nor executed here. Pinned project reference

Four judgments to carry into another task

  1. Why can word F1 differ when two systems preserve exactly the same character sequence?

Answer: Word scoring compares complete spans at specified positions. Different grouping can yield different words even when every character survives. Establish the task’s annotation convention before judging errors; character agreement does not establish word-level correctness.

  1. Calculate word F1 and internal-boundary F1 for the fine prediction against the coarse reference.

Answer: Three predicted words and two reference words share only the 南京市 span, giving 2/(3+2)=0.42/(3+2)=0.4. Two predicted internal boundaries and one reference boundary share one position, giving 2/(2+1)=2/32/(2+1)=2/3. The scores answer different questions.

  1. At p=0p=0 or p=1p=1, what is the expected number of partially selected words? Does expanding seeds twice change the result?

Answer: Both endpoints yield no partially selected words: every word is entirely unselected or entirely selected. Whole-word closure is idempotent. The first expansion includes every position of each triggered word, so another expansion adds nothing. The program checks both probability endpoints and closure properties.

  1. What are the expected selected-character count and variance if the two coarse words are independently selected with probability 0.15, instead of selecting characters and expanding?

Answer: Each word contributes its length times a selection indicator. The expectation is (3+4)0.15=1.05(3+4)0.15=1.05, while the variance is (32+42)0.15(1−0.15)=3.1875(3^2+4^2)0.15(1-0.15)=3.1875. Independent character selection has variance only 7(0.15)(0.85)=0.89257(0.15)(0.85)=0.8925. Equal expectations can hide different fluctuations, another reason to report selection units as well as masking rates. This exercise is an independent derivation; the main program implements character selection followed by closure.

From word-boundary protocols to multiple representations

The SIGHAN report provides a concrete historical view: evaluation depends on corpus standards, encoding and processing details. Scores across standards cannot directly establish language difficulty. ChineseBERT presents a different set of choices involving characters, glyphs, pinyin and masking. The works are years apart and address different questions; they are not an inevitable sequence of replacements. Original evaluation report Pretraining method

Continue with tokenization for input units and Bernoulli and binomial distributions to recompute selection probabilities. The source notes below state the actual reading scope; downloading a paper is not treated as reproducing its entire contents.

Make a prediction, then check

Does expanding independently selected character seeds to whole words preserve the original expected number of selected characters?

Choose one answer

Learning objectives

  • Distinguish characters, words, model tokens and position units.
  • Calculate word and boundary scores under a stated annotation policy.
  • Derive masking expansion and partial-word probabilities.
  • Separate representation choices from demonstrated downstream gains.

Prerequisites & connections

Explore related knowledge →

References

  1. The Second International Chinese Word Segmentation Bakeoff
    Thomas Emerson · 2005
  2. ChineseBERT: Chinese Pretraining Enhanced by Glyph and Pinyin Information
    Zijun Sun, Xiaoya Li, Xiaofei Sun, Yuxian Meng, Xiang Ao, Qing He, Fei Wu, Jiwei Li · 2021
  3. ChineseBERT official repository: pinned introductory README
    ShannonAI contributors · 2022

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-13 · Single AI author checked character/word/token distinctions against scoped Emerson standards and ChineseBERT representations/masking. Six paired equations and four explained exercises: exact position spans, word versus boundary F1, Bernoulli seeds, word closure and partial-selection probabilities, direct word-selection variance. The given annotation policies and character-seed closure do not reproduce a tokenizer or ChineseBERT training.

  • Verified exact reconstruction/Unicode positions, word/boundary F1, closure invariants and all bounded character masks against closed-form expectations. Independently enumerated direct word-selection variance 3.1875 versus character variance .8925. Source dimension inconsistency not inherited.
  • 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:

Related topics

No matches. Try a synonym or acronym.

0 results shown

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