蓝色天空.知识 · 实践 · 创造
我的收藏
自然语言处理 NLP 教程目录 21章
自然语言处理 NLP / LEARN BY DOING

文本分类

核对文本分类流程、四类特征表示与传统/深度模型选型,基于离线 4 类新闻语料严格先划分再拟合 TF-IDF+逻辑回归及 5 折 CV 算法对比,并实测 90:10 类别不平衡陷阱与多标签分类。

学完这一章,你能够

  • 核对文本分类流程、四类特征表示与传统/深度模型选型,基于离线 4 类新闻语料严格先划分再拟合 TF-IDF+逻辑回归及 5 折 CV 算法对比,并实测 90:10 类别不平衡陷阱与多标签分类。

文本分类概念、应用场景与基本流程

文本分类(Text Classification)是将文本文档自动指派到一个或多个预定义类别的基础 NLP 任务,好比图书馆管理员按主题把图书归类上架,广泛应用于评论情感分析、垃圾邮件过滤、新闻板块归类(体育/财经/科技)、对话意图识别和医疗症状分诊。

标准文本分类流水线依次包含预处理、特征提取、模型训练与评估。预处理通常执行小写化、去非字母和数字、分词、去停用词与词干提取;本站离线规则预处理函数实测将“The Graphics Engines are Rendering 3D Polygons & Textures in 2026!”清洗为 6 个规范词元“graphic engine render d polygon texture”。

特征提取将文本数值化(词袋、TF-IDF、Word2Vec、BERT 四类对比见下表),随后根据数据规模与算力选择传统机器学习(朴素贝叶斯、SVM、逻辑回归、随机森林)或深度学习模型(CNN、RNN/LSTM、BERT 等 Transformer)。

四类新闻分类离线实战与多模型交叉验证

来源实践示例通过 fetch_20newsgroups 下载 4 类 20 Newsgroups 数据并展示约 0.91 准确率的典型分类报告。由于离线隔离环境禁止联网下载外部语料,本站构建了 160 条 4 类(comp.graphics、sci.med、finance、sports)离线新闻语料,严格先按 75/25 分层拆分为 120 训练与 40 留出测试样本,再在 Pipeline 内仅用训练集拟合 TfidfVectorizer(max_features=5000)(习得词表 64 词)与 LogisticRegression(max_iter=1000),实测留出准确率与宏平均 F1 均达 1.0(四类 F1 均为 1.0)。同时在 120 条训练集上用无泄露 5 折分层交叉验证对比 MultinomialNB、LinearSVC、LogisticRegression 与 RandomForestClassifier,四者 CV 宏平均 F1 与留出测试宏平均 F1 均达 1.0。

进阶优化技巧、常见挑战与学习路径

面对严重类别不平衡时,切忌单独以准确率衡量模型,应结合过采样/欠采样、设置类别权重(class_weight='balanced')并观察少数类召回率与 F1。本站在 90:10 不平衡语料(200 样本,70/30 划分)实测:全预测多数类的基线虽表面获得 0.90 准确率,少数类 F1 却为 0.0;改用 class_weight='balanced' 逻辑回归后,少数类召回率与 F1 均提升至 1.0。

提升分类性能可从三方面着手:特征工程(调整 n-gram 范围、融合词性特征或预训练嵌入)、模型优化(超参数搜索、集成学习与深度网络)以及数据增强(回译、同义词替换、生成式增强)。实战中还常遇多标签分类(本站用 MultiLabelBinarizer + OneVsRestClassifier 在 3 标签语料上实测留出微平均 F1 = 1.0)、跨领域性能退化、小样本标注不足及决策可解释性挑战。建议按“TF-IDF + SVM/LR 基线 → 词嵌入 → CNN/LSTM → BERT/GPT 迁移微调”路径逐步深入。

文本分类常用特征提取方法对比

方法描述优点缺点
词袋模型(BoW)统计词表各词在文档中的出现频次实现简单直观、计算开销极低忽略词序与语义,特征稀疏高维
TF-IDF以词频乘逆文档频率衡量词语在语料中的区分度压低高频噪声词,通常比纯词袋更精确(本站四类新闻留出 F1=1.0)仍缺乏上下文语序与同义词语义建模
Word2Vec通过神经语言模型将词映射为低维稠密词向量能够捕捉词间语义与句法相似关系静态单一向量无法处理多义词,需额外池化得到文档向量
BERT基于双向 Transformer 的上下文感知预训练表示深层语义理解与多义词区分能力强预训练与推理计算/显存资源要求高

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

含完整源码 · 235 行
展开查看收起
python
"""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()
验证预处理 6 词输出、120/40 分层留出 4 类新闻准确率与宏平均 F1 达 1.0、4 算法 5 折 CV 对比,以及 90:10 不平衡准确率陷阱(基线 0.90/F1=0 vs 加权 F1=1.0)与多标签微平均 F1=1.0。

查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包

本地运行

解压后按 README 说明在对应本地环境运行脚本。

下载本章实验包 (mbskycom202612a545.zip) ↓ 查看运行说明 ↗

本章附件与实例包

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

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

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

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

常见错误与边界检查

  • 实际端口、文档资源与应用配置都应和测试条件一致。

技术规范与官方资料

练习与参考解答

查看参考解答

只需把所有样本一律判为多数类即可凭空获得 90% 准确率,但对真正需要检出的少数类(如欺诈、风险警报)召回率与 F1 均为 0;因此必须使用少数类 F1、PR-AUC 与类别权重/重采样联合评估。

SITE SEARCH

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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