文本表示方法
系统核对词袋模型、TF-IDF(区分教科书公式与 sklearn 平滑+L2 归一化)、N-gram、Word2Vec/GloVe/FastText、ELMo/BERT 上下文表示以及 Doc2Vec/句向量/LDA 主题建模,并实测 5 项 NumPy/sklearn 文本表示实验。
学完这一章,你能够
- 系统核对词袋模型、TF-IDF(区分教科书公式与 sklearn 平滑+L2 归一化)、N-gram、Word2Vec/GloVe/FastText、ELMo/BERT 上下文表示以及 Doc2Vec/句向量/LDA 主题建模,并实测 5 项 NumPy/sklearn 文本表示实验。
传统离散文本表示:BoW、TF-IDF 与 N-gram
文本表示负责将非结构化文字映射为可计算的数值向量。词袋模型(Bag of Words)忽略语序和语法,仅统计词表各词在文档中的出现频次,优点是实现直观、计算快、适合小数据基线,缺点是维度高且稀疏,无法区分词序、同义词与多义词。本站对 4 句标准英文示例语料运行 CountVectorizer,实测得到 9 词词表与 (4, 9) 频次矩阵。
TF-IDF 通过词频(TF)与逆文档频率(IDF = log(N/df))相乘压低高频停用词权重、凸显区分性关键词,但仍属于高维稀疏表示且不能捕捉语义相近关系。需特别区分教科书未平滑公式与 scikit-learn 默认实现:TfidfVectorizer 默认采用原始频次、平滑 IDF = log((1+N)/(1+df)) + 1 并对每行做 L2 归一化。本站实测手算 sklearn 公式与 TfidfVectorizer 最大绝对误差为 0.0(首句较罕见词 first 得 0.5803 高于常见词 document 的 0.4698;按教科书未平滑公式两者分别为 0.1386 与 0.0575)。
N-gram 通过提取连续 n 个词(Unigram、Bigram、Trigram)捕获局部语序与固定短语搭配,代价是特征维度随 n 急剧膨胀且依然无法建模长距离依赖。本站对相同 4 句运行 CountVectorizer(ngram_range=(2, 2)),维度由 9 个 unigram 扩增至 13 个 bigram(形状 (4, 13))。
静态稠密词向量:Word2Vec、GloVe 与 FastText
词向量将词汇压缩至 50–300 维低维稠密空间,能够编码语义相似与线性类比关系(如 king - man + woman ≈ queen)。2013 年 Google 提出的 Word2Vec 包含 CBOW(上下文预测中心词)和 Skip-gram(中心词预测上下文)两种局部窗口架构;2014 年 GloVe 则基于全局词共现矩阵,优化词向量点积逼近共现次数对数(两者差异见下表)。本站在 18 词王室/宠物双域语料上用纯 NumPy 实测 PPMI+SVD 全局共现分解与 Skip-gram 负采样 SGD:4 维 SVD 向量使 cos(king, queen) = 1.0、cos(cat, dog) = 1.0 而跨域 cos(king, cat) = 0.0;30 轮 Skip-gram 负采样损失由 1.3871 单调降至 0.3269。
Facebook 提出的 FastText 把每个词拆解为字符 n-gram 子词集合之和,因此能为未登录词(OOV)合成有效向量,对形态变化丰富的语言尤为有利。本站用纯 NumPy 字符 3-gram 子词向量模拟 FastText:词表外未见词 playfulness 命中 9 个共享子词片段,合成模长 1.3627 的非零向量,其与形态近亲 playful 的余弦相似度达 0.8519,远高于无关词 computer 的 0.4349。
上下文感知表示与预训练语言模型
静态词向量为同一多义词只保留单一向量,而 2018 年 ELMo 利用多层双向 LSTM 语言模型动态结合整句上下文,并可加权融合不同隐层的句法与语义特征。
BERT 引入 Transformer 双向编码器及掩码语言模型(MLM)、下一句预测(NSP)预训练目标,衍生出 RoBERTa(移除 NSP 并优化动态掩码训练)、DistilBERT(知识蒸馏轻量化)与 ALBERT(跨层参数共享与因式分解嵌入)等变体,确立了“大规模无监督预训练 + 下游任务微调”的现代范式(代表模型演进见下表)。本站用纯 NumPy 缩放点积自注意力实测多义词 bank:静态查表余弦恒为 1.0,而经河岸语境与贷款语境自注意力融合后,两处 bank 上下文向量余弦相似度降至 0.4456。
文档级表示、主题建模与方法选型总结
文档与句子级表示既可通过 Doc2Vec(PV-DM 类似 CBOW 拼入文档 ID、PV-DBOW 类似 Skip-gram)直接学习,也可由词向量简单平均、SIF 平滑逆频率加权平均或 BERT [CLS]/均值池化与 Sentence-BERT 获得。代码勘误:来源 Doc2Vec 示例将未分词字符串列表 corpus 直接传入 TaggedDocument(doc, [i]),实际 Gensim 要求 words 参数为词元列表,传字符串会被逐字符拆分。本站对比简单平均与 SIF(a=0.001):在句子前注入 3 个高频停用词后,简单平均句向量余弦漂移达 0.3046,而 SIF 漂移仅 0.001106。
潜在狄利克雷分配(LDA)把文档建模为多主题混合概率分布、把主题建模为词表概率分布,经变分推断或 Gibbs 采样学习,常用于文档聚类、内容推荐与文本摘要。本站对 12 条科技与体育双主题文档运行 CountVectorizer + LatentDirichletAllocation(n_components=2, random_state=42),实测文档-主题概率行和严格为 1.0,主导主题分类纯度达 1.0(科技首篇主主题概率 0.9489,体育首篇另一主题概率 0.9437)。综合选型应依据语义深度需求、语料规模、算力预算与语言形态特点,在传统稀疏表示、静态词向量、上下文预训练模型与文档主题表示之间权衡。
Word2Vec 与 GloVe 静态词向量对比
| 特性 | Word2Vec | GloVe |
|---|---|---|
| 训练方式 | 基于局部上下文滑动窗口(CBOW / Skip-gram)在线更新 | 先统计全局词共现矩阵再分解回归对数共现次数 |
| 计算效率 | 流式逐窗负采样更新,内存占用低、训练效率较高 | 需构建并存储全局共现矩阵,内存与预处理开销较高 |
| 小数据集表现 | 负采样与窗口迭代在中小型语料上较易拟合 | 共现矩阵在极小语料上稀疏,表现一般 |
| 大数据集表现 | 在大规模语料上训练稳定且效果良好 | 充分吸收全局统计信息,在大语料语义类比中往往表现更优 |
典型文本表示模型演进对比
| 模型 | 发布时间 | 主要特点 |
|---|---|---|
| Word2Vec | 2013 | 浅层神经网络静态词向量(CBOW/Skip-gram),无法区分多义词 |
| GloVe | 2014 | 融合全局共现统计与局部窗口的静态词向量 |
| ELMo | 2018 | 基于多层双向 LSTM 语言模型,生成上下文相关的动态词表示 |
| BERT | 2018 | 基于 Transformer 双向编码器,经 MLM/NSP 预训练捕捉深层双向上下文 |
| GPT-3 | 2020 | 1750 亿参数单向自回归 Transformer,具备强生成与少样本上下文学习能力 |
运行 BoW/TF-IDF/Bigram、PPMI+SVD 与 Skip-gram、FastText 子词、SIF/自注意力上下文漂移及 LDA 实验
"""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()
- 核对 sklearn 平滑 TF-IDF 与手算差 0.0、PPMI+SVD 同域余弦 1.0/跨域 0.0 与 Skip-gram 损失收敛、FastText OOV 子词相似 0.8519、SIF 停用词漂移 0.001106 及 LDA 纯度 1.0。
所需环境: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。
当前源码 SHA256:2c17108b7c70ce1914810317a8e4641b73112b7df5cd3ee1cdb7d3e56238d06c
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境: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。
ZIP SHA256:1c6b2c5f84cb6325e6ac4f547980a19f562293121dfd35310afe93cf74ecace2
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
为什么 scikit-learn 默认 TfidfVectorizer 算出的数值与教科书公式 (tf/len)*log(N/df) 不一致?
展开参考解答
TfidfVectorizer 默认使用文档内原始词频而非除以总词数,采用平滑公式 idf(t) = log((1+N)/(1+df(t))) + 1 以防除零与全文档词归零,最后还对每篇文档向量执行 L2 单位归一化。