Calculate gradients for Word2Vec

Now that we have learned how to calculate gradients w.r.t. vectors in the last blog post, let’s see whether we can apply this technique to another model, the famous Word2vec.

Basically what Word2vec is trying to do is to predict every word around each word. It does this by calculating the probability of every possible choice in the vocabulary to be the context word for each center word.

Concretely, if uou_o is the vector representing the context word, and vcv_c is the vector representing the center word, then the probability of uou_o being the correct context word is: y^o=p(o∣c)=euoTvc∑w=1VeuwTvc\hat{y}_o = p(o|c) = \frac{e^{u_o^T v_c}}{\sum_{w=1}^V e^{u_w^Tv_c}}. Now we want this to be as high as possible, which means the cost function is defined as below:

J=CE(y,y^)=−∑i=1Vyilog⁡y^iJ = CE(y, \hat{y}) = -\sum_{i=1}^{V} y_i \log \hat{y}_i

Let’s define θo=uoTvc\theta_o = u_o^T v_c. Then we already know that ∂J∂θ=y^−y\frac{\partial J}{\partial \theta} = \hat{y} - y.

Now we go back.

∂J∂vci=∑w=1V∂J∂θw∂θw∂vci=∑w=1V(y^w−yw)uwiT=Ui(y^−y)\begin{aligned} \frac{\partial J}{\partial v_{ci}} &= \sum_{w=1}^V \frac{\partial J}{\partial \theta_w} \frac{\partial \theta_w}{\partial v_{ci}} \\ &= \sum_{w=1}^V \left( \hat{y}_w - y_w \right) u_{wi}^T \\ &= U_i(\hat{y} - y) \\ \end{aligned} ∂J∂vc=U(y^−y)\frac{\partial J}{\partial v_c} = U(\hat{y} - y) ∂J∂uki=∑w=1V∂J∂θw∂θw∂uki=(y^k−yk)∂θk∂uki=(y^k−yk)vci\begin{aligned} \frac{\partial J}{\partial u_{ki}} &= \sum_{w=1}^V \frac{\partial J}{\partial \theta_w} \frac{\partial \theta_w}{\partial u_{ki}} \\ &= \left( \hat{y}_k - y_k \right) \frac{\partial \theta_k}{\partial u_{ki}} \\ &= \left( \hat{y}_k - y_k \right) v_{ci} \\ \end{aligned} ∂J∂uk=(y^k−yk)vc\frac{\partial J}{\partial u_k} = (\hat{y}_k - y_k)v_c ∂J∂U=vc(y^−y)T\frac{\partial J}{\partial U} = v_c (\hat{y} - y)^T