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

数据处理工具

核对 Pandas、NumPy、Scikit-learn 与 Matplotlib 全链路 NLP 数据处理工具,实测纠正 pandas 3.x str.replace 默认 regex=False、NumPy 括号语法错误与全集评估数据泄露,并生成词频与混淆矩阵双联图。

学完这一章,你能够

  • 核对 Pandas、NumPy、Scikit-learn 与 Matplotlib 全链路 NLP 数据处理工具,实测纠正 pandas 3.x str.replace 默认 regex=False、NumPy 括号语法错误与全集评估数据泄露,并生成词频与混淆矩阵双联图。

Pandas 文本清洗、pandas 3.x 正则修复与 HTML/JSONL 流水线

高质量数据处理决定 NLP 模型上限。Pandas 以一维带标签 Series 与二维表格 DataFrame 两大结构(见下表 1)支撑语料加载、清洗、切词与词频统计,并支持 `str.contains(r'\bNLP\b')` 正则筛选、配合外部停用词表过滤以及 `dropna()` / `fillna('UNK')` 处理缺失值。关键版本勘误:来源代码直接调用 `.str.replace('[^\w\s]', '')`,但在现代 pandas ≥ 2.0(含本站 pandas 3.1.0)中 `regex` 参数默认已改为 `False`,且非原始字符串会在 Python 3.12 触发转义告警!本站实测证明:按默认 `regex=False` 执行时首行仍残留感叹号 `'hello world!'`,显式传入 `r'[^\w\s]'` 与 `regex=True` 才正确洗净为 `'hello world'` 并统计出 7 个去重词项;同时核对 `str.contains(r'\bNLP\b')` 命中 1 条、`dropna()` 保留 3 行、`fillna('UNK')` 填充缺失为 `'UNK'`,并扩展验证了 BeautifulSoup + lxml 清除 HTML 标签及 JSONL 逐行序列化往返(`'Great NLP pipeline & clean data!'` 精确无损)。

NumPy 词向量余弦相似度勘误、einsum 与二进制存储

NumPy 以多维数组、广播机制与线性代数算子为词向量存储、嵌入运算与矩阵分解提供高性能支撑。语法勘误提示:来源余弦相似度代码 `np.dot(a, b) / (np.linalg.norm(a) * (np.linalg.norm(b))` 遗漏了一个闭合右括号,直接运行会触发 SyntaxError,正确写法为 `np.dot(a, b) / (np.linalg.norm(a) * np.linalg.norm(b))`。本站修复后在 3×5 示例词向量矩阵上实测:词向量 0 与 1 的余弦相似度精确等于 1.30 / √1.815 ≈ 0.9650(与词向量 2 为 0.9453);通过 `np.einsum('ij,kj->ik', ...)` 一步求取全部两两内积并与单对点积对照误差精确为 0.0;`np.save` / `np.load` 往返读写误差为 0.0。性能方面需提醒:`np.vectorize` 本质仍是 Python 函数调用封装而非 C 级向量化,真正提速应优先采用原生数组广播、ufunc 或 BLAS 矩阵乘法。

Scikit-learn 特征提取、LSA 降维与无泄露流水线优化

Scikit-learn 借助 `Pipeline` 将文本向量化与分类器串联为可复现的端到端工作流,核心 NLP 组件(`CountVectorizer`、`TfidfVectorizer`、`HashingVectorizer` 与 `TruncatedSVD`)汇总见下表 2。数据泄露警示:来源管道示例把仅 3 条短句重复乘以 100 构造 300 条样本后再切分,导致训练集与测试集充斥完全重复的文本,测出的 1.00 准确率属于严重数据泄露假象。本站首先在 3 句标准英文语料上核对 `CountVectorizer` 与 `TfidfVectorizer` 精确产出 (3, 9) 特征矩阵(9 词表与来源一致)、无状态 `HashingVectorizer(n_features=32)` 产出 (3, 32)、`TruncatedSVD(n_components=2)` 降维至 (3, 2);继而构造 80 条互不重复的评论语料按 75/25 分层切分(核验训练/测试文本重叠严格为 0),在 `Pipeline` 内集成 `TfidfVectorizer`、`SelectKBest(chi2, k=16)`、磁盘 `memory` 缓存与 `RandomForestClassifier(n_jobs=1)`,实测在独立留出集上取得 1.0000 准确率。

Matplotlib 可视化与端到端情感分析留出实测

可视化环节常以 Matplotlib 绘制基础词频柱状图(如 `['nlp', 'python', 'learning']` 频数 `[25, 40, 35]`),并按需扩展 Seaborn 热力图、WordCloud 词云与 Plotly 3D 交互散点。本站隔离环境未安装 Seaborn、WordCloud 与 Plotly,直接以纯 Matplotlib 的 `bar` 与带数值标注的 `imshow` 即可无额外依赖完成词频柱状图与混淆矩阵热力图绘制。

针对文末情感分析综合项目,须纠正来源直接先在全量数据拟合 `TfidfVectorizer` 再用 `LinearSVC` 在训练集自身上预测评估混淆矩阵的双重泄露问题。本站严格按“DataFrame 正则清洗 → 75/25 分层划分(60 训练 / 20 留出测试) → `Pipeline([('tfidf', TfidfVectorizer), ('clf', LinearSVC)])` 仅在训练集拟合 → 独立留出集评估”执行,实测留出准确率 1.0000,留出混淆矩阵精确为 `[[10, 0], [0, 10]]`(见下方实测双联图)。在工程调优与扩展方面,除 `n_jobs` 并行、`SelectKBest` 特征筛选与 `Pipeline(memory=...)` 缓存外,还可按任务需求无缝接入 NLTK、spaCy、Gensim 与 Hugging Face Transformers 组成完整工具链。

左图为 NLP 术语词频柱状图,右图为无泄露 Pipeline(TfidfVectorizer + LinearSVC) 在 20 条留出测试集上的混淆矩阵热力图。
本站 pandas 3.1.0、scikit-learn 1.9.1 与 Matplotlib 3.11.2 实测的术语词频与 LinearSVC 留出混淆矩阵双联图。

Pandas 核心数据结构与 NLP 应用场景

数据结构特点NLP应用场景
Series一维带索引标签数组,内置向量化 .str 字符串方法存储单列原始文本、清洗后文本、分词列表或情感标签
DataFrame二维异构表格结构,支持过滤、分组与缺失值批处理承载完整文本语料表(多字段元数据 + 文本 + 标签)

Scikit-learn 常用 NLP 特征与降维组件

组件类别主要类功能说明
特征提取CountVectorizer词袋计数矩阵(实测 3 句语料产出 (3, 9) 稀疏矩阵)
特征提取(同上)TfidfVectorizer结合词频与逆文档频率加权(实测产出 (3, 9) 矩阵并适配 Pipeline)
文本预处理HashingVectorizer无状态特征哈希映射,无需维护词表、内存占用恒定(实测 (3, 32))
降维TruncatedSVD面向稀疏矩阵的截断奇异值分解,用于潜在语义分析 LSA(实测 (3, 2))

运行 pandas 3.1.0 清洗修复与 BS4/JSONL、NumPy einsum、sklearn 四组件管道及 LinearSVC 留出实测

含完整源码 · 315 行
展开查看收起
python
"""Independent pandas 3.1.0, NumPy 2.5.4, scikit-learn 1.9.1, BeautifulSoup/lxml & Matplotlib lab (Ch 21)."""
import argparse
import hashlib
import json
import platform
import tempfile
from pathlib import Path

from bs4 import BeautifulSoup
import numpy as np
import pandas as pd
from sklearn.decomposition import TruncatedSVD
from sklearn.ensemble import RandomForestClassifier
from sklearn.feature_extraction.text import CountVectorizer, HashingVectorizer, TfidfVectorizer
from sklearn.feature_selection import SelectKBest, chi2
from sklearn.metrics import accuracy_score, confusion_matrix
from sklearn.model_selection import train_test_split
from sklearn.pipeline import Pipeline
from sklearn.svm import LinearSVC


def sha(path: Path) -> str:
    return hashlib.sha256(path.read_bytes()).hexdigest()


def run_cases(fig_dir: Path | None):
    cases = []
    figures = {}

    # 1. Pandas 3.1.0 Series/DataFrame Text Cleaning, regex=True Fix, Missing Values, BS4/lxml & JSONL
    raw_df = pd.DataFrame({
        "text": ["Hello World!", "NLP is amazing", "Python 3.8", None],
        "label": [1, 0, 1, 0],
    })
    # Demonstrate pandas >=2.0/3.x default regex=False pitfall vs explicit regex=True
    clean_buggy = raw_df["text"].dropna().str.lower().str.replace(r"[^\w\s]", "", regex=False)
    clean_fixed = raw_df["text"].dropna().str.lower().str.replace(r"[^\w\s]", "", regex=True)
    buggy_kept_bang = "!" in clean_buggy.iloc[0]
    fixed_stripped_bang = "!" not in clean_fixed.iloc[0] and "." not in clean_fixed.iloc[2]

    tokens_series = clean_fixed.str.split()
    word_counts = tokens_series.explode().value_counts()
    nlp_hits = int(raw_df["text"].fillna("").str.contains(r"\bNLP\b", regex=True).sum())
    filled_val = str(raw_df["text"].fillna("UNK").iloc[3])
    dropped_len = len(raw_df.dropna())

    # BeautifulSoup + lxml HTML cleaning & JSONL round-trip
    html_records = [
        {"id": 1, "html": "<p>Great <b>NLP</b> pipeline &amp; clean data!</p>", "sentiment": 1},
        {"id": 2, "html": "<div>Slow parser, <em>broken</em> tokens...</div>", "sentiment": 0},
    ]
    jsonl_lines = []
    for rec in html_records:
        plain = BeautifulSoup(rec["html"], "lxml").get_text(" ", strip=True)
        jsonl_lines.append(json.dumps({"id": rec["id"], "text": plain, "sentiment": rec["sentiment"]}, ensure_ascii=False))
    parsed_jsonl = [json.loads(line) for line in jsonl_lines]

    c1_ok = (
        isinstance(raw_df["text"], pd.Series)
        and buggy_kept_bang
        and fixed_stripped_bang
        and nlp_hits == 1
        and filled_val == "UNK"
        and dropped_len == 3
        and len(word_counts) == 7
        and parsed_jsonl[0]["text"] == "Great NLP pipeline & clean data!"
    )
    cases.append(dict(
        name="pandas_cleaning_regex_fix_bs4_jsonl",
        inputs=dict(rows=len(raw_df), html_records=len(html_records), pandas_version=pd.__version__),
        prerequisites="在 pandas 3.1.0 上实测 Series/DataFrame 文本清洗、缺失处理、BeautifulSoup+lxml 去标签及 JSONL 序列化。",
        action="验证 pandas 3.x 中 str.replace 默认 regex=False 会保留标点,显式 regex=True 才正确清除,并核对词频与 HTML 清洗。",
        expected=dict(regex_false_keeps_punct=True, regex_true_strips_punct=True, missing_and_regex_filter_exact=True, bs4_jsonl_roundtrip_exact=True),
        actual=dict(
            regex_false_keeps_punct=buggy_kept_bang,
            regex_true_strips_punct=fixed_stripped_bang,
            missing_and_regex_filter_exact=(nlp_hits == 1 and filled_val == "UNK" and dropped_len == 3),
            bs4_jsonl_roundtrip_exact=(parsed_jsonl[0]["text"] == "Great NLP pipeline & clean data!"),
        ),
        measurements=dict(
            clean_buggy_row0=str(clean_buggy.iloc[0]),
            clean_fixed_row0=str(clean_fixed.iloc[0]),
            unique_tokens=int(len(word_counts)),
            nlp_regex_matches=nlp_hits,
            bs4_cleaned_sample=parsed_jsonl[0]["text"],
        ),
        passed=c1_ok,
    ))

    # 2. NumPy Cosine Similarity (fixing source Code 4 parenthesis SyntaxError), einsum & np.save/load
    word_vectors = np.array([
        [0.1, 0.2, 0.3, 0.4, 0.5],
        [0.6, 0.7, 0.8, 0.9, 1.0],
        [1.1, 1.2, 1.3, 1.4, 1.5],
    ], dtype=float)

    def cosine_similarity(a: np.ndarray, b: np.ndarray) -> float:
        return float(np.dot(a, b) / (np.linalg.norm(a) * np.linalg.norm(b)))

    sim_01 = cosine_similarity(word_vectors[0], word_vectors[1])
    norms = np.linalg.norm(word_vectors, axis=1)
    # Pairwise cosine via np.einsum + broadcasting
    dot_mat = np.einsum("ij,kj->ik", word_vectors, word_vectors)
    cos_mat = dot_mat / np.outer(norms, norms)
    einsum_err = abs(float(cos_mat[0, 1]) - sim_01)

    # Lossless np.save / np.load roundtrip + np.vectorize vs native ufunc check
    with tempfile.TemporaryDirectory() as tmp:
        npy_path = Path(tmp) / "wv.npy"
        np.save(npy_path, word_vectors)
        reloaded = np.load(npy_path)
    io_max_err = float(np.max(np.abs(reloaded - word_vectors)))
    v_sq = np.vectorize(lambda x: x * x)(word_vectors)
    ufunc_diff = float(np.max(np.abs(v_sq - (word_vectors ** 2))))

    exact_cos_01 = 1.30 / float(np.sqrt(0.55 * 3.30))
    c2_ok = abs(sim_01 - exact_cos_01) < 1e-12 and einsum_err < 1e-12 and io_max_err == 0.0 and ufunc_diff < 1e-12
    cases.append(dict(
        name="numpy_cosine_einsum_and_io_roundtrip",
        inputs=dict(matrix_shape=list(word_vectors.shape)),
        prerequisites="修复来源代码缺失右括号语法错误,计算词向量余弦相似度并核对 np.einsum 批量矩阵、np.save/load 往返与广播等价性。",
        action="验证词向量 0 与 1 余弦相似度精确等于 1.30/sqrt(1.815)≈0.9650、np.einsum 误差 <1e-12 且二进制读写零误差。",
        expected=dict(cosine_01_exact=True, einsum_matches_dot=True, save_load_lossless=True),
        actual=dict(
            cosine_01_exact=abs(sim_01 - exact_cos_01) < 1e-12,
            einsum_matches_dot=einsum_err < 1e-12,
            save_load_lossless=(io_max_err == 0.0 and ufunc_diff < 1e-12),
        ),
        measurements=dict(
            cosine_v0_v1=round(sim_01, 4),
            cosine_v0_v2=round(float(cos_mat[0, 2]), 4),
            einsum_max_err=float(f"{einsum_err:.2e}"),
            npy_roundtrip_err=io_max_err,
        ),
        passed=c2_ok,
    ))

    # 3. Scikit-learn 4 NLP Components (CountVectorizer, TfidfVectorizer, HashingVectorizer, TruncatedSVD) & Pipeline Caching
    corpus_3 = [
        "This is the first document.",
        "This document is the second document.",
        "And this is the third one.",
    ]
    x_cnt = CountVectorizer().fit_transform(corpus_3)
    tf_vec = TfidfVectorizer()
    x_tf = tf_vec.fit_transform(corpus_3)
    vocab_3 = list(tf_vec.get_feature_names_out())
    x_hash = HashingVectorizer(n_features=32).transform(corpus_3)
    x_svd = TruncatedSVD(n_components=2, random_state=42).fit_transform(x_tf)

    # Leak-free Pipeline with SelectKBest + memory caching + n_jobs
    pos_adj = ["excellent", "smooth", "clean", "accurate", "helpful", "fast", "reliable", "clear", "solid", "brilliant"]
    neg_adj = ["broken", "slow", "noisy", "buggy", "terrible", "confusing", "crash", "poor", "messy", "useless"]
    topics = ["parser", "tokenizer", "pipeline", "dataset", "classifier", "matrix", "chart", "model"]
    rng = np.random.default_rng(21)
    synth_texts, synth_labels = [], []
    seen = set()
    while len(synth_texts) < 80:
        lbl = len(synth_texts) % 2
        pool = pos_adj if lbl == 1 else neg_adj
        w1, w2 = rng.choice(pool, size=2, replace=False)
        t1, t2 = rng.choice(topics, size=2, replace=False)
        txt = f"The {t1} and {t2} are {w1} and {w2} for nlp work!"
        if txt not in seen:
            seen.add(txt)
            synth_texts.append(txt)
            synth_labels.append(lbl)

    x_tr, x_te, y_tr, y_te = train_test_split(synth_texts, synth_labels, test_size=0.25, random_state=42, stratify=synth_labels)
    overlap_count = len(set(x_tr) & set(x_te))
    with tempfile.TemporaryDirectory() as cache_dir:
        rf_pipe = Pipeline(
            [
                ("tfidf", TfidfVectorizer(max_features=1000)),
                ("select", SelectKBest(chi2, k=16)),
                ("clf", RandomForestClassifier(n_estimators=60, random_state=42, n_jobs=1)),
            ],
            memory=cache_dir,
        )
        rf_pipe.fit(x_tr, y_tr)
        rf_acc = float(rf_pipe.score(x_te, y_te))
        selected_feats = int(rf_pipe.named_steps["select"].get_support().sum())

    c3_ok = (
        x_cnt.shape == (3, 9)
        and x_tf.shape == (3, 9)
        and x_hash.shape == (3, 32)
        and x_svd.shape == (3, 2)
        and overlap_count == 0
        and selected_feats == 16
        and rf_acc >= 0.95
    )
    cases.append(dict(
        name="sklearn_vectorizers_svd_and_pipeline_optimization",
        inputs=dict(mini_corpus_docs=3, sentiment_unique_docs=len(synth_texts), select_k=16),
        prerequisites="依次验证 CountVectorizer、TfidfVectorizer、HashingVectorizer 与 TruncatedSVD,并在无重复样本 75/25 切分上运行带 SelectKBest 与 memory 缓存的 Pipeline。",
        action="验证 3 文档特征矩阵形状 (3,9)、哈希矩阵 (3,32)、LSA 降维 (3,2),以及零泄露管道留出准确率 >=95%。",
        expected=dict(four_components_shapes_exact=True, zero_train_test_overlap=True, rf_pipeline_acc_ge_95pct=True),
        actual=dict(
            four_components_shapes_exact=(x_cnt.shape == (3, 9) and x_tf.shape == (3, 9) and x_hash.shape == (3, 32) and x_svd.shape == (3, 2)),
            zero_train_test_overlap=(overlap_count == 0),
            rf_pipeline_acc_ge_95pct=(rf_acc >= 0.95 and selected_feats == 16),
        ),
        measurements=dict(
            count_and_tfidf_shape=list(x_tf.shape),
            hashing_shape=list(x_hash.shape),
            svd_shape=list(x_svd.shape),
            corpus_vocab=vocab_3,
            selected_features=selected_feats,
            rf_holdout_acc=round(rf_acc, 4),
        ),
        passed=c3_ok,
    ))

    # 4. End-to-End Sentiment Project (DataFrame Clean -> Stratified Split -> Tfidf + LinearSVC -> Holdout CM)
    df_sent = pd.DataFrame({"text": synth_texts, "sentiment": synth_labels})
    df_sent["clean_text"] = df_sent["text"].str.lower().str.replace(r"[^\w\s]", "", regex=True)
    sx_tr, sx_te, sy_tr, sy_te = train_test_split(
        df_sent["clean_text"], df_sent["sentiment"], test_size=0.25, random_state=42, stratify=df_sent["sentiment"]
    )
    svc_pipe = Pipeline([
        ("tfidf", TfidfVectorizer(max_features=5000)),
        ("clf", LinearSVC(random_state=42)),
    ])
    svc_pipe.fit(sx_tr, sy_tr)
    sy_pred = svc_pipe.predict(sx_te)
    svc_acc = float(accuracy_score(sy_te, sy_pred))
    cm = confusion_matrix(sy_te, sy_pred)

    c4_ok = svc_acc >= 0.95 and int(np.sum(cm)) == len(sy_te)
    cases.append(dict(
        name="end_to_end_sentiment_linearsvc_and_cm",
        inputs=dict(train_samples=len(sx_tr), holdout_samples=len(sx_te)),
        prerequisites="纠正来源综合案例在全量训练集上拟合与自评的泄露做法,改用先 75/25 分层切分再经 Pipeline(TfidfVectorizer + LinearSVC) 留出评估。",
        action="验证情感分析完整流程在 20 条独立留出测试样本上取得高准确率并产出精确混淆矩阵。",
        expected=dict(holdout_acc_ge_95pct=True, cm_sum_matches_holdout=True),
        actual=dict(holdout_acc_ge_95pct=(svc_acc >= 0.95), cm_sum_matches_holdout=(int(np.sum(cm)) == len(sy_te))),
        measurements=dict(
            linearsvc_holdout_acc=round(svc_acc, 4),
            confusion_matrix=cm.tolist(),
        ),
        passed=c4_ok,
    ))

    # 5. Pure Matplotlib Dual Panel Chart: Term Frequency Bar + Annotated Confusion Matrix Heatmap
    bar_words = ["nlp", "python", "learning"]
    bar_freqs = [25, 40, 35]
    mpl_ver = None
    if fig_dir is not None:
        import matplotlib
        matplotlib.use("Agg")
        import matplotlib.pyplot as plt

        fig_dir.mkdir(parents=True, exist_ok=True)
        fig, axes = plt.subplots(1, 2, figsize=(10.0, 4.0), dpi=140)

        colors = ["#3498db", "#2ecc71", "#e74c3c"]
        bars = axes[0].bar(bar_words, bar_freqs, color=colors, width=0.55)
        axes[0].set_title("NLP Term Frequency Distribution", fontsize=10)
        axes[0].set_xlabel("Term")
        axes[0].set_ylabel("Count")
        axes[0].set_ylim(0, 48)
        axes[0].grid(axis="y", alpha=0.3)
        for bar, val in zip(bars, bar_freqs):
            axes[0].text(bar.get_x() + bar.get_width() / 2.0, val + 1.0, str(val), ha="center", va="bottom", fontsize=9)

        im = axes[1].imshow(cm, cmap="Blues", vmin=0, vmax=max(int(np.max(cm)), 1))
        axes[1].set_xticks([0, 1])
        axes[1].set_xticklabels(["Pred Neg (0)", "Pred Pos (1)"], fontsize=9)
        axes[1].set_yticks([0, 1])
        axes[1].set_yticklabels(["True Neg (0)", "True Pos (1)"], fontsize=9)
        axes[1].set_title(f"LinearSVC Holdout Confusion Matrix (Acc={svc_acc:.2f})", fontsize=10)
        for i in range(2):
            for j in range(2):
                val = int(cm[i, j])
                axes[1].text(j, i, str(val), ha="center", va="center",
                             color="white" if val > np.max(cm) / 2.0 else "#1a1a1a", fontsize=11, fontweight="bold")
        fig.colorbar(im, ax=axes[1], fraction=0.046, pad=0.04)

        fig.tight_layout()
        out_png = fig_dir / "nlp-data-pipeline-overview.png"
        fig.savefig(out_png)
        plt.close(fig)
        figures["nlp-data-pipeline-overview.png"] = sha(out_png)
        mpl_ver = matplotlib.__version__

    c5_ok = sum(bar_freqs) == 100 and cm.shape == (2, 2)
    cases.append(dict(
        name="observed_data_tools_charts_plot",
        inputs=dict(bar_terms=bar_words, bar_counts=bar_freqs),
        prerequisites="不依赖未安装的 Seaborn/WordCloud/Plotly,以纯 Matplotlib 绘制词频柱状图与带数值标注的混淆矩阵热力图。",
        action="验证柱状图统计频数和为 100、混淆矩阵形状 (2, 2) 且高清双联 PNG 正常输出。",
        expected=dict(bar_total_100=True, cm_2x2=True),
        actual=dict(bar_total_100=(sum(bar_freqs) == 100), cm_2x2=(cm.shape == (2, 2))),
        measurements=dict(figure_generated="nlp-data-pipeline-overview.png" in figures),
        passed=c5_ok,
    ))

    payload = dict(
        version=platform.python_version(),
        system=platform.system(),
        cases=cases,
    )
    if mpl_ver:
        payload["matplotlib"] = mpl_ver
        payload["figures"] = figures
    print(json.dumps(payload, ensure_ascii=False))


if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("--figures", type=Path, default=None)
    args = parser.parse_args()
    run_cases(args.figures)
核对 regex=True 修复去标点、BeautifulSoup/JSONL 无损清洗、余弦相似度 0.9650 与 einsum 零误差、sklearn 四组件形状与无泄露 LinearSVC 留出混淆矩阵 [[10,0],[0,10]] 及双联图。

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

本地运行

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

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

本章附件与实例包

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

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

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

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

常见错误与边界检查

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

技术规范与官方资料

练习与参考解答

查看参考解答

pandas 自 2.0 起将 str.replace 的默认参数改为 regex=False,不显式传入 regex=True 会把正则当成普通字面串匹配;而先全量拟合 TfidfVectorizer 会把测试集词表与 IDF 权重提前泄露给训练过程,正确做法是先划分数据再把向量化器与分类器封装进 Pipeline 仅在训练集拟合。

SITE SEARCH

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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