Word2vec:通过预测邻词学习向量
Word2vec
推导CBOW和skip-gram梯度,区分softmax与负采样,检查可重现的小型训练目标。
word2vec通过询问附近的词,学习坐标
在一份虚构语料里,blue bird flies 与 red bird flies 共享两个词和一种模式,blue fish swims 与 red fish swims 则共享另一种。独热表示给每个不同词分配一条垂直坐标轴,于是 bird 与 fish 的距离关系,和它与任意其他不同词都一样。能否用一个训练任务,让这些坐标拥有更有用的结构?
Word2vec通过预测附近的词来学习查找表向量。skip-gram从中心词预测周围词;连续词袋CBOW则平均周围词的输入向量,预测中心词。向量在这里的用途是帮助完成指定预测任务,训练没有提供字典释义或同义词标签。架构论文:§3.1—3.2
不同出现共享参数,每次 bird 都使用同一输入行,因此更新会汇集不同上下文的证据。这也规定了一项局限:基本模型为一个词类型提供一个输入向量,不会随每次词义或句子生成不同向量。上下文词表示解决的是另一种表示问题。
这并不能证明上下文相似就是同义。反义词也能适合相同框架:虚构短语 water is hot 和 water is cold 的局部邻词并未揭示两者的对立。应把相似性当作待评测行为,而不是意义的定义。
先选事件,再选目标
两套参数表与固定窗口
设词表大小为V、嵌入维度为D,输入表U和输出表W都各有V行、D列。即使c和o指同一个词,u_c与w_o的角色也不同。skip-gram的中心词为c时,隐藏向量h=u_c,候选输出o的logit为w_oᵀh。完整softmax给出输出词上的归一化分布:
这对应第二篇Word2vec论文中的基本softmax形式。分母遍历V个词,使一个训练事件的代价依赖词表大小。Skip-gram论文:式2
半径为1时,blue bird flies 产生有向词对 (blue,bird)、(bird,blue)、(bird,flies)、(flies,bird),句界会截断窗口。完整演示使用开头四句话,再重复三遍 blue bird flies:共21个词元、六个词表词项、28个skip-gram事件,不增加BOS或EOS目标。
实现最小化M个构造事件上的平均损失:
论文写的是对中心位置平均、内部再对上下文求和。若事件集合固定,论文的值是这里事件均值的M/T倍,T是中心词元数。整体乘正常数不改变最小点,但会改变梯度大小和有效步长。复现一次更新或损失值时,应记录归一化方式。
CBOW平均的是出现,包括重复项
上下文出现为c_1,…,c_m时,CBOW使用:
预测目标是中心词。边界附近可用上下文更少,分母取实际出现数。单词句没有非空上下文,不贡献CBOW事件。本文七个三词句产生21个CBOW事件。架构论文描述的是共享投影取平均,上下文内部词序因此丢失。架构论文:§3.1
对一个目标o,令δ_j=p(j|h)−1[j=o],对负对数softmax求导得到:
最后一步按词表行累加。上下文索引为[0,0,1]时,第0行收到2g/3,第1行收到g/3。对上下文去重会改变均值;使用赋值代替累加则会丢掉一次出现的梯度。程序使用索引累加,并通过有限差分核对。
负采样改变了学习问题
带负采样的skip-gram,即SGNS,对观测输出和每个噪声输出分别提出一个二元判别问题。定义σ(s)=1/(1+exp(−s))、softplus(s)=log(1+exp(s))。正词对为(c,o),明确提供K个噪声抽样n_k时:
等价地,对正logit最大化log σ,对每个噪声logit的相反数最大化log σ。论文定义对噪声抽样求期望,有限抽样列表是该目标的随机估计。负采样目标与NCE、归一化softmax似然都不同。Skip-gram论文:§2.2,式4
对每个被评分的出现,其二元目标y∈1,二元交叉熵的导数为:
相同噪声索引出现多次,就贡献多次梯度。噪声词可能在语料其他位置确实作为上下文出现;“负”表示这次采样的训练角色,不是经过核实的“该词对永不出现”。
论文让噪声分布与unigram频率的分数次幂成比例。训练计数C(j)为正时:
因此计数[1,16]产生概率[1/9,8/9];原始频率是[1/17,16/17],均匀噪声则为[1/2,1/2]。这个指数是作者报告的选择,不是最优采样的普遍定理。固定作者代码以0.75次方构造有限采样表。论文:§2.2 固定C代码:第43—67行
本文默认有放回抽样,允许抽到正目标。可选排除政策会去掉正目标,再归一化噪声分布,因此改变目标。固定C循环则遇到与正目标相同的抽样时跳过该次应用,有效负样本数可能小于请求次数,不能暗中把这些政策当作同一种采样器。固定C代码:第465—483行
SGNS的sigmoid值在词表上不必和为1,三个零logit的二元分数之和就是1.5。它们不能直接用来算语言模型困惑度。事后加一道归一化会定义新的评分模型,并不能把已经训练的二元目标变成softmax似然。
层次softmax是另一种归一化方法
二叉树为每个词表词项分配一个叶子,为每个内部决策节点分配一个向量。沿根到目标词的路径,相乘所选分支的概率。若左分支概率为σ(a_rᵀh),右分支为1−σ(a_rᵀh),令左分支ε_r=+1、右分支ε_r=−1:
叶子概率和为1,因为每个内部节点都把流入概率分给两个子节点。给一个目标评分需O(D L_o)工作,L_o为路径长度,无需计算V个叶子logit。论文使用Huffman树,让高频词拥有较短路径。Skip-gram论文:§2.1,式3
深度取决于树。三个等频词若码长为1、2、2,平均长度为5/3,略大于log₂3。“平均代价呈对数级”不等于每条路径或每个有限规模平均值都不超过log₂V。二叉树最深路径可能有V−1条边,Huffman权重和被评分目标的分布都重要。本文解释树方法,但下面的可执行实验实现完整softmax和SGNS。
稳定算术让大logit仍然可用
直接计算exp(2000)会超出普通浮点范围。减去最大logit保持softmax概率不变,并给出稳定的对数配分量:
程序用 np.logaddexp 计算softplus,对正负参数分别计算sigmoid。显示出来的softmax概率很小时可能舍入为零,但通过平移后的对数计算,负对数似然仍可有限。如果点积或梯度本身超出支持的浮点范围,程序会报错。
运行三个目标,不给不同分数硬排高低
将代码保存为 word2vec.py。它需要NumPy,已检查环境为Python 3.12.4、NumPy 1.26.4,执行 python3 word2vec.py。输入是已经分词的句子列表,保留大小写和Unicode形式。输出包括词表、计数向量、完整训练事件、固定噪声抽样、两套参数表和损失轨迹。
"""Original small Word2vec objective lab; NumPy 1.26.4.
Full-softmax CBOW/skip-gram and explicitly fixed SGNS draws. Deterministic batch
steps are teaching choices, not the threaded author C implementation. No claim
of semantic quality, calibrated SGNS probabilities or hierarchical softmax.
"""
from collections import Counter
import json,math
import numpy as np
def integer(x,minimum=1):
if type(x) is not int or x<minimum:raise ValueError('Integer outside supported range')
return x
def vocabulary(sentences):
if not isinstance(sentences,(list,tuple)) or not sentences:raise ValueError('Supply tokenized sentences')
rows=[]
for row in sentences:
if not isinstance(row,(list,tuple)) or any(not isinstance(w,str) or not w or any(0xD800<=ord(c)<=0xDFFF for c in w) for w in row):raise ValueError('Nonempty Unicode tokens without surrogates required')
rows.append(list(row))
counts=Counter(w for row in rows for w in row);words=tuple(sorted(counts))
if not words:raise ValueError('No training words')
return {'words':words,'index':{w:i for i,w in enumerate(words)},'counts':np.array([counts[w] for w in words],dtype=float),'sentences':rows}
def examples(vocab,window=1,kind='skipgram'):
integer(window)
if kind not in ('skipgram','cbow'):raise ValueError('Choose skipgram or cbow')
result=[]
for row in vocab['sentences']:
ids=[vocab['index'][w] for w in row]
for i,center in enumerate(ids):
context=[ids[j] for j in range(max(0,i-window),min(len(ids),i+window+1)) if j!=i]
if kind=='cbow' and context:result.append({'input':context,'target':center})
if kind=='skipgram':result.extend({'input':[center],'target':target} for target in context)
return result
def initialize(size,dim=3,seed=7):
integer(size);integer(dim);integer(seed,0);rng=np.random.default_rng(seed)
return {k:rng.uniform(-.1,.1,(size,dim)) for k in ('input','output')}
def matrices(model):
if not isinstance(model,dict) or set(model)!= {'input','output'}:raise ValueError('Input and output matrices required')
a,b=(np.asarray(model[k],dtype=float) for k in ('input','output'))
if a.ndim!=2 or not all(a.shape) or b.shape!=a.shape or not np.isfinite(a).all() or not np.isfinite(b).all():raise ValueError('Finite matching vocabulary-by-dimension matrices required')
return a,b
def ids(values,size,empty=False):
if not isinstance(values,(list,tuple)) or (not values and not empty) or any(type(i) is not int or not 0<=i<size for i in values):raise ValueError('Valid vocabulary index list required')
return list(values)
def sigmoid(values):
x=np.asarray(values,dtype=float);out=np.empty_like(x);positive=x>=0
out[positive]=1/(1+np.exp(-x[positive]));e=np.exp(x[~positive]);out[~positive]=e/(1+e)
return out
def loss_gradient(model,inputs,target,negative=None):
a,b=matrices(model);inputs=ids(inputs,len(a));ids([target],len(a))
with np.errstate(over='raise',invalid='raise',divide='raise'):
try:
h=a[inputs].mean(axis=0);da=np.zeros_like(a);db=np.zeros_like(b)
if negative is None:
scores=b@h;shifted=scores-scores.max();weights=np.exp(shifted);prob=weights/weights.sum()
loss=float(np.log(weights.sum())-shifted[target]);delta=prob.copy();delta[target]-=1
db=delta[:,None]*h;dh=delta@b
diagnostics={'kind':'softmax','probabilities':prob.tolist(),'probability_sum':float(prob.sum())}
else:
targets=[target]+ids(negative,len(a),empty=True);scores=b[targets]@h
signs=np.ones(len(targets));signs[0]=-1
loss=float(np.logaddexp(0,signs*scores).sum());delta=sigmoid(scores);delta[0]-=1
np.add.at(db,targets,delta[:,None]*h);dh=delta@b[targets]
diagnostics={'kind':'sgns','draws':targets[1:],'logits':scores.tolist(),'binary_scores':sigmoid(scores).tolist()}
np.add.at(da,inputs,dh/len(inputs))
except FloatingPointError as error:raise ValueError('Objective arithmetic overflow') from error
if not math.isfinite(loss) or not np.isfinite(da).all() or not np.isfinite(db).all():raise ValueError('Nonfinite objective or gradient')
return loss,{'input':da,'output':db},diagnostics
def noise_distribution(counts,power=.75,exclude=None):
c=np.asarray(counts,dtype=float)
if c.ndim!=1 or not len(c) or not np.isfinite(c).all() or np.any(c<=0):raise ValueError('Positive finite training counts required')
if isinstance(power,bool) or not isinstance(power,(int,float)) or not math.isfinite(power) or not 0<=power<=1:raise ValueError('Noise power must lie in [0,1]')
logweights=power*np.log(c);weights=np.exp(logweights-logweights.max())
if exclude is not None:ids([exclude],len(c));weights[exclude]=0
if not weights.sum():raise ValueError('No supported negative target remains')
return weights/weights.sum()
def fixed_negatives(rows,counts,k=2,seed=11,exclude_positive=False):
integer(k,0);integer(seed,0)
if type(exclude_positive) is not bool:raise ValueError('Boolean exclusion policy required')
rng=np.random.default_rng(seed);result=[]
for row in rows:
distribution=noise_distribution(counts,exclude=row['target'] if exclude_positive and k else None)
result.append({**row,'negative':rng.choice(len(distribution),size=k,replace=True,p=distribution).tolist()})
return result
def batch(model,rows):
a,b=matrices(model)
if not isinstance(rows,(list,tuple)) or not rows:raise ValueError('Nonempty event list required')
gradient={'input':np.zeros_like(a),'output':np.zeros_like(b)};loss=0.
for row in rows:
value,g,_=loss_gradient(model,row['input'],row['target'],row.get('negative'))
loss+=value
for key in gradient:gradient[key]+=g[key]
for key in gradient:gradient[key]/=len(rows)
return loss/len(rows),gradient
def train(initial,rows,steps=60,rate=1.):
integer(steps,0)
if isinstance(rate,bool) or not isinstance(rate,(int,float)) or not math.isfinite(rate) or rate<=0:raise ValueError('Positive finite initial step required')
matrices(initial);model={k:np.array(v,dtype=float,copy=True) for k,v in initial.items()};value,grad=batch(model,rows);trace=[value]
for _ in range(steps):
norm=sum(float(np.sum(g*g)) for g in grad.values())
if norm<1e-24:break
step=rate
for attempt in range(40):
candidate={k:model[k]-step*grad[k] for k in model}
try:new,ng=batch(candidate,rows)
except ValueError:new=math.inf
if new<=value-1e-4*step*norm:break
step*=.5
else:raise ValueError('No decreasing step found')
model,value,grad=candidate,new,ng;trace.append(value)
return model,trace
def demo():
text=[['blue','bird','flies'],['red','bird','flies'],['blue','fish','swims'],['red','fish','swims']]+[['blue','bird','flies']]*3
vocab=vocabulary(text);sg=examples(vocab);cbow=examples(vocab,kind='cbow');fixed=fixed_negatives(sg,vocab['counts'])
initial=initialize(len(vocab['words']));runs={}
for name,rows in [('skipgram_softmax',sg),('cbow_softmax',cbow),('sgns_fixed_draws',fixed)]:
model,trace=train(initial,rows)
runs[name]={'events':len(rows),'loss_trace':trace,'input_vectors':model['input'].tolist(),'output_vectors':model['output'].tolist()}
hand={'input':np.array([[1.,0.],[0.,1.],[1.,1.]]),'output':np.zeros((3,2))}
soft,softgrad,sd=loss_gradient(hand,[0,1],2);neg,ng,nd=loss_gradient(hand,[0],1,[2,2])
return {'training':text,'vocabulary':list(vocab['words']),'counts':vocab['counts'].tolist(),'skipgram_events':sg,'cbow_events':cbow,
'noise_distribution_power075':noise_distribution(vocab['counts']).tolist(),'fixed_negative_events':fixed,'runs':runs,
'hand':{'softmax_loss':soft,'softmax':sd,'softmax_output_gradient':softgrad['output'].tolist(),'sgns_loss':neg,'sgns':nd,'sgns_output_gradient':ng['output'].tolist()},
'scope':'Original small fixed-window corpus. Batch mean per event; fixed replacement noise draws may include the positive target. Exact chain-rule mean-CBOW gradients; no threaded C, random windows, subsampling, hierarchical softmax or semantic-quality reproduction.'}
if __name__=='__main__':print(json.dumps(demo(),ensure_ascii=False,indent=2,allow_nan=False))
七句实验让各目标从同一组固定种子参数表出发。经过60次接受的批量更新,skip-gram softmax平均损失约从1.792461变为0.680052;CBOW softmax从1.791993变为0.775125;固定抽样SGNS从2.079576变为1.525548。这是三种不同目标,事件和输出含义不同,不能直接按原始数值给词向量质量排序。
优化器同时固定正事件和噪声抽样,计算完整批量梯度,再把候选步长不断减半,直到满足足够下降条件。显示轨迹因此针对同一个函数。每次重抽噪声会改变这次抽样所对应的函数,使直接前后比较更嘈杂。大规模Word2vec通常使用随机更新,这个小型确定性过程是教学选择,不是作者训练速度的复现。
固定C实现除采样外还有其他差异:CBOW前向平均输入向量,但输入行更新直接加上累计误差信号,没有再除上下文数。本文实现有意对声明的均值求精确导数,不能用这里的梯度检查证明C优化器使用相同更新约定。固定C代码:第432—496行
可以手算一次:输入表三行为[1,0]、[0,1]、[1,1],输出表全零。上下文[0,1]得到h=[0.5,0.5],三个softmax输出概率均为1/3,目标2损失为ln3。输出梯度依次为[1/6,1/6]、[1/6,1/6]、[−1/3,−1/3]。此刻输入梯度为零,因为所有输出行都是零;之后输出更新可使其变为非零。
这个便于检查的实现究竟花多少计算
设词元总数为T、句子数为S。把有限长度词元操作视为单位操作时,词表计数需平均O(T+S)哈希工作,排序V种词项需O(V log V)。固定半径R构造O(TR)个skip-gram事件,保存完整CBOW上下文也需O(TR)个索引条目。字符串哈希和比较另有依赖词元长度的成本。
数学上的稠密softmax事件需O(VD+mD)工作,m是输入出现数。SGNS评分和稀疏梯度贡献只需O((K+m)D),但本文每次调用都分配并检查完整V×D梯度/参数数组,因此实际单事件工作仍包含O(VD),稠密梯度存储也为O(VD)。它没有演示生产SGNS的稀疏更新速度优势。fixed_negatives还为每个事件重建噪声分布,计算这些噪声权重在这里另需O(MV)工作,还要抽取并保存MK个样本。
每个批量步骤扫描整份事件列表;回溯每拒绝一个候选,又多做一次完整目标求值。代码最多尝试40个候选。报告优化器耗时时,应同时写明事件数、梯度表示和求值次数,不能把短短一条数学损失公式当作全部运行代价。
附近的词提供监督,不提供意义认证
词表筛选、分词、动态窗口、高频词子采样、维度和导出哪套向量,都会影响表示。本实验固定词表,没有特殊UNK输入行;新拼写需要另一项处理政策才能查表。fastText共享字符子词参数,GloVe则拟合加权共现统计。
原论文还讨论效率选择与短语表示。这些不同于直接平均词向量:习语不一定适合用组成词的向量和表示。完整短语算法、实验设置和成绩主张不属于本实验已验证的实现。
应在目标任务上固定数据和预处理后评测。内在相似性、类比题和下游准确率衡量不同表现,不能无理由地互相代替。训练中的频率、多义和社会关联都可能影响邻域。小语料和下降的训练目标不能证明可靠的语义泛化,详见嵌入质量评测。
先预测更新,再追问指标
1. 理解:预测朝哪个方向?
对 blue bird flies 使用半径1,列出skip-gram事件,以及目标为 bird 的CBOW事件。构造窗口前直接拼上下一个句子,会没有影响吗?
答案:skip-gram产生blue→bird、bird→blue、bird→flies、flies→bird;中心CBOW事件用[blue,flies]预测bird。拼接句子会增加跨句界上下文对,改变训练数据;程序有意在每个句界结束窗口。
2. 手算:输出表全零
使用给定三行手算模型,求上下文[0,1]、目标2的softmax损失与输出梯度。再令输入[0]、正目标1、噪声抽样[2,2],求SGNS损失和输出第2行梯度。
答案:均值上下文为[0.5,0.5],softmax损失为ln3,输出梯度依次为[1/6,1/6]、[1/6,1/6]、[−1/3,−1/3]。SGNS的三个logit均为零,损失为3ln2;负样本第2行的每次出现贡献[0.5,0],合计[1,0]。只保留一次会计算另一个损失和梯度。
3. 反例:上下文顺序与重复索引
上下文索引为[0,0,1]、隐藏梯度为g时,每个输入行收到多少?[0,1]会给出相同隐藏向量吗?为什么排序和去重不是同一种操作?
答案:第0行收到2g/3,第1行收到g/3,隐藏向量是(2u_0+u_1)/3,一般不同于(u_0+u_1)/2。重新排列相同出现不改变均值,删除重复项却会改变次数、均值和梯度。应按索引累加,不能覆盖共享行。
4. 迁移:更低的训练数字
一项SGNS运行的最终损失低于另一项,但两者使用不同噪声分布和负样本数。这能证明语义向量更好吗?能否直接用sigmoid分数计算语言困惑度?
答案:两者都不能。改变噪声分布或抽样数,会改变判别任务及损失尺度;应在同一个相关评测设置下比较表示。独立sigmoid分数在输出词表上不必和为1,其对数不是归一化语言模型似然。目标、采样政策和评测主张要分别记录。
区分架构、目标与实现版本
架构论文首次提交于2013年1月,所链v3是同年9月修订;另一篇2013年10月论文展开负采样等扩展。只引用第一篇,不应让读者以为后来的全部训练细节都包含在最初版本里。架构论文 Skip-gram扩展
核读的作者代码快照为2017年7月16日的提交 20c129a,根许可证为Apache-2.0。本文原创Python讲解和实现没有复制或执行该C程序。来源检查覆盖CBOW/skip-gram定义、softmax与负采样公式、所示树路径、噪声表代码和选定CBOW更新块,不认证整仓库、所有基准或人工同行审校。本文训练句子、梯度、实验及习题均为原创。
先判断,再看解释
CBOW平均三个上下文出现,索引为[0,0,1]。若隐藏向量梯度为g,输入表第0行收到什么?
学习目标
- 构造不跨句界的CBOW与skip-gram事件。
- 推导平均上下文及重复负样本索引的梯度。
- 区分完整softmax、树概率和SGNS二元目标。
- 准确记录采样、归一化和评测选择。
先修与延伸
查看知识关联图 →参考文献
- Efficient Estimation of Word Representations in Vector Space, v3
Tomas Mikolov; Kai Chen; Greg Corrado; Jeffrey Dean · 2013 - Distributed Representations of Words and Phrases and their Compositionality, v1
Tomas Mikolov; Ilya Sutskever; Kai Chen; Greg Corrado; Jeffrey Dean · 2013 - Author Word2vec C implementation, pinned snapshot
Tomas Mikolov and word2vec contributors · 2017
版本1 · 编写状态: 已完成记录中的技术复核
查看技术检查记录(AI)
Codex · 2026-09-08 · Codex single-AI-author technical check: scoped architecture and negative-sampling papers plus pinned author C; nine paired equations, event versus center normalization, strict mean-CBOW gradients, full softmax versus binary SGNS and noise policies, normalized hierarchical paths with a three-leaf depth counterexample, stable arithmetic, actual dense complexity and four explained exercises. Original fixed-window toy data and deterministic batch objectives; not semantic quality, C reproduction or human peer review.
- 双语九组显示公式、四解释习题与三项限定来源对应。核28个skip-gram与21个CBOW事件、M/T归一化、重复输入/噪声累加、三等概率Huffman叶与平均深度5/3大于log2(3)。保留正样本命中、排除重抽与固定C跳过政策的区别。
- 正式测试执行实际MDX:20项原型梯度/边界、3项正文数学与6项出版检查。核中心差分、零输出手算梯度、固定噪声损失端点和幂次分布。保留稠密分配/校验成本,训练曲线不排名语义质量。
- 四张原创SVG绑定实际MDX结果,八项图检查核数据、算术、条形及双语引用。隔离18种语言/宽度组合、四种备用字体验证通过,保留隔离检查页开发工具栏遮挡及XML入口失败记录;实际查看桌面/手机截图。完整文章浏览器验收另记,无人工同行审校或上游代码执行。
核对的来源位置:
- Efficient Estimation of Word Representations in Vector Space, v3 · Scoped sections3.1–3.2, cached text190–233: averaged shared CBOW projection and skip-gram context prediction. v1 January16, v3 September7. No adopted benchmark claims.
- Distributed Representations of Words and Phrases and their Compositionality, v1 · Scoped§2–2.3 opening: dual tables, full/hierarchical softmax, negative sampling and noise power; PDF page3 inspected for equations2–4. Phrase algorithm and experimental tables not fully reviewed.
- Author Word2vec C implementation, pinned snapshot · Lines43–67 and432–496: noise table, CBOW average, sampling and input update. Apache-2.0 root license identified; no C execution, whole-repository audit or copied implementation.
相关主题