cs224n assignment2: Word2vec实现
本文是对cs224n_assignment 2实验中理论部分的总结。
原版lab 手册和code参见:
Stanford CS 224N | Natural Language Processing with Deep Learning
笔者完成了实验,code参见:
word2vec_lab
skip-gram思想:
用center word预测outside word。
定义参数:
定义两张表 U U U和 V V V,同时也是该网络唯一的参数。
处理center word时,查询 V V V,处理outside word,查询 U U U。
查询结果( u i , v j u_i,v_j ui,vj )分别作为outside word和center word的词向量。
优化目标:
center word c预测到outside word为o的概率为:
P ( O = o ∣ C = c ) = e x p ( u o T v c ) ∑ w ∈ v o c a b e x p ( u w T v c ) P(O=o|C=c)=\frac{exp(u_o^Tv_c)}{\sum_{w\in vocab}exp(u_w^Tv_c)} P(O=o∣C=c)=∑w∈vocabexp(uwTvc)exp(uoTvc)
对应代码实现为:
import numpy as np
def softmax(x):
"""Compute the softmax function for each row of the input x.
It is crucial that this function is optimized for speed because
it will be used frequently in later code
Arguments:
x -- A D dimensional vector or N x D dimensional numpy matrix.
Return:
x -- You are allowed to modify x in-place
"""
orig_shape = x.shape
if len(x.shape) > 1:
# Matrix
tmp = np.max(x, axis=1)
x -= tmp.reshape((x.shape[0], 1))
x = np.exp(x)
tmp = np.sum(x, axis=1)
x /= tmp.reshape((x.shape[0], 1))
else:
# Vector
tmp = np.max(x)
x -= tmp
x = np.exp(x)
tmp = np.sum(x)
x /= tmp
assert x.shape == orig_shape
return x`
outsideWordVecs=np.random.rand(100,10) #U
centerWordVecs=np.random.rand(100,10) #V
centerWordIndex=1
centerWordVector=centerWordVecs[centerWordIndex]
softmax(np.dot(outsideWordVecs,centerWordVector)).shape
#(100,)
P P P表征预测词的概率分布,既然是分类问题,则使用交叉熵损失函数。记 o o o即为当前预测的target,则损失函数
L = − l o g ( P ( O = o ∣ C = c ) ) \mathcal{L}=-log(P(O=o|C=c)) L=−log(P(O=o∣C=c))
网络的目标在于找到:
a r g U , V m i n L arg _{U,V}min\ \mathcal{L} argU,Vmin L
下面讨论分析优化的过程,指出这个办法的性能瓶颈,并介绍改进的负采样技术
使用SGD的办法优化网络,梯度为:
∇ L = ( ∂ V L , ∂ U L ) \nabla\mathcal{L}=(\frac\partial{V}{\mathcal{L}},\frac\partial{U}{\mathcal{L}}) ∇L=(V∂L,U∂L)
对于前一项,只需对 v 0 v_0 v0求导,其余地方梯度为0,不难证明: