"""Independent offline NLP lab for Ch 05 (Text Representation): BoW/TF-IDF/N-gram, PPMI+SVD & Skip-gram, FastText subwords, SIF/context shift, LDA."""
import json
import math
import platform
from collections import Counter
import numpy as np
from sklearn.decomposition import LatentDirichletAllocation
from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer
def cosine(a: np.ndarray, b: np.ndarray) -> float:
na, nb = float(np.linalg.norm(a)), float(np.linalg.norm(b))
if na == 0.0 or nb == 0.0:
return 0.0
return float(np.dot(a, b) / (na * nb))
def char_ngrams(word: str, n: int = 3):
padded = f"<{word}>"
return [padded[i:i + n] for i in range(max(1, len(padded) - n + 1))]
def run_cases():
cases = []
# 1. Exact CountVectorizer, TfidfVectorizer (formula vs sklearn), and Bigram CountVectorizer
corpus = [
"This is the first document.",
"This document is the second document.",
"And this is the third one.",
"Is this the first document?",
]
cv = CountVectorizer()
x_bow = cv.fit_transform(corpus).toarray()
vocab = cv.get_feature_names_out().tolist()
tv = TfidfVectorizer()
x_tfidf = tv.fit_transform(corpus).toarray()
# Verify sklearn smooth_idf + L2 normalization formula manually
n_docs = len(corpus)
df = (x_bow > 0).sum(axis=0)
manual_idf = np.log((1.0 + n_docs) / (1.0 + df)) + 1.0
manual_raw = x_bow * manual_idf
manual_l2 = manual_raw / np.linalg.norm(manual_raw, axis=1, keepdims=True)
max_formula_diff = float(np.max(np.abs(x_tfidf - manual_l2)))
row_norms = np.linalg.norm(x_tfidf, axis=1)
# Textbook unsmoothed TF-IDF for doc 0 word "document" vs "first"
doc0_len = int(x_bow[0].sum())
idx_doc = vocab.index("document")
idx_first = vocab.index("first")
tb_tfidf_doc = float((x_bow[0, idx_doc] / doc0_len) * math.log(n_docs / int(df[idx_doc])))
tb_tfidf_first = float((x_bow[0, idx_first] / doc0_len) * math.log(n_docs / int(df[idx_first])))
bv = CountVectorizer(ngram_range=(2, 2))
x_bi = bv.fit_transform(corpus).toarray()
bi_vocab = bv.get_feature_names_out().tolist()
c1_ok = bool(
x_bow.shape == (4, 9)
and x_bi.shape == (4, 13)
and max_formula_diff < 1e-12
and float(np.max(np.abs(row_norms - 1.0))) < 1e-12
and tb_tfidf_first > tb_tfidf_doc
)
cases.append(dict(
name="bow_tfidf_ngram_sklearn",
inputs=dict(n_docs=n_docs, ngram_range=[2, 2]),
prerequisites="在 4 条标准英文示例语料上运行 CountVectorizer、TfidfVectorizer 与 Bigram 向量化器。",
action="核对词表规模(9 词、13 二元组)、sklearn 平滑 IDF+L2 归一化精确公式误差及教科书未平滑 TF-IDF 排序。",
expected=dict(bow_shape_4_9=True, bigram_shape_4_13=True, sklearn_tfidf_formula_exact=True, rarer_word_higher_tfidf=True),
actual=dict(
bow_shape_4_9=bool(x_bow.shape == (4, 9)),
bigram_shape_4_13=bool(x_bi.shape == (4, 13)),
sklearn_tfidf_formula_exact=bool(max_formula_diff < 1e-12 and float(np.max(np.abs(row_norms - 1.0))) < 1e-12),
rarer_word_higher_tfidf=bool(tb_tfidf_first > tb_tfidf_doc),
),
measurements=dict(
unigram_vocab=vocab,
bigram_count=len(bi_vocab),
max_tfidf_formula_diff=float(f"{max_formula_diff:.2e}"),
textbook_tfidf_first=round(tb_tfidf_first, 4),
textbook_tfidf_document=round(tb_tfidf_doc, 4),
sklearn_tfidf_first=round(float(x_tfidf[0, idx_first]), 4),
sklearn_tfidf_document=round(float(x_tfidf[0, idx_doc]), 4),
),
passed=c1_ok,
))
# 2. Pure-NumPy PPMI+SVD (GloVe-like global co-occurrence) + Skip-gram negative sampling SGD
sents = [
["king", "rules", "royal", "palace", "crown"],
["queen", "rules", "royal", "palace", "crown"],
["prince", "wears", "royal", "crown", "palace"],
["cat", "eats", "fresh", "fish", "milk"],
["dog", "eats", "fresh", "meat", "bone"],
["kitten", "drinks", "fresh", "milk", "fish"],
] * 8
words = sorted({w for s in sents for w in s})
w2i = {w: i for i, w in enumerate(words)}
v_n = len(words)
cooc = np.zeros((v_n, v_n), dtype=float)
for s in sents:
for i, wi in enumerate(s):
for j in range(max(0, i - 2), min(len(s), i + 3)):
if i != j:
cooc[w2i[wi], w2i[s[j]]] += 1.0
total = cooc.sum()
p_ij = cooc / total
p_i = cooc.sum(axis=1, keepdims=True) / total
p_j = cooc.sum(axis=0, keepdims=True) / total
with np.errstate(divide="ignore", invalid="ignore"):
pmi = np.where(cooc > 0, np.log(p_ij / (p_i @ p_j)), 0.0)
ppmi = np.maximum(pmi, 0.0)
u, sv, _ = np.linalg.svd(ppmi, full_matrices=False)
svd_emb = u[:, :4] * np.sqrt(sv[:4])
cos_king_queen = cosine(svd_emb[w2i["king"]], svd_emb[w2i["queen"]])
cos_cat_dog = cosine(svd_emb[w2i["cat"]], svd_emb[w2i["dog"]])
cos_king_cat = cosine(svd_emb[w2i["king"]], svd_emb[w2i["cat"]])
# Pure-NumPy Skip-gram negative-sampling SGD (loss decreases deterministically)
rng = np.random.default_rng(42)
dim = 6
w_in = rng.normal(0.0, 0.1, size=(v_n, dim))
w_out = rng.normal(0.0, 0.1, size=(v_n, dim))
pairs = []
for s in sents[:6]:
for i, wi in enumerate(s):
for j in range(max(0, i - 2), min(len(s), i + 3)):
if i != j:
pairs.append((w2i[wi], w2i[s[j]]))
def sg_loss():
tot = 0.0
for c, o in pairs:
pos = 1.0 / (1.0 + math.exp(-float(np.dot(w_in[c], w_out[o]))))
tot -= math.log(max(pos, 1e-12))
neg = (o + 5) % v_n
nv = 1.0 / (1.0 + math.exp(float(np.dot(w_in[c], w_out[neg]))))
tot -= math.log(max(nv, 1e-12))
return tot / len(pairs)
loss_init = sg_loss()
lr = 0.15
for _ in range(30):
for c, o in pairs:
score_pos = float(np.dot(w_in[c], w_out[o]))
sig_pos = 1.0 / (1.0 + math.exp(-score_pos))
g_pos = sig_pos - 1.0
vc_old = w_in[c].copy()
w_in[c] -= lr * g_pos * w_out[o]
w_out[o] -= lr * g_pos * vc_old
neg = (o + 5) % v_n
score_neg = float(np.dot(w_in[c], w_out[neg]))
sig_neg = 1.0 / (1.0 + math.exp(-score_neg))
vc_old2 = w_in[c].copy()
w_in[c] -= lr * sig_neg * w_out[neg]
w_out[neg] -= lr * sig_neg * vc_old2
loss_final = sg_loss()
c2_ok = cos_king_queen > 0.9 and cos_cat_dog > 0.5 and cos_king_cat < 0.1 and loss_final < loss_init * 0.4
cases.append(dict(
name="cooccurrence_svd_and_skipgram_numpy",
inputs=dict(vocab_size=v_n, svd_dim=4, skipgram_dim=dim, epochs=30),
prerequisites="在王室与宠物两主题语料上用纯 NumPy 实现 PPMI+SVD 全局共现分解与 Skip-gram 负采样 SGD。",
action="验证同域词 king-queen / cat-dog 稠密向量高相似、跨域 king-cat 低相似,及 Skip-gram 损失大幅收敛。",
expected=dict(king_queen_gt_09=True, cat_dog_gt_05=True, king_cat_lt_01=True, sg_loss_dropped=True),
actual=dict(
king_queen_gt_09=(cos_king_queen > 0.9),
cat_dog_gt_05=(cos_cat_dog > 0.5),
king_cat_lt_01=(cos_king_cat < 0.1),
sg_loss_dropped=(loss_final < loss_init * 0.4),
),
measurements=dict(
cos_king_queen=round(cos_king_queen, 4),
cos_cat_dog=round(cos_cat_dog, 4),
cos_king_cat=round(cos_king_cat, 4),
skipgram_loss_init=round(loss_init, 4),
skipgram_loss_final=round(loss_final, 4),
),
passed=c2_ok,
))
# 3. FastText-style character n-gram subword OOV representation
known_words = ["playful", "kindness", "computer", "network", "learning"]
all_ngrams = sorted({ng for w in known_words for ng in char_ngrams(w, 3)})
rng_ft = np.random.default_rng(7)
ng_vecs = {ng: rng_ft.normal(0.0, 1.0, size=16) for ng in all_ngrams}
def fasttext_vec(word: str):
ngs = [ng_vecs[ng] for ng in char_ngrams(word, 3) if ng in ng_vecs]
return np.mean(ngs, axis=0) if ngs else np.zeros(16)
oov_word = "playfulness" # Not in known_words, shares subwords with playful & kindness
v_oov = fasttext_vec(oov_word)
v_playful = fasttext_vec("playful")
v_computer = fasttext_vec("computer")
cos_oov_playful = cosine(v_oov, v_playful)
cos_oov_computer = cosine(v_oov, v_computer)
oov_norm = float(np.linalg.norm(v_oov))
c3_ok = oov_word not in known_words and oov_norm > 0.5 and cos_oov_playful > cos_oov_computer + 0.4
cases.append(dict(
name="subword_char_ngram_oov",
inputs=dict(known_words=known_words, oov_word=oov_word, char_n=3),
prerequisites="为 5 个已知英文词的所有字符 3-gram 分配确定性子词向量,模拟 FastText 子词求和平均。",
action="为未登录词 playfulness 合成向量并比较其与词根近亲 playful 及无关词 computer 的余弦相似度。",
expected=dict(oov_nonzero_vector=True, closer_to_playful_than_computer=True),
actual=dict(
oov_nonzero_vector=(oov_norm > 0.5),
closer_to_playful_than_computer=(cos_oov_playful > cos_oov_computer + 0.4),
),
measurements=dict(
oov_norm=round(oov_norm, 4),
cos_playfulness_playful=round(cos_oov_playful, 4),
cos_playfulness_computer=round(cos_oov_computer, 4),
matched_subwords=[ng for ng in char_ngrams(oov_word, 3) if ng in ng_vecs],
),
passed=c3_ok,
))
# 4. Sentence representation (mean vs SIF) + Contextual self-attention shift for polysemous "bank"
rng_ctx = np.random.default_rng(123)
toks = ["the", "is", "bank", "river", "water", "muddy", "grassy", "loan", "credit", "cash", "deposit"]
base_e = {t: rng_ctx.normal(0.0, 1.0, size=8) for t in toks}
freqs = {
"the": 0.25, "is": 0.20, "bank": 0.02, "river": 0.01, "water": 0.01,
"muddy": 0.01, "grassy": 0.01, "loan": 0.01, "credit": 0.01, "cash": 0.01, "deposit": 0.01,
}
a_sif = 1e-3
def mean_pool(seq):
return np.mean([base_e[w] for w in seq], axis=0)
def sif_pool(seq):
ws = [a_sif / (a_sif + freqs[w]) for w in seq]
return np.sum([w * base_e[tok] for w, tok in zip(ws, seq)], axis=0) / sum(ws)
# Notice stopword noise shifts mean_pool much more than SIF
s_clean = ["river", "bank", "water"]
s_noisy = ["the", "the", "is", "river", "bank", "water"]
mean_shift = 1.0 - cosine(mean_pool(s_clean), mean_pool(s_noisy))
sif_shift = 1.0 - cosine(sif_pool(s_clean), sif_pool(s_noisy))
# Pure-NumPy single-head scaled dot-product self-attention producing contextualized "bank" vectors
wq = rng_ctx.normal(0.0, 0.25, size=(8, 8))
wk = rng_ctx.normal(0.0, 0.25, size=(8, 8))
wv = np.eye(8)
def self_attn(seq):
x = np.stack([base_e[w] for w in seq], axis=0)
q, k, v = x @ wq, x @ wk, x @ wv
scores = (q @ k.T) / math.sqrt(8.0)
scores -= scores.max(axis=1, keepdims=True)
att = np.exp(scores) / np.exp(scores).sum(axis=1, keepdims=True)
return att @ v
ctx_river_bank = self_attn(["grassy", "muddy", "river", "bank", "water"])[3]
ctx_loan_bank = self_attn(["bank", "loan", "credit", "cash", "deposit"])[0]
static_cos = cosine(base_e["bank"], base_e["bank"])
contextual_cos = cosine(ctx_river_bank, ctx_loan_bank)
c4_ok = bool(sif_shift < mean_shift * 0.1 and abs(static_cos - 1.0) < 1e-12 and contextual_cos < 0.85)
cases.append(dict(
name="sentence_pooling_sif_and_context_shift",
inputs=dict(sif_a=a_sif, attn_dim=8),
prerequisites="对比简单词向量平均与 SIF 加权平均对高频停用词的抗扰度,并用纯 NumPy 缩放点积自注意力演示上下文表示。",
action="计算加入高频停用词后的句向量漂移量,以及多义词 bank 在不同语境下的上下文向量余弦相似度。",
expected=dict(sif_more_robust_than_mean=True, static_bank_identical=True, contextual_bank_distinct=True),
actual=dict(
sif_more_robust_than_mean=bool(sif_shift < mean_shift * 0.1),
static_bank_identical=bool(abs(static_cos - 1.0) < 1e-12),
contextual_bank_distinct=bool(contextual_cos < 0.85),
),
measurements=dict(
mean_pool_stopword_drift=round(mean_shift, 4),
sif_pool_stopword_drift=round(sif_shift, 6),
static_bank_cos=round(static_cos, 4),
contextual_bank_cos=round(contextual_cos, 4),
),
passed=c4_ok,
))
# 5. LDA Topic Modeling (sklearn LatentDirichletAllocation)
topic_docs = [
"python neural network deep learning gpu matrix model training",
"transformer attention nlp language neural model pretraining tokens",
"python neural algorithm software database model cloud code training",
"machine learning gradient descent neural optimizer python model",
"python neural tensor matrix vector learning model training",
"attention transformer nlp neural embedding python model tokens",
"football match goal striker stadium coach championship league",
"basketball match player tournament score coach championship team",
"tennis match tournament serve champion court coach league",
"football stadium marathon athlete medal track coach championship",
"soccer match team striker goal goalkeeper stadium league",
"basketball court match league score team coach championship",
]
lda_cv = CountVectorizer()
x_lda = lda_cv.fit_transform(topic_docs)
lda = LatentDirichletAllocation(n_components=2, random_state=42, max_iter=30)
doc_topics = lda.fit_transform(x_lda)
row_sums_ok = float(np.max(np.abs(doc_topics.sum(axis=1) - 1.0))) < 1e-12
dom = doc_topics.argmax(axis=1).tolist()
tech_topic = dom[0]
sports_topic = dom[6]
purity = (sum(1 for t in dom[:6] if t == tech_topic) + sum(1 for t in dom[6:] if t == sports_topic)) / len(dom)
c5_ok = row_sums_ok and tech_topic != sports_topic and purity == 1.0
cases.append(dict(
name="lda_topic_modeling_sklearn",
inputs=dict(n_docs=len(topic_docs), n_components=2, random_state=42),
prerequisites="在 12 条科技与体育双主题文档上运行 CountVectorizer + LatentDirichletAllocation(n_components=2)。",
action="验证文档-主题概率分布每行之和严格为 1 且主导主题完全分离科技与体育两组文档。",
expected=dict(doc_topic_rows_sum_to_1=True, two_topics_separated=True, purity_1=True),
actual=dict(
doc_topic_rows_sum_to_1=row_sums_ok,
two_topics_separated=(tech_topic != sports_topic),
purity_1=(purity == 1.0),
),
measurements=dict(
dominant_topics=dom,
topic_purity=round(purity, 4),
doc0_probs=[round(float(x), 4) for x in doc_topics[0]],
doc6_probs=[round(float(x), 4) for x in doc_topics[6]],
),
passed=c5_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-representation-lab/explore-text-representation.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-text-representation.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。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a562.zip
课程关联工程包(登记关联21章) · 含当前章节或实例 · mbskycom202612a545.zip