Words as vectors
阅读约需 39分钟 分钟,10节中含8个示例。
这部分尚未翻译,因此以英文显示。
By the end of this chapter you can turn every token of the store's text into a short vector of numbers, so that tokens used in similar ways get similar vectors, by two methods: compressing counts of which tokens appear together, and training a small model to predict each token's neighbours. You'll measure what those vectors know, where they fail, and how they let a model relate text it has never seen to text it has.
Chapter 3 ended on a limit that counting can't get past. Its 4-gram model had seen patio bar stool many times, and suggested stool after patio bar. After outdoor bar, which no training name contains, it fell back to generic suggestions, because a count of one context tells it nothing about another. A shopper, or any reader, knows that outdoor and patio mean nearly the same thing to the store, and a model needs some way to know it too. This chapter gives every token a vector, a list of numbers, and arranges the vectors so that tokens used alike sit close together.
Vectors need text that shows how words get used, and the store, an online seller of furniture and home goods, has plenty of it in its catalog's names and descriptions. Its training split, the 80% of products that models learn from, holds 2,744,320 tokens of that text, and every vector in this chapter comes from it alone, through the store's tokenizer from chapter 2.
独热向量什么也不知道
到目前为止,每个模型都把词元当作名字来处理:patio是表中的一项,outdoor是另一项,二者之间没有任何联系。写成向量,就是独热(one-hot)编码:每个词元对应一个与词表等长的向量,其自身所在的位置为 1,其余位置全为 0。为了衡量两个向量有多相似,本书使用余弦相似度:即两个向量夹角的余弦,方向相同时为 1,互成直角时为 0。它不考虑向量的长度,只比较方向。
给训练文本中出现频率最高的 2,000 个词元分配独热向量,然后将patio分别与outdoor、sofa以及它自身进行比较。这 2,000 个词元约占商店分词器词表的一半,这样本章中的每个矩阵都足够小,几秒钟即可算完:
1"""One-hot vectors for the 2,000 most frequent tokens, and the cosine similarity of patio with outdoor, with sofa and with2itself. The prose's point rests on the patio–outdoor and patio–sofa lines: patio is as unrelated to outdoor as to sofa."""3import numpy as np45from lib.vectors import BREAK, training_ids # the book's shared module; BREAK marks the gap between two texts67ids, vocabulary = training_ids() # each training token as a number; RARE for tokens outside the vocabulary8index = {token: i for i, token in enumerate(vocabulary)}91011def one_hot(token):12 vector = np.zeros(len(vocabulary))13 vector[index[token]] = 1.0 # one column per token: 1 for this token, 0 everywhere else14 return vector151617def cosine(a, b):18 return float(a @ b / (np.linalg.norm(a) * np.linalg.norm(b)))192021print("numbers in each vector:", len(vocabulary))22print("cosine(patio, outdoor):", cosine(one_hot("patio</w>"), one_hot("outdoor</w>"))) # </w> marks a word's last token: patio</w> is the whole word23print("cosine(patio, sofa):", cosine(one_hot("patio</w>"), one_hot("sofa</w>")))24print("cosine(patio, patio):", cosine(one_hot("patio</w>"), one_hot("patio</w>")))25print("share of training tokens with a vector:", f"{(ids >= 0).sum() / (ids != BREAK).sum():.0%}") # ids >= 0 are the kept tokens; BREAK gaps aren't tokens
python one-hot-vectors.pynumbers in each vector: 2000
cosine(patio, outdoor): 0.0
cosine(patio, sofa): 0.0
cosine(patio, patio): 1.0
share of training tokens with a vector: 91%
独热编码认为,这两个户外词汇之间的无关程度,与庭院和沙发之间完全相同。patio与outdoor的余弦相似度是0.0,patio与sofa的余弦相似度也是这个值。只有词元与自身比较时,得分才是1.0。每个向量有2000个数。获得向量的这 2,000 个词元占训练文本的91%;其余词元更为罕见,本章不予考虑。任意两个不同的词元之间都互成直角,因此,关于其中一个词元学到的东西,无法迁移到另一个词元上。
这与第 3 章中计数方法的缺陷如出一辙,只是换了一种形式。读取独热向量的模型,必须针对每个词元单独学习,依据的只是该词元自身出现过的上下文。罕见词元所得甚少,未曾见过的组合则一无所得。
工作准则: 不要把独热向量输入需要建立词元之间关系的模型。只把它们当作索引使用,如后续各节所做的那样,用来查找每个词元对应的已学习向量。
用周围的词元描述一个词元
出路在于通过一个词所处的“语境”来描述它。两个词如果出现在相同的邻近词之间,就很可能含义相近,即使它们很少同时出现。例如 patio 和 outdoor,它们都常出现在 furniture、chair 和 umbrella 附近。因此,可以用邻近词元来描述每个词元:对每一对词元,统计其中一个出现在另一个的小窗口内的次数,这里取两侧各两个词元,并且不跨越两个商品文本之间的间隔。每个词元对应的一行计数,就是一个表示它出现在哪些词元附近的向量。
在训练集划分的名称和描述中统计共现次数,并列出最常出现在 patio 附近的词元:
1"""Counts how often each of the 2,000 kept tokens appears within two tokens of another, and lists the six tokens seen most2often near patio. The prose's point rests on that list: punctuation and common words come first."""3import numpy as np45from lib.vectors import BREAK, cooccurrence, training_ids # the book's shared module; BREAK marks the gap between two texts67ids, vocabulary = training_ids() # each training token as a number; RARE for tokens outside the vocabulary8counts = cooccurrence(ids, len(vocabulary)) # how often each token appears within 2 tokens of another9patio = vocabulary.index("patio</w>") # </w> marks a word's last token: patio</w> is the whole word, not a piece of a longer one1011print("training tokens:", f"{int((ids != BREAK).sum()):,}") # RARE tokens count here, since they are tokens; only the BREAK gaps don't12print("vocabulary kept:", f"{len(vocabulary):,}")13print("tokens near patio, counting repeats:", f"{int(counts[patio].sum()):,}") # the row's total, a token counted again at each repeat14for i in np.argsort(-counts[patio], kind="stable")[:6]: # the minus sorts most frequent first; ties keep vocabulary order15 print(f" near patio: {vocabulary[i]:<12} {int(counts[patio, i]):>6,}")
python cooccurrence-counts.pytraining tokens: 2,744,320
vocabulary kept: 2,000
tokens near patio, counting repeats: 8,790
near patio: ,</w> 646
near patio: or</w> 448
near patio: with</w> 433
near patio: your</w> 381
near patio: .</w> 340
near patio: furniture</w> 249
在 patio 前后两个位置之内共有 8,790 个词元(同一词元每次出现都重复计数),其中最常见的结果令人失望:一个逗号、or、with、your 和一个句号,排在第一个与庭院有关的词 furniture 之前。这些词元几乎出现在所有词的附近,因为它们无处不在。一行原始计数主要反映的是每个邻近词本身有多常见,而不是这一行所属词元有什么特别之处。
因此,原始计数并不适合作为向量。两个都经常出现的词元,会因为共享同样的高频邻近词(逗号和 with)而显得相似,无论它们的含义是什么。真正重要的是:相对于这些邻近词本身的常见程度,哪些邻近词与某个词元同时出现的频率高于预期。
工作准则: 在模型将要学习的文本中,于小窗口(两到五个词元)内统计共现次数,并且不要跨越文档边界。不要把原始计数直接当作向量:要重新加权,如下一节所做的那样,使高频邻近词不再占据主导。
以意外程度加权共现
修正的办法是把每个计数与随机情形下的预期值相比较。如果 patio 与 furniture 的出现彼此独立,它们共现的次数就应与各自的单独频率所暗示的次数大致相当。逐点互信息(pointwise mutual information,简称 PMI)衡量真实计数偏离随机预期的程度:即两个词元实际共现的频率与随机情形下共现的频率之比的对数(Church and Hanks, 1990)。用符号表示,对词元 a 和 b:
PMI(a, b) = log [ P(a, b) / (P(a) · P(b)) ]
其中 P(a, b) 是 a 与 b 一同出现的计数在全部共现计数中所占的份额,P(a) 和 P(b) 分别是各词元所占的份额。当两个词元一同出现的次数多于随机预期时,PMI 为正;少于随机预期时,PMI 为负。负值并不可靠,因为"少于随机预期"通常意味着"根本很少见到",所以正 PMI(PPMI)把每个负值都替换为零。本书的共享模块 lib.vectors 依据上一节的共现计数计算 PPMI,只需三行:先算出每个词对在随机情形下的预期计数,再取真实计数与它之比的对数,凡结果为负或词对从未出现之处一律取零:
expected = counts.sum(1, keepdims=True) * counts.sum(0, keepdims=True) / total
pmi = np.log(counts / expected)
return np.where(counts > 0, np.maximum(pmi, 0), 0.0)
重新加权的目的是避免高频邻词占据主导,因此把原始计数换成 PPMI,再次列出 patio 最强的邻词:
1"""Reweights the co-occurrence counts with positive PMI, and lists the six tokens with the strongest weight beside patio.2The prose's point rests on that list: the commas and common words of the raw counts are gone."""3import numpy as np45from lib.vectors import cooccurrence, ppmi, training_ids67ids, vocabulary = training_ids() # each training token as a number; RARE for tokens outside the vocabulary8weights = ppmi(cooccurrence(ids, len(vocabulary))) # PPMI of the co-occurrence counts, within the same window of 2 tokens9patio = vocabulary.index("patio</w>") # </w> marks a word's last token: patio</w> is the whole word1011print("share of PPMI entries that are zero:", f"{(weights == 0).mean():.0%}") # zero for pairs that never co-occur and for pairs seen no more often than chance12for i in np.argsort(-weights[patio], kind="stable")[:6]: # the largest weights first; ties keep vocabulary order13 print(f" PPMI with patio: {vocabulary[i]:<12} {weights[patio, i]:.2f}")
python ppmi-neighbours.pyshare of PPMI entries that are zero: 86%
PPMI with patio: porch</w> 4.51
PPMI with patio: deck</w> 4.19
PPMI with patio: backyard</w> 3.97
PPMI with patio: sectional</w> 3.75
PPMI with patio: furniture</w> 3.59
PPMI with patio: garden</w> 3.53
逗号已经消失。按 PPMI 排序,patio 最强的邻词是 porch、deck、backyard、sectional、furniture 和 garden:这些都是人们会与露台联想到一起的词,按其在该词附近出现的频率超出随机预期的程度排序。大多数词元对一同出现的次数并不超过随机预期,这正是 PPMI 矩阵中有 86% 为零的原因。
PPMI 向量已经有用:两个词元的 PPMI 行相似,说明它们有相似的特征性邻词。但每个向量仍有 2,000 个数,大部分为零,而两个邻词相关但不完全相同的词元,例如 deck 与 porch,可能只共享很少的非零项。
工作准则: 在把共现计数用作向量之前,先用正 PMI 对其重新加权。要预料到 PMI 会高估由稀有词元构成的词对,因为它们寥寥几次的共现看起来远高于随机预期;这正是只保留高频词元(如本章所做)或要求最低计数的原因之一。
将计数压缩为稠密向量
一个由 2,000 个数字组成的 PPMI 向量大部分是零,空间很大,信息很少。把它压缩成短而稠密的向量,就能保留共现中最强的模式,去掉噪声,并让邻居相关的词元彼此靠近,即使它们共有的确切邻居很少。所用的工具是奇异值分解(SVD)。它找出 64 个方向,这些方向合在一起能最好地重构 PPMI 的各行,并按每个方向解释各行的程度为其加权。一个词元在这些方向上的 64 个加权坐标就是它的新向量,即嵌入(embedding),也就是代表一个词元的稠密向量。方法 lib.vectors.svd_vectors 负责计算这些向量,并把每个向量缩放为单位长度;方法 lib.vectors.nearest 则找出与任意向量余弦相似度最高的词元。
六个词元各自的四个最近邻,显示了这 64 个数字保留了什么:
1"""Compresses the PPMI matrix into 64 numbers per token, and lists the four nearest neighbours of six tokens. The prose's2point rests on the first two lists and the last line: patio and outdoor are each other's nearest neighbour, at the cosine printed last."""3from lib.vectors import DIMENSIONS, nearest, svd_vectors # svd_vectors does the PPMI and SVD steps; nearest ranks tokens by cosine similarity45vectors, vocabulary = svd_vectors() # one 64-number row per token, each scaled to unit length6index = {token: i for i, token in enumerate(vocabulary)}78print("dimensions per token:", DIMENSIONS)9for token in ["patio</w>", "outdoor</w>", "sofa</w>", "oak</w>", "blue</w>", "48</w>"]: # </w> marks a word's last token10 neighbours = nearest(vectors, vocabulary, vectors[index[token]], k=4, skip=(token,)) # skip leaves out the token itself, which would otherwise be its own nearest at 1.0011 print(f"{token:<12} -> " + ", ".join(f"{t} {s:.2f}" for t, s in neighbours))12print("cosine(patio, outdoor):", f"{float(vectors[index['patio</w>']] @ vectors[index['outdoor</w>']]):.2f}") # unit-length vectors, so the dot product is the cosine
python svd-neighbours.pydimensions per token: 64
patio</w> -> outdoor</w> 0.84, bistro</w> 0.79, porch</w> 0.79, lounge</w> 0.77
outdoor</w> -> patio</w> 0.84, porch</w> 0.82, indoor</w> 0.80, furniture</w> 0.74
sofa</w> -> sectional</w> 0.93, chaise</w> 0.90, loveseat</w> 0.89, lounge</w> 0.87
oak</w> -> walnut</w> 0.96, veneers</w> 0.90, espresso</w> 0.89, weathered</w> 0.88
blue</w> -> green</w> 0.86, beige</w> 0.86, pur 0.80, abstract</w> 0.79
48</w> -> 36</w> 0.94, 32</w> 0.93, 24</w> 0.92, 30</w> 0.89
cosine(patio, outdoor): 0.84
现在每个词元都有 64 个数字,它的邻居读起来就像为家具店编的同义词词典。patio 与 outdoor 互为最近邻,余弦相似度为 0.84,而它们的独热向量得分为零。sofa 与 sectional、chaise、loveseat 相邻;oak 与 walnut、espresso 相邻,后者是一种木材饰面;blue 与其他颜色相邻;48 与其他以英寸计的尺寸相邻。
这些都不是人教给它的。这个方法从未见过 sofa 的定义、颜色的列表,也没有任何提示说明 48 是一个数字。它发现这些词元在商店文本中出现在同类邻居之间,SVD 因此把它们放在了相近的位置。这正是第 3 章的计数所缺少的性质:模型对 patio bar stool 学到的东西,现在可以通过嵌入迁移到 outdoor bar stool。
工作准则: 用 SVD 把 PPMI 压缩到 50 至 300 维,并按本节的做法检查结果:列出若干词元的最近邻并逐一阅读。如果邻居多是高频功能词,说明重新加权出了问题;如果邻居互不相关,说明窗口或词表太小。
通过预测邻近词来学习向量
获得嵌入的另一种方法是通过预测来学习,本书中每一个神经语言模型的嵌入都是这样得到的。带负采样的 Skip-gram(skip-gram with negative sampling)是 word2vec 背后的方法,它为每个词元配备两个向量,一个用于该词元作为中心词元时,另一个用于它作为邻近词元时,并只用一个任务来训练它们:给定一个词元,把它真实的邻近词元与随机词元区分开来(Mikolov et al., 2013a;Mikolov et al., 2013b)。对于一个词元及其某个真实邻近词元,模型用二者向量的点积为这一对打分,再用逻辑函数把分数转换为概率,并微调向量使该概率上升。对于从词表中抽取的若干随机噪声词元,模型则微调向量使概率下降。在数百万个词对上反复进行之后,拥有相同邻近词元的词元最终会得到相近的向量。这并非巧合:Levy 和 Goldberg 证明,以这种方式训练的带负采样 skip-gram,实际上是在分解一个 PMI 矩阵,该矩阵再减去噪声词元个数的对数,这与 SVD 分解 PPMI 的做法如出一辙(Levy and Goldberg, 2014)。
记 v 为中心词元的向量,u 为真实邻近词元的向量,uₙ 为各个噪声词元的向量,σ 为逻辑函数 σ(s) = 1 / (1 + e⁻ˢ),它把分数转换为概率。一个词对的 skip-gram 损失,等于真实邻近词元带来的意外程度,加上每个噪声词元并非邻近词元所带来的意外程度:
L = −log σ(v·u) − Σₙ log σ(−v·uₙ)
lib.skipgram.step 用三行梯度下降来降低它,其中 real 为 σ(v·u),fake 保存各噪声词元对应的 σ(v·uₙ),rate 为步长:
np.add.at(inputs, centre, -rate * grad_v) # move v: towards u, away from each uₙ
np.add.at(outputs, context, -rate * (real - 1)[:, None] * v) # move u towards v
np.add.at(outputs, noise, -rate * fake[:, :, None] * v[:, None, :]) # move each uₙ away from v
对一个真实词对 patio 与 umbrella 做三次更新,以 sofa 和 48 作为噪声词元。中心向量一开始取较小的随机值,邻近向量则从零开始,与 lib.skipgram.train 的起始方式相同:
1"""Three updates of skip-gram with negative sampling on one real pair, patio and umbrella, with sofa and 48 as noise tokens,2printing each pair's probability before and after. The prose's point rests on the four probability lines: umbrella's rises,3and the noise tokens' fall."""4import numpy as np56from lib.skipgram import sigmoid, step # one gradient step, and the logistic function7from lib.vectors import training_ids89_, vocabulary = training_ids()10rng = np.random.default_rng(2026) # a fixed seed, so the starting vectors are the same on every run11inputs = (rng.random((len(vocabulary), 8)) - 0.5) / 8 # each token's vector as a centre, small and random12outputs = np.zeros((len(vocabulary), 8)) # and as a neighbour: zero, as training starts13centre, context = [vocabulary.index("patio</w>")], [vocabulary.index("umbrella</w>")] # the real pair: patio as the centre, umbrella its real neighbour14noise = np.array([[vocabulary.index("sofa</w>"), vocabulary.index("48</w>")]]) # noise tokens, picked by hand here; training draws them at random151617def chances():18 real = sigmoid(inputs[centre[0]] @ outputs[context[0]])19 fake = sigmoid(outputs[noise[0]] @ inputs[centre[0]])20 return real, fake212223before = chances() # zero neighbour vectors give every score zero, so every probability is one half24for _ in range(3): # three updates on the same pair25 step(np.array(centre), np.array(context), noise, inputs, outputs, rate=1.0) # rate 1.0, far above the 0.025 that training starts from, so three steps show26after = chances()27print("P(umbrella is a real neighbour of patio), before:", f"{before[0]:.3f}")28print("P(umbrella is a real neighbour of patio), after 3 steps:", f"{after[0]:.3f}")29print("P(sofa, 48 are real neighbours), before:", ", ".join(f"{p:.3f}" for p in before[1]))30print("P(sofa, 48 are real neighbours), after 3 steps:", ", ".join(f"{p:.3f}" for p in after[1]))
python skipgram-step.pyP(umbrella is a real neighbour of patio), before: 0.500
P(umbrella is a real neighbour of patio), after 3 steps: 0.525
P(sofa, 48 are real neighbours), before: 0.500, 0.500
P(sofa, 48 are real neighbours), after 3 steps: 0.475, 0.475
训练把真实的邻近词元拉近,把随机词元推远,三次更新便是它的缩影。在任何更新之前,邻近向量全为零,因此每个分数都是零,而 σ(0) 等于二分之一:模型一无所知。三次更新之后,umbrella 作为 patio 的邻近词元,得分为 0.525,此前为 0.500,而 sofa 和 48 已降至 0.475, 0.475。训练所做的就是这些,重复数百万次。
**工作准则:**训练嵌入时,像 lib.skipgram.train 那样,第二组向量从零开始,第一组从较小的随机值开始,并按词频的 0.75 次幂成比例地抽取噪声词元,Mikolov 等人发现这比直接按词频抽取效果更好。在运行数百万次之前,先手工检查一次更新:概率朝错误的方向变化,说明梯度的符号有误。
比较学习得到的向量与计数得到的向量
在商店的全部训练文本上训练 skip-gram 需要进行数百万次更新,其确切结果取决于机器的浮点运算,而不同处理器之间的浮点运算会有细微差异。因此它只运行一次,即在 recordings/skipgram.py 中,使用本书自己的代码和固定的随机种子,各示例读取它保存的向量。它的清单记录了各项设置:窗口为两个词元,64 维,每个词对使用五个噪声词元,对文本遍历两遍。有一项设置是固定在 lib.skipgram 中而没有记录的:以逗号等高频词元为中心的词对大多被跳过,阈值为 10⁻⁴,这样可以避免它们主导训练(Mikolov et al., 2013b,他们对更大的文本建议取 10⁻⁵ 左右)。
向记录下来的 skip-gram 向量查询同样这六个词元的近邻,并将结果与 SVD 的比较:
1"""Reads the skip-gram vectors and training losses that recordings/skipgram.py saved, and lists the same six tokens' four2nearest neighbours as the SVD example. The prose's point rests on the two loss lines and on outdoor's nearest neighbour."""3import json45import numpy as np67from lib.vectors import nearest89recorded = "data/recorded/skipgram/" # saved by recordings/skipgram.py, which trains once: its values depend on the machine10vectors = np.load(recorded + "vectors.npy")11vocabulary = json.load(open(recorded + "vocabulary.json", encoding="utf-8"))12losses = np.load(recorded + "losses.npy") # one loss per batch, in training order13index = {token: i for i, token in enumerate(vocabulary)}1415print("training loss, first batch:", f"{losses[0]:.2f}") # index 0: the first batch, when nothing has been learned yet16print("training loss, last 100 batches:", f"{losses[-100:].mean():.2f}")17for token in ["patio</w>", "outdoor</w>", "sofa</w>", "oak</w>", "blue</w>", "48</w>"]:18 neighbours = nearest(vectors, vocabulary, vectors[index[token]], k=4, skip=(token,)) # skip leaves out the token itself19 print(f"{token:<12} -> " + ", ".join(f"{t} {s:.2f}" for t, s in neighbours))
python skipgram-neighbours.pytraining loss, first batch: 4.16
training loss, last 100 batches: 2.05
patio</w> -> porch</w> 0.77, bistro</w> 0.69, garden</w> 0.69, couch</w> 0.67
outdoor</w> -> indoor</w> 0.75, patio</w> 0.66, garden</w> 0.65, living</w> 0.61
sofa</w> -> couch</w> 0.85, sleeper</w> 0.84, chaise</w> 0.80, sectional</w> 0.78
oak</w> -> walnut</w> 0.91, espresso</w> 0.84, weathered</w> 0.81, glossy</w> 0.80
blue</w> -> beige</w> 0.88, gray</w> 0.87, green</w> 0.85, brown</w> 0.80
48</w> -> 36</w> 0.94, 32</w> 0.92, 1.5</w> 0.89, 24</w> 0.89
该模型学会了区分真实的近邻与噪声:它的训练损失从第一个批次的 4.16 降到了最后一百个批次的 2.05。对多数词元,它的近邻与 SVD 的一致:sofa 对应 sectional 和 chaise,oak 对应 walnut 和 espresso,颜色对应颜色,尺寸对应尺寸;对另一些词元则侧重点不同:skip-gram 把 outdoor 放在最接近 indoor 的位置,因为这两个词在 indoor or outdoor use 之类的描述中出现在相同的位置上。
这一差异值得注意。由近邻构建的向量会把用在相同位置上的词放在一起,而反义词往往正是如此:这里的 indoor 与 outdoor 是一例,在下一节中还有 small,它的最近邻既包括 larger,也包括 smaller。相似的向量表示用法相似,而不是含义相似。
**工作准则:**把计数得到的嵌入(PPMI 和 SVD)与学习得到的嵌入(skip-gram)视为相近的备选方案:在几百万个词元的规模上,它们给出相似的近邻,而计数得到的嵌入是确定性的,速度也快。当嵌入本来就是你要训练的更大模型的一部分时,优先选择学习得到的嵌入,本书后面的每一章都是如此。切勿在未检查反义词的情况下,把高相似度当作同义。
类比,以及类比在何处失效
嵌入向量以能够通过算术运算完成类比而著称:如果 chair 与 chairs 之间的差是表示“复数”的方向,那么把它加到 table 上,结果应当落在 tables 附近。在向量中,“a 之于 b,相当于 c 之于什么?”的答案,是与 b − a + c 最接近的词元,但要排除问题中的这三个词元(Mikolov et al., 2013a)。这是检验向量是否学到一致关系的一项简明测试,也是观察其局限的好地方。
在 skip-gram 向量上做三个类比,可以看出算术在哪里成立、在哪里失效;这三个类比引出了三个词元,它们的最近邻则说明了原因:
1"""Three analogies on the skip-gram vectors, each answered by the tokens nearest b minus a plus c; whether lamps and light2have vectors at all; and the nearest tokens to a few single words. The prose rests on the three analogy lines, the lamps line and the neighbour lists."""3import json45import numpy as np67from lib.vectors import nearest89vectors = np.load("data/recorded/skipgram/vectors.npy") # saved by recordings/skipgram.py, which trains once10vocabulary = json.load(open("data/recorded/skipgram/vocabulary.json", encoding="utf-8"))11index = {token: i for i, token in enumerate(vocabulary)}1213for a, b, c in [("chair", "chairs", "table"), ("chair", "chairs", "lamp"), ("black", "white", "dark")]: # each reads: a is to b as c is to what14 a, b, c = (word + "</w>" for word in (a, b, c)) # the tokenizer marks each word's last token with </w>, so words are looked up in that form15 query = vectors[index[b]] - vectors[index[a]] + vectors[index[c]] # b - a + c: "c, changed the way a became b"16 answers = nearest(vectors, vocabulary, query, k=3, skip=(a, b, c)) # the words in the question can't be their own answer17 print(f"{a} : {b} :: {c} : ? -> " + ", ".join(t for t, _ in answers))18print("lamps in the vocabulary:", "lamps</w>" in index)19print("light in the vocabulary:", "light</w>" in index)20for token in ["light</w>", "dark</w>", "small</w>"]:21 print(f"{token:<12} -> " + ", ".join(t for t, _ in nearest(vectors, vocabulary, vectors[index[token]], k=4, skip=(token,))))
python analogies.pychair</w> : chairs</w> :: table</w> : ? -> tables</w>, cup</w>, stools</w>
chair</w> : chairs</w> :: lamp</w> : ? -> tops</w>, coffee</w>, tray</w>
black</w> : white</w> :: dark</w> : ? -> brown</w>, blue</w>, glossy</w>
lamps in the vocabulary: False
light in the vocabulary: True
light</w> -> lights</w>, bulb</w>, dimmable</w>, candle</w>
dark</w> -> brown</w>, walnut</w>, gray</w>, espresso</w>
small</w> -> smaller</w>, larger</w>, displaying</w>, storing</w>
只有第一个类比得到了预期的答案:chair 之于 chairs,相当于 table 之于 tables,并且它是排名第一的答案。第二个失败,是因为 lamps 不在拥有向量的 2,000 个词元之中,所以根本找不到正确答案,算术运算只能返回最接近的那个词元。第三个的失败方式不同。light 在词表中,但按这些向量的判断,black 之于 white,相当于 dark 之于 brown。近邻列表说明了原因:light 与 lights、bulb、dimmable 和 candle 处在一起,因为在该商店的文本中,它多半指灯具,如 ceiling light,而不是灯罩;而 dark 与 brown、walnut 和 espresso 处在一起,这些都是它所描述的饰面。此外,small 既与 larger 相邻,也与 smaller 相邻:表示尺寸的词出现在相同的位置,无论它们指的是哪种尺寸。
类比是一种演示,而不是一种度量。它适用于文本中一致且频繁表达的关系,例如常见词的复数形式;对于罕见词、多义词,以及文本中很少明确说出的关系,它就会失效。模型并不使用类比,它使用的是向量的位置,而这些位置带有同样的长处和盲区。
工作准则: 不要用类比来评判嵌入向量,而要看它们对所服务的任务有多大帮助,下一节和后面各章都是这样做的。当某个类比失败时,先检查答案是否在词表中,以及这些词在你的文本中是否真的是你所设想的含义。
用向量查找相似名称
词元的嵌入只需再多一步,就能得到整段文本的嵌入:对文本中各词元的向量取平均,再把结果缩放为单位长度,相似的文本就会得到相似的向量。这是搜索引擎所说的语义检索的粗略版本,即按含义而不是按词语匹配来查找文本。本书的配套读物《搜索相关性入门》(A Primer on Search Relevance)用训练好的模型对此做了完整的构建(语义检索)。在这里,它用来检验本章着手解决的那个问题:第 3 章的计数模型无法把 outdoor bar 与 patio bar 联系起来。
把每个训练名称的 skip-gram 向量取平均,每个名称就变成一个向量。罕见词,最常见的是某个产品系列的名称,会按 第 1 章所解释的那样显示为 [name]。两个查询可以说明这样做的收获:outdoor bar,即曾难住第 3 章4-gram 模型的那个前缀,以及 patio umbrella:
1"""Averages each training name's skip-gram token vectors into one unit-length vector, and prints the four training names2nearest to each of two queries. The prose's point rests on the first query: two patio bar stool names come up for outdoor bar."""3import json45import numpy as np67from lib import bpe8from lib.store import load_products, masked910vectors = np.load("data/recorded/skipgram/vectors.npy")11vocabulary = json.load(open("data/recorded/skipgram/vocabulary.json", encoding="utf-8"))12index, tokenizer = {t: i for i, t in enumerate(vocabulary)}, bpe.store_tokenizer()131415def name_vector(text): # the average of the text's token vectors, at unit length16 found = [index[t] for t in tokenizer.encode(text) if t in index] # tokens outside the 2,000 kept have no vector, so they're left out17 average = vectors[found].mean(0) if found else np.zeros(vectors.shape[1]) # a text with no kept tokens gets the zero vector18 return average / (np.linalg.norm(average) or 1.0) # `or 1.0`: a zero average stays zero, rather than dividing by zero192021names = load_products("train")["name"].tolist() # the training split's product names, the texts to compare22matrix = np.array([name_vector(n) for n in names])23for query in ["outdoor bar", "patio umbrella"]:24 best = np.argsort(-(matrix @ name_vector(query)), kind="stable")[:4] # unit vectors, so the dot product is the cosine; the four largest, most similar first25 print(f"{query}: " + " | ".join(masked(names[i]) for i in best)) # [name]: a rare word
python name-vectors.pyoutdoor bar: outdoor modern industrial 5 piece bar height dining set | [name] bar & bar stool | 29.5 '' patio bar stool | 28.5 '' patio bar stool
patio umbrella: premium tight weave outdoor patio umbrella cover | patio lantern | garden patio 88 [name] rattan deck box | outdoor patio chair
平均后的向量把两个 patio bar stool 名称排在与 outdoor bar 最接近的名称之列,而这两个名称都不含 outdoor 一词。那个模型无法建立这种联系,因为它只有 patio bar stool 的计数,没有 outdoor bar 的计数。这种联系是通过 outdoor 和 patio 建立的,二者的向量很接近。对于 patio umbrella,最接近的名称是露台类和户外类产品,排在首位的是一款伞套,但其中没有一个本身是伞:平均使 patio 的权重超过了 umbrella。
平均法很粗糙:它忽略词序,所以 bar stool 和 stool bar 得到相同的向量,而且它会让高频词元淹没真正重要的那个词元。但它展示了本书后续每个模型所依据的性质:读取嵌入而不是独热词元的模型,可以把学到的关于一个短语的知识迁移到另一个短语上。
工作准则: 需要对短文本做快速、不考虑顺序的表示时,可以对词元嵌入取平均,但要预期它能找到相关条目,排序却比较松散。要做真正的语义检索,应使用专门训练的模型,如《入门》中所做的那样。对于语言建模,应把嵌入本身交给模型,让它自己学习如何组合,第 5 章开始这样做。
生产中会出什么问题
嵌入会把训练文本的习惯带入所有使用它们的系统:
- 用法相近不等于含义相近。
indoor与outdoor的向量彼此靠得很近。如果系统把相近的向量当作可以互换的,就会毫无察觉地把意思相反的词互相替换。请检查产品所依赖的那些词的最近邻。 - 罕见词和新词的向量质量很差,或者根本没有向量。 本章保留了 2,000 个词元。不在这份列表中的词元没有向量,只出现过寥寥几次的词元,其向量则带有噪声。该商店的分词器所含词元数量是这个数的两倍多,一个罕见词被分词器拆成若干片段后,只有其中属于这 2,000 个词元的片段才有向量。像后续各章那样自行学习嵌入的模型,则可以覆盖整个词表。
- 向量反映的是它们所来自的文本。 该商店的文本把
light描述为一盏灯,因此它的向量与照明类词语靠在一起。在某一领域训练出的嵌入,会把该领域的词义和偏见带到另一个领域。 - 交付向量,而不只是交付配方。 用梯度下降训练嵌入,在不同的处理器上得到的向量会略有差异,这正是本书要把它们记录下来的原因。请保存你所交付的向量,以及生成它们的代码和设置。
- 嵌入会过时。 目录中会出现新的产品线和新词。当词汇发生漂移时,应重新训练或扩充嵌入,并在每次重新训练之后,检查那些重要词元的近邻列表。
本章的决定
- 词元之间用其向量的余弦相似度来比较。 余弦相似度忽略长度,只比较方向,
lib.vectors.nearest返回的正是这个值。每个向量都先缩放为单位长度,因此余弦就是一个普通的点积,原始向量更长的高频词元也不会因为长度而占优。 - 计数式嵌入由经过 SVD 压缩的正 PMI 得到, 在
lib.vectors中使用两个词元的窗口和出现频率最高的 2,000 个词元。在商店的文本上,它们把patio放到了outdoor的旁边,而独热向量做不到这一点。 - 学习式嵌入由带负采样的 skip-gram 得到, 在
recordings/skipgram.py中用本书自己的代码和固定的随机种子训练一次,因为它们的确切数值取决于机器。它们与计数式嵌入在大多数词元上是一致的。 - 相似的向量意味着相似的用法。 像
indoor和outdoor这样的反义词会得到相近的向量,而类比只对文本中经常表达的关系才成立,所以本书根据嵌入对任务的帮助程度来评判它们,而不是根据类比。 - 之后的每个模型都会学习自己的嵌入, 作为预测下一个词元的一部分,从 第 5 章的神经语言模型开始。本章的向量表明,嵌入能把知识从一种语境带到另一种语境,本书其余的模型则会利用这一点。
本章,在本版次中
版次 2026.11.16示例于 2026年11月19日 通过本章 8个示例 个示例中有 8 个通过
译自英文版图书,版次 2026.11.16。