"""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 & 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)
本例需在 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-data-processing-tools-lab/explore-data-processing-tools.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-data-processing-tools.py,或下载右侧课程工程包。 - 确认本地已准备 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。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联21章) · 含当前章节或实例 · mbskycom202612a545.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a547.zip