word2vec理论和实现及负采样技术

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=oC=c)=wvocabexp(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=oC=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=(VL,UL)
对于前一项,只需对 v 0 v_0 v0求导,其余地方梯度为0,不难证明:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值