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

运行上下文词义消歧、规则与统计意图分类对比、抽取式摘要与 BLEU-2 局限实验

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-intro.py
explore-intro.py258 行
"""Independent offline NLP lab for Ch 02 (NLP Intro): disambiguation, rule vs statistical intent, summary, BLEU limits."""
import json
import math
import platform
import re
from collections import Counter

import numpy as np
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score
from sklearn.metrics.pairwise import cosine_similarity
from sklearn.model_selection import train_test_split
from sklearn.pipeline import Pipeline


def compute_bleu2(candidate_tokens, reference_tokens):
    c_len = len(candidate_tokens)
    r_len = len(reference_tokens)
    if c_len == 0:
        return 0.0
    bp = 1.0 if c_len > r_len else math.exp(1.0 - r_len / c_len)
    precisions = []
    for n in (1, 2):
        cand_ngrams = Counter(tuple(candidate_tokens[i:i + n]) for i in range(c_len - n + 1))
        ref_ngrams = Counter(tuple(reference_tokens[i:i + n]) for i in range(r_len - n + 1))
        overlap = sum(min(cnt, ref_ngrams[ng]) for ng, cnt in cand_ngrams.items())
        total = max(sum(cand_ngrams.values()), 1)
        precisions.append(overlap / total)
    if any(p == 0.0 for p in precisions):
        return 0.0
    return bp * math.exp(0.5 * (math.log(precisions[0]) + math.log(precisions[1])))


def run_cases():
    cases = []

    # 1. Context-based lexical disambiguation for "bank" (English) and "苹果" (Chinese char n-grams)
    bank_train_texts = [
        "deposit cash loan interest rate credit account bank",
        "mortgage finance branch transfer savings money bank",
        "bank approved commercial business credit line payment",
        "river water flood trees boat fishing muddy bank",
        "sat along the grassy river bank watching ducks swim",
        "stream overflowed the steep sandy river bank after rain",
    ]
    bank_train_labels = ["finance", "finance", "finance", "river", "river", "river"]
    bank_test_texts = [
        "she transferred savings and paid the loan at the bank",
        "children walked along the muddy bank beside the river",
    ]
    bank_test_labels = ["finance", "river"]

    vec_en = TfidfVectorizer(stop_words="english")
    x_tr_en = vec_en.fit_transform(bank_train_texts)
    x_te_en = vec_en.transform(bank_test_texts)
    sims_en = cosine_similarity(x_te_en, x_tr_en)
    preds_en = []
    for row in sims_en:
        fin_score = float(np.mean(row[:3]))
        riv_score = float(np.mean(row[3:]))
        preds_en.append("finance" if fin_score >= riv_score else "river")

    apple_train_texts = [
        "新鲜红苹果香甜多汁水果超市现摘",
        "切开苹果果肉清脆酸甜可口水果",
        "买了一袋富士苹果水分足味道甜",
        "苹果公司发布新款芯片与智能手机产品",
        "苹果季度营收与市值创下科技行业新高",
        "苹果系统升级优化手机续航与处理器性能",
    ]
    apple_test_texts = [
        "他们买了甜脆多汁的红苹果当水果吃",
        "他们买了苹果公司最新款手机和芯片设备",
    ]
    vec_zh = TfidfVectorizer(analyzer="char", ngram_range=(1, 2))
    x_tr_zh = vec_zh.fit_transform(apple_train_texts)
    x_te_zh = vec_zh.transform(apple_test_texts)
    sims_zh = cosine_similarity(x_te_zh, x_tr_zh)
    preds_zh = [
        "fruit" if float(np.mean(row[:3])) >= float(np.mean(row[3:])) else "company"
        for row in sims_zh
    ]

    c1_ok = preds_en == bank_test_labels and preds_zh == ["fruit", "company"]
    cases.append(dict(
        name="context_lexical_disambiguation",
        inputs=dict(ambiguous_words=["bank", "苹果"], n_test_en=2, n_test_zh=2),
        prerequisites="为多义词 bank(金融/河岸)和“苹果”(水果/科技公司)各构造 6 条上下文原型与 2 条留出句。",
        action="使用训练集拟合的 TF-IDF 向量余弦相似度进行上下文词义消歧。",
        expected=dict(en_disambiguated=True, zh_disambiguated=True),
        actual=dict(
            en_disambiguated=(preds_en == bank_test_labels),
            zh_disambiguated=(preds_zh == ["fruit", "company"]),
        ),
        measurements=dict(
            bank_predictions=preds_en,
            apple_predictions=preds_zh,
            apple_fruit_gap=round(float(np.mean(sims_zh[0, :3]) - np.mean(sims_zh[0, 3:])), 4),
            apple_company_gap=round(float(np.mean(sims_zh[1, 3:]) - np.mean(sims_zh[1, :3])), 4),
        ),
        passed=c1_ok,
    ))

    # 2. Rule-based pattern matching (Stage 1) vs Statistical classifier (Stage 2) on dialog intent
    intent_data = [
        ("book a flight ticket to beijing tomorrow", "booking"),
        ("reserve two train seats for friday morning", "booking"),
        ("order a hotel room near the station", "booking"),
        ("i want to book a return air ticket", "booking"),
        ("schedule a flight reservation for next week", "booking"),
        ("can you arrange a hotel room booking", "booking"),
        ("need to reserve a seat on the express train", "booking"),
        ("please book one round trip flight ticket", "booking"),
        ("what is the weather forecast in shanghai today", "weather"),
        ("will it rain tomorrow afternoon in hangzhou", "weather"),
        ("check the temperature and wind speed outside", "weather"),
        ("tell me today weather condition and humidity", "weather"),
        ("is sunny or cloudy expected this weekend", "weather"),
        ("weather report for shenzhen tomorrow morning", "weather"),
        ("how cold will the temperature be tonight", "weather"),
        ("forecast rain probability for this afternoon", "weather"),
        ("my package arrived broken and damaged", "complaint"),
        ("the delivery is late and customer service ignored me", "complaint"),
        ("request a refund for the defective screen", "complaint"),
        ("very unhappy with the damaged order item", "complaint"),
        ("complaint about wrong product shipped twice", "complaint"),
        ("please refund my order because it stopped working", "complaint"),
        ("terrible delivery delay and broken box", "complaint"),
        ("file a complaint regarding defective charger", "complaint"),
    ]
    texts = [t for t, _ in intent_data]
    labels = [y for _, y in intent_data]
    x_tr, x_te, y_tr, y_te = train_test_split(
        texts, labels, test_size=0.25, random_state=42, stratify=labels
    )

    def rule_matcher(text: str) -> str:
        t = text.lower()
        if re.search(r"\b(book|ticket)\b", t):
            return "booking"
        if re.search(r"\b(weather|rain)\b", t):
            return "weather"
        if re.search(r"\b(broken|refund)\b", t):
            return "complaint"
        return "unknown"

    rule_preds = [rule_matcher(t) for t in x_te]
    rule_acc = float(accuracy_score(y_te, rule_preds))

    stat_pipe = Pipeline([
        ("tfidf", TfidfVectorizer(ngram_range=(1, 2))),
        ("clf", LogisticRegression(max_iter=500)),
    ])
    stat_pipe.fit(x_tr, y_tr)
    stat_preds = stat_pipe.predict(x_te).tolist()
    stat_acc = float(accuracy_score(y_te, stat_preds))

    # Unseen paraphrases without exact narrow rule keywords
    paraphrase_tests = [
        ("reserve a hotel room and train seat", "booking"),
        ("check temperature forecast and humidity tonight", "weather"),
        ("defective charger and delivery delay issue", "complaint"),
    ]
    para_rule_acc = float(accuracy_score(
        [y for _, y in paraphrase_tests], [rule_matcher(x) for x, _ in paraphrase_tests]
    ))
    para_stat_acc = float(accuracy_score(
        [y for _, y in paraphrase_tests], stat_pipe.predict([x for x, _ in paraphrase_tests])
    ))

    c2_ok = stat_acc >= rule_acc and para_stat_acc == 1.0 and para_rule_acc == 0.0
    cases.append(dict(
        name="rule_vs_statistical_intent",
        inputs=dict(train_size=len(x_tr), test_size=len(x_te), paraphrase_size=len(paraphrase_tests)),
        prerequisites="对比手工正则规则匹配(第一阶段)与 TF-IDF + LogisticRegression(第二阶段)在对话意图识别上的泛化。",
        action="在 6 条分层留出句与 3 条未包含窄关键词的改写句上分别计算准确率。",
        expected=dict(stat_ge_rule_on_test=True, stat_perfect_on_paraphrase=True, rule_zero_on_paraphrase=True),
        actual=dict(
            stat_ge_rule_on_test=(stat_acc >= rule_acc),
            stat_perfect_on_paraphrase=(para_stat_acc == 1.0),
            rule_zero_on_paraphrase=(para_rule_acc == 0.0),
        ),
        measurements=dict(
            rule_test_acc=round(rule_acc, 4),
            stat_test_acc=round(stat_acc, 4),
            rule_paraphrase_acc=round(para_rule_acc, 4),
            stat_paraphrase_acc=round(para_stat_acc, 4),
        ),
        passed=c2_ok,
    ))

    # 3. Extractive summarization via TF-IDF sentence centrality
    sentences = [
        "Transformer architecture replaced recurrence with self-attention for parallel sequence training.",
        "Large language models pretrain on massive text corpora before instruction fine-tuning.",
        "Yesterday afternoon it rained lightly near the campus cafeteria.",
        "Self-attention allows Transformer models to capture long-range context dependencies across tokens.",
        "Office printers occasionally run out of paper on Monday mornings.",
    ]
    s_vec = TfidfVectorizer(stop_words="english")
    s_mat = s_vec.fit_transform(sentences)
    centroid = np.asarray(s_mat.mean(axis=0))
    scores = cosine_similarity(s_mat, centroid).ravel()
    top2_idx = sorted(np.argsort(scores)[-2:].tolist())
    c3_ok = top2_idx == [0, 3] and float(scores[0]) > float(scores[2]) and float(scores[3]) > float(scores[4])
    cases.append(dict(
        name="extractive_summary_tfidf",
        inputs=dict(num_sentences=len(sentences), top_k=2),
        prerequisites="构造含 3 条 NLP 主题句与 2 条离题噪声句的 5 句文档。",
        action="计算各句 TF-IDF 向量与文档质心的余弦相似度并抽取前 2 句作为抽取式摘要。",
        expected=dict(selected_topic_indices_0_3=True, topic_scores_above_noise=True),
        actual=dict(
            selected_topic_indices_0_3=(top2_idx == [0, 3]),
            topic_scores_above_noise=(float(scores[0]) > float(scores[2]) and float(scores[3]) > float(scores[4])),
        ),
        measurements=dict(
            sentence_scores=[round(float(x), 4) for x in scores],
            selected_indices=top2_idx,
        ),
        passed=c3_ok,
    ))

    # 4. BLEU-2 evaluation metric limitation on synonym paraphrase vs literal match
    ref = ["the", "quick", "brown", "fox", "jumps", "over", "the", "lazy", "dog"]
    exact_cand = ["the", "quick", "brown", "fox", "jumps", "over", "the", "lazy", "dog"]
    synonym_cand = ["a", "fast", "dark", "canine", "leaps", "above", "a", "sleepy", "hound"]
    partial_cand = ["the", "quick", "fox", "jumps", "over", "the", "dog"]

    bleu_exact = compute_bleu2(exact_cand, ref)
    bleu_partial = compute_bleu2(partial_cand, ref)
    bleu_synonym = compute_bleu2(synonym_cand, ref)
    c4_ok = abs(bleu_exact - 1.0) < 1e-12 and 0.3 < bleu_partial < 0.9 and bleu_synonym == 0.0
    cases.append(dict(
        name="bleu_n_gram_limitation",
        inputs=dict(reference_len=len(ref), metric="BLEU-2"),
        prerequisites="给定标准参考译文,分别构造逐词一致、部分重合与语义等价但近义词替换三条候选译文。",
        action="计算精确 BLEU-2(1/2-gram 修正精确率几何平均乘以短句惩罚),观察同义改写得分。",
        expected=dict(exact_is_1=True, partial_between_03_09=True, synonym_paraphrase_is_0=True),
        actual=dict(
            exact_is_1=abs(bleu_exact - 1.0) < 1e-12,
            partial_between_03_09=(0.3 < bleu_partial < 0.9),
            synonym_paraphrase_is_0=(bleu_synonym == 0.0),
        ),
        measurements=dict(
            bleu_exact=round(bleu_exact, 4),
            bleu_partial=round(bleu_partial, 4),
            bleu_synonym_paraphrase=round(bleu_synonym, 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-intro-lab/explore-intro.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-intro.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章) · 含当前章节或实例 · mbskycom202612a550.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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