# 2.6 Word2Vec

选择context和target的方法中，比较流行的是采用**Skip-Gram**模型

Skip-Gram模型的做法是：首先随机选择一个单词作为context，例如“orange”；然后使用一个宽度为5或10（自定义）的滑动窗，在context附近选择一个单词作为target，可以是“juice”、“glass”、“my”等等。最终得到了多个context—target对作为监督式学习样本：

[![](https://github.com/fengdu78/deeplearning_ai_books/raw/master/images/0800c19895cbf1a360379b5dc5493902.png)](https://github.com/fengdu78/deeplearning_ai_books/blob/master/images/0800c19895cbf1a360379b5dc5493902.png)

训练的过程是构建自然语言模型，经过softmax单元的输出为：

$$
\hat y=\frac{e^{\theta\_t^T\cdot e\_c}}{\sum\_{j=1}^{10000}e^{\theta\_j^T\cdot e\_c}}
$$

$$\theta\_t$$为target对应的参数，$$e\_c$$为context的embedding vector，且$$e\_c=E\cdot O\_c$$

[![](https://github.com/fengdu78/deeplearning_ai_books/raw/master/images/4ebf216a59d46efa2136f72b51fd49bd.png)](https://legacy.gitbook.com/book/baozou/neural-networks-and-deep-learning/edit#)

相应的loss function为：

$$
L(\hat y,y)=-\sum\_{i=1}^{10000}y\_ilog\ \hat y\_i
$$

> 由于 $$y$$ 是一个one-hot向量，所以上式实际上10000个项里面只有一项是非0的

然后，运用梯度下降算法，迭代优化，最终得到embedding matrix $$E$$

然而，这种算法计算量大，影响运算速度。主要因为softmax输出单元为10000个，$$\hat y$$计算公式中包含了大量的求和运算

解决的办法之一是使用**hierarchical softmax classifier**，即**树形分类器**：

[\
![](https://github.com/fengdu78/deeplearning_ai_books/raw/master/images/89743b5ade106cad1318b8f3f4547a7f.png)](https://legacy.gitbook.com/book/baozou/neural-networks-and-deep-learning/edit#)

这种树形分类器是一种二分类。它在每个数节点上对目标单词进行区间判断，最终定位到目标单词。最多需要$$\log\_2 N$$步就能找到目标单词，N为单词总数

实际应用中，对树形分类器做了一些改进。改进后的树形分类器是非对称的，通常选择把比较常用的单词放在树的顶层，而把不常用的单词放在树的底层。这样更能提高搜索速度

关于context的采样：如果使用均匀采样，那么一些常用的介词、冠词，例如the, of, a, and, to等出现的概率更大一些。但是这些单词的embedding vectors通常不是最关心的，更关心的例如orange, apple， juice等这些名词。所以实际应用中一般不选择随机均匀采样的方式来选择context，而是使用其它算法来处理这类问题


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://baozoulin.gitbook.io/neural-networks-and-deep-learning/di-wu-men-ke-xu-lie-mo-xing-sequence-models/di-wu-men-kexulie-mo-578b28-sequence-models/natural-language-processing-and-word-embeddings/26-word2vec.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
