Skip to main content

Introduction

In classical NLP, words were treated as atomic symbols, such as hotel, conference or walk, and represented with sparse one-hot vectors: hotel=[0,0,...,0,1,0,0,..,0]\mathtt{hotel} = [0,0, ..., 0,1, 0,0,..,0] motel=[0,0,...,0,0,0,1,..,0]\mathtt{motel} = [0,0, ..., 0,0, 0,1,..,0] The length of each vector equals the vocabulary size ∣V∣|V|, which runs from tens of thousands of words for a single application to millions for web-scale text. One-hot vectors are also orthogonal by construction, so nothing relates motel to hotel: their dot product is s=hotelTmotel=0 s = \mathtt{hotel}^T \mathtt{motel} = 0 One of the key ideas that made NLP successful is distributional semantics, which goes back to Firth: a word’s meaning is given by the words that frequently appear close by. When a word xx appears in a text, its context is the set of words that appear nearby, within a fixed-size window. The many contexts of xx across a corpus are used to build up a representation of xx. distributional-similarity Distributional similarity: banking is represented by the words to its left and right across all sentences of the corpus. This is the idea behind word2vec embeddings, which the rest of this section develops. Embeddings learned this way are general purpose. A model for a specific task can start from them or learn its own embedding layer from scratch, and which works better depends on the task and on how much labeled data it has.

Features of Word2Vec embeddings

In 2013, Tomas Mikolov and colleagues at Google published two papers that learn word vectors of a few hundred dimensions dd by training a shallow network to predict the words around each word (Mikolov et al., 2013; Mikolov et al., 2013). They released the code as word2vec. banking-vector A word2vec embedding for the word banking in d=8 dimensions. The Embedding Projector shows such vectors projected from dd dimensions to 3. Search for the word “truck”: the list of nearest neighbors is computed in the original dd-dimensional space, while the 3D positions come from PCA or t-SNE, so points that look close in the plot need not be neighbors. Projected to 2D, the vectors of US cities do not reproduce the geographic map, but cities that are similar in meaning fall close together, which is what an embedding is for. semantic-map-word2vec Semantic map produced by word2vec for US cities. Word2vec vectors also encode analogies. The classic example is king − man + woman ≈ queen. queen-example The queen example, where king − man ≈ queen − woman, shown by the parallel red arrows. Four analogies can be read off the arrows and their directions. The figure is idealized: the query vector only has to be closer to queen than to any other word, not equal to it. The similar direction of the arrows indicates a similar relation. Word2vec has two training algorithms[^1]. This section covers the skip-gram method, using the diagrams below. word2vec-idea word2vec-idea2 Skip-gram predicts the context given the center word, so it needs the probability p(wt+j∣wt)p(w_{t+j} | w_t). The model goes through each position tt of the corpus and, for the center word wtw_t, predicts the context words wt+jw_{t+j} for −m≤j≤m-m \le j \le m, j≠0j \neq 0. A window of mm words on each side gives C=2mC = 2m context words per center word. In this view, the meaning of banking is captured by how well it predicts the words around it across the corpus. Prediction means maximum likelihood, as in the regression section: the network is trained to make pmodelp_{model} match the empirical distribution p^data\hat p_{data} by minimizing cross-entropy. The average negative log-likelihood is J(θ)=−1T∑t=1T∑−m≤j≤m,j≠0log⁡p(wt+j∣wt;θ)J(\theta) = -\frac{1}{T} \sum_{t=1}^{T} \sum_{-m\le j \le m, j \neq 0} \log p(w_{t+j} | w_t; \theta) where TT is the number of words in the corpus, which can reach billions. The vocabulary size ∣V∣|V| is a different number: each distinct word counts once. Training pairs are generated directly from the corpus once the window mm is fixed: training-data-word2vec Training data generation for the sentence ‘Claude Monet painted the Grand Canal of Venice in 1908’. The probability p(wt+j∣wt;θ)p(w_{t+j} | w_t; \theta) comes from the network below. word2vec-network Conceptual architecture of the network that learns word2vec embeddings. The text writes dd for the figure’s hidden layer dimension NN, and z\mathbf z for its hidden layer h\mathbf h. The network maps the one-hot center word x\mathbf x through the embedding matrix W∣V∣×d\mathbf W_{|V| \times d} to the hidden vector z\mathbf z, which is simply the row of W\mathbf W for that word. The output matrix Wd×∣V∣′\mathbf W^\prime_{d \times |V|} turns z\mathbf z into one score per vocabulary word, and the softmax turns the scores into a distribution y^\hat{\mathbf y} over the vocabulary: z=xTW\mathbf z = \mathbf x^T \mathbf W z′=zW′\mathbf z^\prime = \mathbf z \mathbf W^\prime y^=softmax(z′)\hat{\mathbf y} = \mathtt{softmax}(\mathbf z^\prime) L=∑j=1CCE(yj,y^)L = \sum_{j=1}^{C} CE(\mathbf{y}_j, \hat{\mathbf y}) The figure draws CC output panels, one per context position. All of them use the same W′\mathbf W^\prime, so they hold the same distribution y^\hat{\mathbf y}. What differs between panels is the one-hot target yj\mathbf y_j, the context word at that position. Writing vw\mathbf v_w for row ww of W\mathbf W and uw\mathbf u_w for column ww of W′\mathbf W^\prime, the model is p(o∣c)=exp⁡(uoTvc)∑w=1∣V∣exp⁡(uwTvc)p(o \mid c) = \frac{\exp(\mathbf u_o^T \mathbf v_c)}{\sum_{w=1}^{|V|} \exp(\mathbf u_w^T \mathbf v_c)} so every word has an input vector, used when it is the center word, and an output vector, used when it is a context word. The parameters θ={W,W′}\theta = \{\mathbf W, \mathbf W^{\prime} \} are optimized with an algorithm from the SGD family. After training, the rows of W\mathbf W are the word embeddings, and W\mathbf W is what the parsing stage of an NLP pipeline loads. The denominator above sums over the whole vocabulary for every training pair, which is too slow for large vocabularies. In practice word2vec replaces it with negative sampling: a logistic regression in which the positive examples are (center, context) pairs from the corpus and the negative examples are (center, random word) pairs (Mikolov et al., 2013). The next section derives that loss and trains it on 15 million words. The CS224n notes cover it in more detail.
Mind the difference between learning a representation from contexts across the corpus and applying that representation. Word2vec vectors are applied without context. After training, a single matrix W\mathbf W is used, so the word ‘bank’ gets the same vector whether it appears next to ‘river’ or next to ‘deposit’.Contextual representations are covered in a separate section.

Example

Consider a training corpus of three sentences: “the dog saw a cat”, “the dog chased the cat”, “the cat climbed a tree” This corpus has ∣V∣=8|V|=8 distinct words, and the goal is embeddings of dimension d=3d=3. The parameter matrices are randomly initialized as \end\{bmatrix\}$$ $$ W^\prime = \begin{bmatrix}0.18 & 0.37 & 0.01 & 0.25 & 0.80 & 0.02 & 0.60 & 0.60\\0.11 & 0.38 & 0.04 & 0.89 & 0.98 & 0.06 & 0.89 & 0.58\\0.74 & 0.63 & 0.58 & 0.02 & 0.21 & 0.54 & 0.77 & 0.25 \end\{bmatrix\}$$ Take the training pair from "the cat climbed a tree" in which “climbed” is the center word and “cat” is the context word one position to its left. The network should assign a high probability to “cat” when “climbed” is the input. With the words sorted alphabetically (a, cat, chased, climbed, dog, saw, the, tree), “climbed” is the 4th word, so the input is $\mathbf x = [0, 0, 0, 1, 0, 0, 0, 0]^T$. “cat” is the 2nd word, so the target is $\mathbf y = [0, 1, 0, 0, 0, 0, 0, 0]^T$. The hidden layer is the 4th row of $W$: $$\mathbf z = \mathbf x^T \mathbf W = \begin{bmatrix} 0.58 & 0.89 & 0.21 \end\{bmatrix\}$$ Multiplying by $W^\prime$ gives one score per vocabulary word: $$\mathbf z^\prime = \mathbf z \mathbf W^\prime =\begin{bmatrix} 0.36 & 0.69 & 0.16 & 0.94 & 1.38 & 0.18 & 1.30 & 0.92 \end\{bmatrix\}$$ The softmax turns the scores into probabilities that sum to one: $$\hat{\mathbf y} = \mathtt{softmax}(\mathbf z^\prime) = \begin{bmatrix} 0.077 & \mathbf{0.107} & 0.064 & 0.139 & 0.215 & 0.065 & 0.199 & 0.135 \end\{bmatrix\}$$ The entry in bold is $p(\text{cat} \mid \text{climbed}) = 0.107$, and the cross-entropy loss for this pair is $-\log 0.107 = 2.23$. The untrained network gives its highest probability, 0.215, to “dog”. The gradient of the loss with respect to $\mathbf z^\prime$ is $\hat{\mathbf y} - \mathbf y$. Backpropagation uses it to update $W^\prime$ and the row of $W$ for “climbed”. Training repeats this for every (center, context) pair in the corpus. A center word with several context words contributes one cross-entropy term per context word. ## References - Mikolov, T., Chen, K., Corrado, G., Dean, J. (2013). *Efficient Estimation of Word Representations in Vector Space*. arXiv [cs.CL]. [Link](http://arxiv.org/abs/1301.3781) - Mikolov, T., Sutskever, I., Chen, K., Corrado, G., Dean, J. (2013). *Distributed Representations of Words and Phrases and their Compositionality*. Advances in Neural Information Processing Systems 26. [Link](http://papers.nips.cc/paper/5021-distributed-representations-of-words-and-phrases-and-their-compositionality.pdf) - Rong, X. (2014). *word2vec Parameter Learning Explained*. arXiv [cs.CL]. [Link](http://arxiv.org/abs/1411.2738) --- <Callout icon="bug" iconType="regular"> Found an error on this page? [Report an issue](https://github.com/aegean-ai/eaia-feedback/issues/new?template=page-issue.yml&page=/aiml-common/lectures/nlp/nlp-introduction/word2vec). </Callout>