蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

运行 CFG 短语解析与依存树校验、词干 vs 词形还原、中文分词歧义与加一平滑二元模型实验

PYTHONWindows x64 CPU、CPython 3.12.14、NumPy 2.5.4、SciPy 1.18.1、scikit-learn 1.9.1、pandas 3.1.0、Matplotlib 3.11.2。explore-linguistics-basics.py
explore-linguistics-basics.py292 行
"""Independent offline NLP lab for Ch 03 (Linguistics Basics): CFG/dependency parsing, stemming vs lemma, Chinese seg ambiguity, N-gram LM."""
import json
import math
import platform
from collections import Counter


# Exact CFG rules from source CODE 0
CFG_RULES = {
    "S": [("NP", "VP")],
    "NP": [("Det", "N")],
    "VP": [("V", "NP")],
}
CFG_LEX = {
    "Det": {"the", "a", "an"},
    "N": {"cat", "dog", "book"},
    "V": {"chase", "read"},
}


def parse_cfg(symbol, tokens, pos):
    if symbol in CFG_LEX:
        if pos < len(tokens) and tokens[pos] in CFG_LEX[symbol]:
            return [(f"({symbol} {tokens[pos]})", pos + 1)]
        return []
    results = []
    for rhs in CFG_RULES.get(symbol, []):
        partials = [([], pos)]
        for part in rhs:
            next_partials = []
            for trees, idx in partials:
                for subtree, nxt in parse_cfg(part, tokens, idx):
                    next_partials.append((trees + [subtree], nxt))
            partials = next_partials
        for trees, end_pos in partials:
            results.append((f"({symbol} {' '.join(trees)})", end_pos))
    return results


def simple_porter_stem(word: str) -> str:
    w = word.lower()
    if w.endswith("ing") and len(w) > 5:
        base = w[:-3]
        if len(base) >= 2 and base[-1] == base[-2]:
            base = base[:-1]
        return base
    if w.endswith("s") and not w.endswith("ss") and len(w) > 3:
        return w[:-1]
    return w


LEMMA_DICT = {
    ("running", "VERB"): "run",
    ("runs", "VERB"): "run",
    ("ran", "VERB"): "run",
    ("children", "NOUN"): "child",
    ("books", "NOUN"): "book",
}


def english_plural_phoneme(word: str) -> str:
    w = word.lower()
    if w.endswith(("ses", "zes", "ches", "shes", "xes")):
        return "/ɪz/"
    stem = w[:-1] if w.endswith("s") else w
    if stem and stem[-1] in {"p", "t", "k", "f"}:
        return "/s/"
    return "/z/"


def fmm_segment(text: str, vocab: set, max_len: int = 5):
    res, i, n = [], 0, len(text)
    while i < n:
        matched = None
        for l in range(min(max_len, n - i), 0, -1):
            piece = text[i:i + l]
            if piece in vocab or l == 1:
                matched = piece
                break
        res.append(matched)
        i += len(matched)
    return res


def bmm_segment(text: str, vocab: set, max_len: int = 5):
    res, i = [], len(text)
    while i > 0:
        matched = None
        for l in range(min(max_len, i), 0, -1):
            piece = text[i - l:i]
            if piece in vocab or l == 1:
                matched = piece
                break
        res.append(matched)
        i -= len(matched)
    return list(reversed(res))


def run_cases():
    cases = []

    # 1. CFG constituent parsing (CODE 0) & Dependency tree validation (CODE 1)
    tokens = ["the", "cat", "chase", "a", "dog"]
    parses = [tree for tree, end in parse_cfg("S", tokens, 0) if end == len(tokens)]
    invalid_parses = [tree for tree, end in parse_cfg("S", ["cat", "the", "chase"], 0) if end == 3]

    # Dependency graph for "小猫追老鼠" with word/morpheme attachments matching source CODE 1
    dep_edges = [
        ("追", "ROOT", "root"),
        ("小猫", "追", "nsubj"),
        ("老鼠", "追", "dobj"),
        ("小", "小猫", "amod"),
    ]
    roots = [dep for dep, head, _ in dep_edges if head == "ROOT"]
    nodes = {dep for dep, _, _ in dep_edges}
    all_heads_valid = all(head == "ROOT" or head in nodes for _, head, _ in dep_edges)
    # Check cycle-free tree via depth traversal
    parent_map = {dep: head for dep, head, _ in dep_edges}
    depths = {}
    for node in nodes:
        cur, d = node, 0
        while parent_map[cur] != "ROOT" and d <= len(nodes):
            cur = parent_map[cur]
            d += 1
        depths[node] = d
    acyclic = all(d < len(nodes) for d in depths.values())
    c1_ok = (
        len(parses) == 1
        and parses[0] == "(S (NP (Det the) (N cat)) (VP (V chase) (NP (Det a) (N dog))))"
        and len(invalid_parses) == 0
        and roots == ["追"]
        and all_heads_valid
        and acyclic
        and max(depths.values()) == 2
    )
    cases.append(dict(
        name="cfg_and_dependency_parsing",
        inputs=dict(cfg_sentence=" ".join(tokens), dep_sentence="小猫追老鼠"),
        prerequisites="载入短语结构文法规则(S→NP VP 等)与“小猫追老鼠”依存关系边集。",
        action="执行递归下降短语结构解析并校验非法语序拒识;同时校验依存树单根性、无环性与深度。",
        expected=dict(valid_cfg_parsed=True, invalid_rejected=True, dep_tree_valid=True, max_depth_2=True),
        actual=dict(
            valid_cfg_parsed=(len(parses) == 1 and parses[0] == "(S (NP (Det the) (N cat)) (VP (V chase) (NP (Det a) (N dog))))"),
            invalid_rejected=(len(invalid_parses) == 0),
            dep_tree_valid=(roots == ["追"] and all_heads_valid and acyclic),
            max_depth_2=(max(depths.values()) == 2),
        ),
        measurements=dict(
            constituent_tree=parses[0],
            dep_root=roots[0],
            dep_depths=depths,
        ),
        passed=c1_ok,
    ))

    # 2. Morphology: Porter-style suffix stemming vs Lemmatization (+ phonological plural rule)
    forms = ["running", "runs", "ran"]
    stems = {w: simple_porter_stem(w) for w in forms}
    lemmas = {w: LEMMA_DICT[(w, "VERB")] for w in forms}
    plurals = {w: english_plural_phoneme(w) for w in ["cats", "dogs", "horses"]}
    # Key factual correction: Porter stemmer maps running/runs -> run, but leaves irregular 'ran' as 'ran'
    c2_ok = (
        stems == {"running": "run", "runs": "run", "ran": "ran"}
        and lemmas == {"running": "run", "runs": "run", "ran": "run"}
        and plurals == {"cats": "/s/", "dogs": "/z/", "horses": "/ɪz/"}
    )
    cases.append(dict(
        name="morphology_stem_vs_lemma",
        inputs=dict(verb_forms=forms, plural_words=["cats", "dogs", "horses"]),
        prerequisites="对比规则切缀词干提取与词典词性词形还原,并验证英语复数清浊/咝音音韵规则。",
        action="测试 running/runs/ran 在词干提取与词形还原上的差异,以及 cats/dogs/horses 的复数尾音。",
        expected=dict(stem_leaves_ran_unchanged=True, lemma_normalizes_all_three=True, plural_phonology_exact=True),
        actual=dict(
            stem_leaves_ran_unchanged=(stems["running"] == "run" and stems["runs"] == "run" and stems["ran"] == "ran"),
            lemma_normalizes_all_three=(lemmas == {"running": "run", "runs": "run", "ran": "run"}),
            plural_phonology_exact=(plurals == {"cats": "/s/", "dogs": "/z/", "horses": "/ɪz/"}),
        ),
        measurements=dict(stems=stems, lemmas=lemmas, plural_phonemes=plurals),
        passed=c2_ok,
    ))

    # 3. Chinese word segmentation ambiguity: FMM vs BMM + bigram probability disambiguation
    vocab = {
        "结婚", "结婚的", "和", "和尚", "尚未", "未", "的",
        "长春", "长春市", "市长", "药店", "春药店",
        "乒乓球", "乒乓球拍", "拍卖", "卖完了", "完了",
    }
    s_comb = "结婚的和尚未结婚的"
    fmm_comb = fmm_segment(s_comb, vocab)
    bmm_comb = bmm_segment(s_comb, vocab)

    s_overlap = "长春市长春药店"
    fmm_overlap = fmm_segment(s_overlap, vocab)
    bmm_overlap = bmm_segment(s_overlap, vocab)

    # Bigram scoring disambiguates combinatorial ambiguity
    bigram_logp = {
        ("结婚的", "和"): -1.2, ("和", "尚未"): -1.5, ("尚未", "结婚的"): -1.3,
        ("结婚的", "和尚"): -6.5, ("和尚", "未"): -5.0, ("未", "结婚的"): -3.0,
    }
    cand_correct = ["结婚的", "和", "尚未", "结婚的"]
    cand_wrong = ["结婚的", "和尚", "未", "结婚的"]
    score_correct = sum(bigram_logp[(cand_correct[i], cand_correct[i + 1])] for i in range(len(cand_correct) - 1))
    score_wrong = sum(bigram_logp[(cand_wrong[i], cand_wrong[i + 1])] for i in range(len(cand_wrong) - 1))

    c3_ok = (
        fmm_comb == ["结婚的", "和尚", "未", "结婚的"]
        and bmm_comb == ["结婚的", "和", "尚未", "结婚的"]
        and fmm_overlap != bmm_overlap
        and score_correct > score_wrong
    )
    cases.append(dict(
        name="chinese_segmentation_ambiguity",
        inputs=dict(combinatorial=s_comb, overlapping=s_overlap, vocab_size=len(vocab)),
        prerequisites="构建包含组合歧义词项与交集歧义词项的中文词表。",
        action="分别运行正向最大匹配(FMM)、逆向最大匹配(BMM)与二元统计打分消歧。",
        expected=dict(fmm_hits_monk_trap=True, bmm_resolves_combinatorial=True, overlap_diverges=True, bigram_picks_correct=True),
        actual=dict(
            fmm_hits_monk_trap=(fmm_comb == ["结婚的", "和尚", "未", "结婚的"]),
            bmm_resolves_combinatorial=(bmm_comb == ["结婚的", "和", "尚未", "结婚的"]),
            overlap_diverges=(fmm_overlap != bmm_overlap),
            bigram_picks_correct=(score_correct > score_wrong),
        ),
        measurements=dict(
            fmm_combinatorial=fmm_comb,
            bmm_combinatorial=bmm_comb,
            fmm_overlapping=fmm_overlap,
            bmm_overlapping=bmm_overlap,
            bigram_score_correct=round(score_correct, 3),
            bigram_score_wrong=round(score_wrong, 3),
        ),
        passed=c3_ok,
    ))

    # 4. Bigram language model with Add-1 (Laplace) smoothing
    corpus = [
        ["<s>", "the", "cat", "chased", "the", "mouse", "</s>"],
        ["<s>", "the", "dog", "chased", "the", "cat", "</s>"],
        ["<s>", "the", "cat", "liked", "the", "fish", "</s>"],
        ["<s>", "the", "mouse", "ate", "the", "cheese", "</s>"],
    ]
    unigrams = Counter()
    bigrams = Counter()
    for sent in corpus:
        for w in sent:
            unigrams[w] += 1
        for a, b in zip(sent, sent[1:]):
            bigrams[(a, b)] += 1
    vocab_lm = sorted(unigrams.keys())
    v_size = len(vocab_lm)

    def prob_add1(prev_w, cur_w):
        return (bigrams[(prev_w, cur_w)] + 1.0) / (unigrams[prev_w] + v_size)

    # Check normalization over all next words given "the"
    sum_given_the = sum(prob_add1("the", w) for w in vocab_lm)
    unseen_mle = bigrams[("mouse", "chased")] / unigrams["mouse"]
    unseen_smoothed = prob_add1("mouse", "chased")

    def sent_logp(seq):
        return sum(math.log(prob_add1(a, b)) for a, b in zip(seq, seq[1:]))

    lp_fluent = sent_logp(["<s>", "the", "cat", "chased", "the", "mouse", "</s>"])
    lp_shuffled = sent_logp(["<s>", "mouse", "the", "the", "chased", "cat", "</s>"])
    c4_ok = abs(sum_given_the - 1.0) < 1e-12 and unseen_mle == 0.0 and unseen_smoothed > 0.0 and lp_fluent > lp_shuffled
    cases.append(dict(
        name="ngram_smoothing_language_model",
        inputs=dict(corpus_sentences=len(corpus), vocab_size=v_size, smoothing="add-1"),
        prerequisites="在 4 条标注首尾标记的语料上统计一元与二元频次并应用加一平滑。",
        action="验证条件概率分布归一化为 1、未见二元组零概率经平滑变为正值,且流畅句对数概率高于乱序句。",
        expected=dict(cond_dist_sums_to_1=True, oov_bigram_smoothed_nonzero=True, fluent_beats_shuffled=True),
        actual=dict(
            cond_dist_sums_to_1=abs(sum_given_the - 1.0) < 1e-12,
            oov_bigram_smoothed_nonzero=(unseen_mle == 0.0 and unseen_smoothed > 0.0),
            fluent_beats_shuffled=(lp_fluent > lp_shuffled),
        ),
        measurements=dict(
            sum_prob_given_the=round(sum_given_the, 6),
            unseen_mle_prob=unseen_mle,
            unseen_add1_prob=round(unseen_smoothed, 6),
            fluent_log_prob=round(lp_fluent, 4),
            shuffled_log_prob=round(lp_shuffled, 4),
        ),
        passed=c4_ok,
    ))

    print(json.dumps(dict(version=platform.python_version(), system=platform.system(), cases=cases), ensure_ascii=False))


if __name__ == "__main__":
    run_cases()
本例需在 Windows x64 CPU、CPython 3.12.14、NumPy 2.5.4、SciPy 1.18.1、scikit-learn 1.9.1、pandas 3.1.0、Matplotlib 3.11.2。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows x64 CPU、CPython 3.12.14、NumPy 2.5.4、SciPy 1.18.1、scikit-learn 1.9.1、pandas 3.1.0、Matplotlib 3.11.2。

入口文件:projects/nlp-linguistics-basics-lab/explore-linguistics-basics.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-linguistics-basics.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64 CPU、CPython 3.12.14、NumPy 2.5.4、SciPy 1.18.1、scikit-learn 1.9.1、pandas 3.1.0、Matplotlib 3.11.2。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:自然语言处理 NLP

课程关联工程包(登记关联21章) · 含当前章节或实例 · mbskycom202612a545.zip

下载课程关联工程包:自然语言处理 NLP

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a551.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习