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

运行文本分类预处理、无泄露 4 类 TF-IDF+LR、5 折 CV 算法对比与不平衡/多标签实验

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-text-classification.py
explore-text-classification.py235 行
"""Independent offline NLP lab for Ch 06 (Text Classification): preprocessing, 4-class TF-IDF+LogReg, 5-fold CV comparison, imbalance & multi-label."""
import json
import platform
import re

import numpy as np
from sklearn.ensemble import RandomForestClassifier
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score, classification_report, f1_score, recall_score
from sklearn.model_selection import StratifiedKFold, cross_val_score, train_test_split
from sklearn.multiclass import OneVsRestClassifier
from sklearn.naive_bayes import MultinomialNB
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import MultiLabelBinarizer
from sklearn.svm import LinearSVC

EN_STOPWORDS = {
    "a", "an", "and", "are", "as", "at", "be", "by", "for", "from", "has",
    "in", "is", "it", "of", "on", "or", "that", "the", "to", "was", "with", "this",
}


def preprocess_text(text: str) -> str:
    text = text.lower()
    text = re.sub(r"[^a-z\s]", " ", text)
    words = [w for w in text.split() if w not in EN_STOPWORDS]
    stemmed = []
    for w in words:
        if w.endswith("ing") and len(w) > 5:
            w = w[:-3]
        elif w.endswith("ed") and len(w) > 4:
            w = w[:-2]
        elif w.endswith("s") and not w.endswith("ss") and len(w) > 3:
            w = w[:-1]
        stemmed.append(w)
    return " ".join(stemmed)


def build_four_class_corpus():
    rng = np.random.default_rng(42)
    class_vocab = {
        "comp.graphics": [
            "shader", "polygon", "opengl", "rendering", "texture", "pixel", "raytracing",
            "mesh", "bitmap", "canvas", "gpu", "raster", "viewport", "lighting",
        ],
        "sci.med": [
            "clinical", "patient", "diagnosis", "therapy", "vaccine", "symptom", "hospital",
            "dosage", "doctor", "surgery", "pathology", "antibiotic", "blood", "immune",
        ],
        "finance": [
            "earnings", "dividend", "portfolio", "inflation", "equity", "mortgage", "centralbank",
            "revenue", "quarter", "bond", "yield", "market", "capital", "audit",
        ],
        "sports": [
            "stadium", "tournament", "goalkeeper", "striker", "championship", "coach", "marathon",
            "referee", "playoff", "league", "score", "sprint", "athlete", "match",
        ],
    }
    shared_fillers = ["report", "update", "analysis", "today", "review", "system", "team", "global"]
    docs, labels = [], []
    for label, vocab in class_vocab.items():
        for _ in range(40):
            chosen = rng.choice(vocab, size=7, replace=False).tolist()
            filler = rng.choice(shared_fillers, size=3, replace=False).tolist()
            words = chosen + filler
            rng.shuffle(words)
            docs.append(" ".join(words))
            labels.append(label)
    return docs, labels


def run_cases():
    cases = []

    # 1. Text preprocessing pipeline (lowercase, regex, stopword removal, stemming)
    raw = "The Graphics Engines are Rendering 3D Polygons & Textures in 2026!"
    cleaned = preprocess_text(raw)
    c1_ok = cleaned == "graphic engine render d polygon texture"
    cases.append(dict(
        name="text_preprocessing_pipeline",
        inputs=dict(raw_text=raw),
        prerequisites="使用纯 Python 停用词表与正则/规则词干处理实现文本分类前预处理函数。",
        action="执行转小写、去非字母与数字、分词、去停用词与词干化,校验清洗后词元序列。",
        expected=dict(cleaned_exact=True, digits_and_stopwords_removed=True),
        actual=dict(
            cleaned_exact=(cleaned == "graphic engine render d polygon texture"),
            digits_and_stopwords_removed=("the" not in cleaned.split() and "2026" not in cleaned),
        ),
        measurements=dict(cleaned_text=cleaned, token_count=len(cleaned.split())),
        passed=c1_ok,
    ))

    # 2. Leak-free 4-class news classification: TF-IDF + LogisticRegression
    docs, labels = build_four_class_corpus()
    x_tr, x_te, y_tr, y_te = train_test_split(
        docs, labels, test_size=0.25, random_state=42, stratify=labels
    )
    pipe_lr = Pipeline([
        ("tfidf", TfidfVectorizer(max_features=5000)),
        ("clf", LogisticRegression(max_iter=1000, random_state=42)),
    ])
    pipe_lr.fit(x_tr, y_tr)
    y_pred = pipe_lr.predict(x_te)
    acc = float(accuracy_score(y_te, y_pred))
    macro_f1 = float(f1_score(y_te, y_pred, average="macro"))
    report = classification_report(y_te, y_pred, output_dict=True)

    c2_ok = len(x_tr) == 120 and len(x_te) == 40 and acc >= 0.95 and macro_f1 >= 0.95
    cases.append(dict(
        name="tfidf_logreg_four_class_news",
        inputs=dict(total_docs=len(docs), train_docs=len(x_tr), test_docs=len(x_te), classes=4),
        prerequisites="构造 160 条 4 类离线新闻语料,先 75/25 分层划分,再用 Pipeline 仅在训练集拟合 TF-IDF 与 LogisticRegression。",
        action="评估留出测试集准确率、宏平均 F1 及各类精确率/召回率/F1。",
        expected=dict(split_120_40=True, test_acc_ge_095=True, macro_f1_ge_095=True),
        actual=dict(
            split_120_40=(len(x_tr) == 120 and len(x_te) == 40),
            test_acc_ge_095=(acc >= 0.95),
            macro_f1_ge_095=(macro_f1 >= 0.95),
        ),
        measurements=dict(
            vocab_size=len(pipe_lr.named_steps["tfidf"].vocabulary_),
            test_accuracy=round(acc, 4),
            test_macro_f1=round(macro_f1, 4),
            per_class_f1={k: round(report[k]["f1-score"], 4) for k in sorted(set(labels))},
        ),
        passed=c2_ok,
    ))

    # 3. Leak-free 5-fold Stratified CV comparison across NB, LinearSVC, LogisticRegression, RandomForest
    cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
    models = {
        "MultinomialNB": MultinomialNB(),
        "LinearSVC": LinearSVC(random_state=42),
        "LogisticRegression": LogisticRegression(max_iter=1000, random_state=42),
        "RandomForest": RandomForestClassifier(n_estimators=100, random_state=42),
    }
    cv_scores = {}
    test_scores = {}
    for name, clf in models.items():
        p = Pipeline([("tfidf", TfidfVectorizer(ngram_range=(1, 2))), ("clf", clf)])
        scores = cross_val_score(p, x_tr, y_tr, cv=cv, scoring="f1_macro")
        cv_scores[name] = round(float(scores.mean()), 4)
        p.fit(x_tr, y_tr)
        test_scores[name] = round(float(f1_score(y_te, p.predict(x_te), average="macro")), 4)

    c3_ok = all(v >= 0.90 for v in cv_scores.values()) and all(v >= 0.90 for v in test_scores.values())
    cases.append(dict(
        name="classifier_comparison_cv",
        inputs=dict(cv_folds=5, models=list(models.keys())),
        prerequisites="在 120 条训练集上使用无泄露 Pipeline 执行 5 折分层交叉验证,比较四种传统分类算法。",
        action="记录各模型的训练集 5 折 CV 宏平均 F1 与独立留出测试集宏平均 F1。",
        expected=dict(all_cv_f1_ge_090=True, all_test_f1_ge_090=True),
        actual=dict(
            all_cv_f1_ge_090=all(v >= 0.90 for v in cv_scores.values()),
            all_test_f1_ge_090=all(v >= 0.90 for v in test_scores.values()),
        ),
        measurements=dict(cv_macro_f1=cv_scores, heldout_test_macro_f1=test_scores),
        passed=c3_ok,
    ))

    # 4. Imbalanced classification (accuracy trap vs class_weight='balanced' F1) & Multi-label OneVsRest
    rng2 = np.random.default_rng(7)
    maj_pool = ["normal", "routine", "invoice", "meeting", "schedule", "report", "memo", "update", "project", "budget"]
    min_pool = ["fraud", "breach", "unauthorized", "urgent", "phishing", "alert", "compromise", "stolen"]
    imb_x, imb_y = [], []
    for _ in range(180):
        imb_x.append(" ".join(rng2.choice(maj_pool, size=5, replace=False)))
        imb_y.append(0)
    for _ in range(20):
        words = rng2.choice(min_pool, size=3, replace=False).tolist() + rng2.choice(maj_pool, size=2, replace=False).tolist()
        imb_x.append(" ".join(words))
        imb_y.append(1)
    ix_tr, ix_te, iy_tr, iy_te = train_test_split(
        imb_x, imb_y, test_size=0.3, random_state=42, stratify=imb_y
    )
    # Majority baseline
    maj_pred = [0] * len(iy_te)
    maj_acc = float(accuracy_score(iy_te, maj_pred))
    maj_f1 = float(f1_score(iy_te, maj_pred, zero_division=0))

    bal_pipe = Pipeline([
        ("tfidf", TfidfVectorizer()),
        ("clf", LogisticRegression(class_weight="balanced", max_iter=1000, random_state=42)),
    ])
    bal_pipe.fit(ix_tr, iy_tr)
    bal_pred = bal_pipe.predict(ix_te)
    bal_f1 = float(f1_score(iy_te, bal_pred))
    bal_recall = float(recall_score(iy_te, bal_pred))

    # Multi-label classification
    ml_docs = [
        "gpu shader rendering engine", "clinical vaccine hospital patient",
        "earnings dividend market equity", "gpu hospital clinical medical imaging",
        "earnings software gpu cloud revenue", "patient medical insurance market bond",
    ] * 6
    ml_tags = [
        ("tech",), ("med",), ("finance",),
        ("tech", "med"), ("tech", "finance"), ("med", "finance"),
    ] * 6
    mlb = MultiLabelBinarizer()
    y_ml = mlb.fit_transform(ml_tags)
    mx_tr, mx_te, my_tr, my_te = train_test_split(ml_docs, y_ml, test_size=0.25, random_state=42)
    ovr = Pipeline([("tfidf", TfidfVectorizer()), ("clf", OneVsRestClassifier(LogisticRegression(max_iter=500)))])
    ovr.fit(mx_tr, my_tr)
    ml_f1 = float(f1_score(my_te, ovr.predict(mx_te), average="micro"))

    c4_ok = abs(maj_acc - 0.9) < 1e-9 and maj_f1 == 0.0 and bal_f1 >= 0.90 and ml_f1 >= 0.90
    cases.append(dict(
        name="imbalanced_and_multilabel_classification",
        inputs=dict(imbalance_ratio="90:10", multilabel_classes=mlb.classes_.tolist()),
        prerequisites="构造 90:10 类别不平衡语料与 3 标签多标签语料,严格先划分后训练。",
        action="对比多数类基线(准确率 0.90 但 F1=0)与 class_weight='balanced' 少数类 F1,并测试 OneVsRest 多标签分类。",
        expected=dict(majority_acc_trap=True, balanced_f1_ge_090=True, multilabel_micro_f1_ge_090=True),
        actual=dict(
            majority_acc_trap=(abs(maj_acc - 0.9) < 1e-9 and maj_f1 == 0.0),
            balanced_f1_ge_090=(bal_f1 >= 0.90),
            multilabel_micro_f1_ge_090=(ml_f1 >= 0.90),
        ),
        measurements=dict(
            majority_baseline_acc=round(maj_acc, 4),
            majority_baseline_f1=round(maj_f1, 4),
            balanced_minority_recall=round(bal_recall, 4),
            balanced_minority_f1=round(bal_f1, 4),
            multilabel_micro_f1=round(ml_f1, 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-text-classification-lab/explore-text-classification.py

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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