Search

Search papers and lessons

Efficient Estimation of Word Representations in Vector Space (word2vec)

Tomas Mikolov, Kai Chen, Greg Corrado et al. · 2013

Two deliberately simple models, CBOW and skip-gram, learn word vectors from billions of words in days on modest hardware, and the vectors answer word analogy questions by plain vector arithmetic.

On this page

  • Colour = topic mix
  • Calculus
  • Neural network basics
  • Linear algebra
  • Discrete math
  • Probability
  • Losses & regularization
  • Sign in to see your progress

TL;DR

Before 2013, the best word vectors came from neural network language models. Those models were slow: the recurrent one took about eight weeks on a single CPU for 320 million words, so nobody could feed them billions of words. Mikolov and colleagues removed the expensive hidden layer and kept only the part that learns word vectors. The two resulting models, CBOW and skip-gram, train on corpora of billions of words (the abstract claims under a day for 1.6 billion words; the single-CPU runs in Section 4 took about one day for CBOW and three for skip-gram), and their vectors answer analogy questions with plain arithmetic: vector("biggest") minus vector("big") plus vector("small") lands near vector("smallest").

Where you'll see it: in the word2vec tool and the pretrained vector sets built with it, in early NLP systems that initialised their input layer with these vectors, and in the idea of a lookup table of learned vectors at the input of later neural language models.

The problem

Most language systems in 2013 treated a word as an index into a vocabulary. Index 4817 has no relation to index 4818, so the system cannot tell that "small" and "smaller" are related. Simple count-based models get around this by scale: an N-gram Language Model predicts the next word from counts of short word sequences, and such counts can be gathered from trillions of words. The catch is that n-gram models do not generalise. Seeing "the cat sat" tells them nothing about "the dog sat" unless they saw that exact phrase.

Neural language models do generalise. They map each word to a dense vector, and words used in similar ways get similar vectors. The trouble is cost. The feedforward model of Bengio and colleagues (which the authors re-trained as a baseline with 640 hidden units and an 8-word history) and the recurrent model (which had taken about 8 weeks on one CPU for 320 million words) were too slow to train on the hundreds of millions of words that would have made their vectors good. Earlier word-vector work had a similar limit: the largest runs used a few hundred million words and vectors of only 50 to 100 dimensions.

The paper sets two goals. The first is to learn high-quality word vectors from data sets with billions of words and vocabularies of millions of words, with much cheaper training than before. The second is a way to measure vector quality. Instead of eyeballing the nearest neighbours of a few words, the authors build a test of word relationships that can be scored automatically.

Key idea

The key observation is that most of the cost sits in the non-linear hidden layer, not in the word vectors themselves. The authors therefore drop the hidden layer and keep a log-linear model: a dot product between a context representation and an output vector, followed by a softmax. Such a model is much cheaper, so it can be trained on far more text and produce higher-dimensional vectors within the same time budget.

Two architectures come from this idea.

  • CBOW (continuous bag of words) takes the words around a position, averages their input vectors into one vector, and predicts the middle word. The order of the context words is ignored. The best setting uses four words on each side.
  • Skip-gram does the reverse. It takes the middle word and predicts the words in a window around it. Nearby words are used more often than distant ones, because the window size is sampled randomly for each position.
flowchart TB
  S["Sentence: the cat sat on the mat"] --> C["CBOW: context words in, centre word out"]
  S --> K["Skip-gram: centre word in, context words out"]
  C --> V["Input vectors are the word embeddings"]
  K --> V

The vectors are a by-product of the prediction task. Nobody labels them. The training signal is simply that a word should predict its neighbours, and words that share neighbours end up with similar vectors.

The method

The cost model

The authors compare models by counting the work needed per training example, which they call Q. Let VV be the vocabulary size, DD the vector dimension, NN the number of context words, HH the hidden layer size, CC the maximum window distance, and TT the number of training words. Training over EE epochs costs about

O=E×T×Q.O = E \times T \times Q.

Each architecture has its own Q. For the feedforward neural language model:

QNNLM=N×D+N×D×H+H×V.Q_{\text{NNLM}} = N \times D + N \times D \times H + H \times V.

The recurrent model has no projection layer and costs QRNNLM=H×H+H×VQ_{\text{RNNLM}} = H \times H + H \times V. For CBOW and skip-gram, the authors use the Hierarchical Softmax for the output, which turns the H×VH \times V or D×VD \times V term into a logarithm of VV:

QCBOW=N×D+D×log⁡2V,Q_{\text{CBOW}} = N \times D + D \times \log_2 V, Qskip-gram=C×(D+D×log⁡2V).Q_{\text{skip-gram}} = C \times \left(D + D \times \log_2 V\right).

The feedforward model has its largest term in N×D×HN \times D \times H, and the hidden layer is what the new models remove.

The output layer: softmax and hierarchical softmax

Let hh be the context representation (for CBOW, the average of the context input vectors) and uw\mathbf{u}_w the output vector of word ww. The usual Softmax assigns the word ww the probability

P(w∣h)=exp⁡(uw⊤h)∑w′=1Vexp⁡(uw′⊤h).P(w \mid h) = \frac{\exp(\mathbf{u}_w^\top h)}{\sum_{w'=1}^{V} \exp(\mathbf{u}_{w'}^\top h)}.

The denominator sums over every word in the vocabulary, so each training example costs about V×DV \times D operations. The hierarchical softmax removes this sum. The words are the leaves of a binary tree, and the probability of a word is the product of binary decisions along its path from the root. Each internal node nn has its own vector un\mathbf{u}_n, and the probability of a left or right turn is a sigmoid:

P(w∣h)=∏n∈path(w)σ ⁣(sn un⊤h),σ(x)=11+e−x,P(w \mid h) = \prod_{n \in \text{path}(w)} \sigma\!\left(s_n \, \mathbf{u}_n^\top h\right), \qquad \sigma(x) = \frac{1}{1 + e^{-x}},

where sns_n is +1+1 or −1-1 according to the branch taken at node nn. The paper uses a Huffman tree, built from word frequencies, so frequent words get short paths. For a tree of this kind, the average path length is close to log⁡2\log_2 of the unigram perplexity of the vocabulary, which is much smaller than log⁡2V\log_2 V when word frequencies are uneven. The authors note that for a vocabulary of one million words this gives about a two-fold speed-up.

Training

Training uses Stochastic Gradient Descent, with gradients computed by Backpropagation. The training criterion is the log probability of the correct word, the negative of which is the Cross-Entropy Loss against a one-hot target. For CBOW the objective is to maximise log⁡P(wt∣context)\log P(w_t \mid \text{context}) over the corpus. For skip-gram it is to maximise ∑log⁡P(c∣wt)\sum \log P(c \mid w_t), summed over the context words cc in the window of each centre word wtw_t.

The skip-gram window is sampled. For each centre word the authors draw a number RR uniformly from 11 to CC, then use RR words on each side as targets. Far words are therefore used less often, as the authors intended. Their experiments use C=10C = 10.

The learning rate starts at 0.025 and decreases linearly to zero by the end of the last epoch. For the large runs, the authors train 50 to 100 model replicas in parallel on the DistBelief framework, with asynchronous mini-batch updates and the Adagrad adaptive learning rate.

Evaluation: analogy questions

The test set has five kinds of semantic question (for example, capital cities and their countries) and nine kinds of syntactic question (for example, comparatives and past tenses). It contains 8,869 semantic questions and 10,675 syntactic ones. A question "a is to b as c is to ?" is answered by computing x=vb−va+vc\mathbf{x} = \mathbf{v}_b - \mathbf{v}_a + \mathbf{v}_c, then finding the vocabulary word whose vector has the highest cosine similarity to x\mathbf{x}, leaving out the three question words. The answer counts only if it is exactly the expected word, so a synonym is scored as wrong. Only single-token words are used, which removes multi-word names such as "New York".

Worked examples

Example 1: what each architecture costs per example

Take a vocabulary of one million words, so V=1,000,000V = 1{,}000{,}000 and log⁡2V≈19.93\log_2 V \approx 19.93. Compare a feedforward model with N=10N = 10, D=500D = 500, H=1000H = 1000 against CBOW with N=8N = 8, D=300D = 300.

  1. Feedforward model, full softmax. The terms are N×D=10×500=5,000N \times D = 10 \times 500 = 5{,}000, N×D×H=5,000,000N \times D \times H = 5{,}000{,}000 and H×V=1,000,000,000H \times V = 1{,}000{,}000{,}000. The total is about 1.005×1091.005 \times 10^9.
  2. Feedforward model, hierarchical softmax. Replace H×VH \times V with H×log⁡2V=1000×19.93≈19,932H \times \log_2 V = 1000 \times 19.93 \approx 19{,}932. The total becomes 5,000+5,000,000+19,932=5,024,9325{,}000 + 5{,}000{,}000 + 19{,}932 = 5{,}024{,}932. The hidden layer term now dominates, which is why the authors removed it.
  3. CBOW. The terms are N×D=8×300=2,400N \times D = 8 \times 300 = 2{,}400 and D×log⁡2V=300×19.93≈5,979D \times \log_2 V = 300 \times 19.93 \approx 5{,}979. The total is about 8,3798{,}379.
  4. Ratio. 5,024,932/8,379≈6005{,}024{,}932 / 8{,}379 \approx 600. CBOW does roughly 600 times less work per example than the feedforward model with the same output layer.

Interpretation: after removing the hidden layer, the remaining cost is a lookup of NN vectors plus one walk down a tree of depth about 20. Adding more data costs roughly linearly, which is what makes billion-word training possible.

Example 2: an analogy with toy numbers

These numbers are made up for illustration. The paper's vectors are learned, not set by hand. Use two dimensions: the first measures royalty, the second measures gender. Let vking=(1,1)\mathbf{v}_{\text{king}} = (1, 1), vman=(0,1)\mathbf{v}_{\text{man}} = (0, 1), vwoman=(0,−1)\mathbf{v}_{\text{woman}} = (0, -1), vqueen=(1,−1)\mathbf{v}_{\text{queen}} = (1, -1) and vapple=(−1,0)\mathbf{v}_{\text{apple}} = (-1, 0).

  1. Compute x=vking−vman+vwoman=(1,1)−(0,1)+(0,−1)=(1,−1)\mathbf{x} = \mathbf{v}_{\text{king}} - \mathbf{v}_{\text{man}} + \mathbf{v}_{\text{woman}} = (1, 1) - (0, 1) + (0, -1) = (1, -1).
  2. Compare x\mathbf{x} with each remaining word. Cosine with queen: 1⋅1+(−1)(−1)22=1\frac{1 \cdot 1 + (-1)(-1)}{\sqrt{2}\sqrt{2}} = 1.
  3. Cosine with apple: (1)(−1)+(−1)(0)2⋅1≈−0.71\frac{(1)(-1) + (-1)(0)}{\sqrt{2} \cdot 1} \approx -0.71.
  4. The nearest word is queen, which is the answer.

Interpretation: if the directions for royalty and gender are separate axes, then subtracting "man" and adding "woman" flips the gender axis while keeping the royalty part. The paper's claim is that real learned vectors behave this way, approximately, on many relationships.

Results

The paper's full tables (Tables 3 to 6) give per-architecture numbers for semantic, syntactic and total accuracy. The headline figures stated in the text are these.

  • Data and vocabulary. The main vectors are trained on a Google News corpus of about 6 billion tokens, restricted to the one million most frequent words. Ablations use a 30,000-word subset of the vocabulary.
  • Architecture comparison. All models use the same 320 million words and 640-dimensional vectors. The recurrent model's vectors do well mostly on syntactic questions. The feedforward model beats the recurrent one clearly. CBOW beats the feedforward model on syntactic questions and matches it on semantic ones. Skip-gram is slightly below CBOW on syntactic questions but much better than every other model on semantic ones.
  • Cost. A CBOW model trained on a subset of the Google News data took about a day on a single CPU. The skip-gram model took about three days. The abstract frames it differently (under a day for 1.6 billion words). Per-model times and accuracies are in Tables 4 and 6, which this lesson does not reproduce.
  • Scale. More dimensions and more data both help, with diminishing returns. The authors argue that doubling the data costs about the same extra work as doubling the vector size, so both should grow together. Training on twice as much data for one epoch is comparable to or better than three epochs on the smaller set.
  • Ensembles. Averaging the vectors of ten example pairs to define one relation improves accuracy of the best models by about 10 points absolute on the combined test.
  • Analogies in practice. Using the 783-million-word skip-gram model with 300 dimensions, the example "Paris minus France plus Italy" gives Rome. The authors note that under their strict exact-match scoring, the examples in their Table 8 would score only about 60 percent, so the method is good but far from perfect.
  • Sentence completion. On the Microsoft Sentence Completion Challenge, skip-gram alone does not beat LSA. Its scores are complementary to those of recurrent language models, and a weighted combination reaches 58.9 percent (59.2 on the development part, 58.7 on the test part). The previous best reported on that benchmark was 55.4 percent.

Known limits, stated by the authors: exact-match scoring punishes correct synonyms; the model has no access to word morphology, which caps syntactic accuracy; and multi-word entities are excluded from the test.

Why it mattered

The paper showed that very simple, fast models trained on very large corpora produce vectors with useful structure. The vector arithmetic on relationships became the standard picture of what a word embedding captures, and the word2vec tool made the method easy to run. The follow-up work in the paper's Section 7 describes a multi-threaded C++ implementation that trains at speeds of billions of words per hour, and a set of 1.4 million named-entity vectors trained on more than 100 billion words.

The approach of learning word vectors first and then using them as the input to another model became common practice in NLP. Later models moved from one fixed vector per word to vectors that depend on context, such as those produced by the Transformer, but the lookup table of learned vectors at the input stayed.

Reading guide

Read the paper in this order, with these prerequisites in hand.

  1. Section 1 (introduction and previous work). Language Model and N-gram Language Model explain the baseline the paper argues against. Word Embedding gives the basic idea of a learned vector per word.
  2. Section 2, the cost model. You need Matrix Multiplication for the projection, and Softmax and Hierarchical Softmax for the output layer. The tree-depth argument is the core of the section.
  3. Section 2.1, the feedforward model. Feedforward Neural Network describes the model whose cost the paper breaks down.
  4. Section 2.2, the recurrent model. Recurrent Neural Network explains the recurrent baseline.
  5. Section 2.3 (parallel training) and the training paragraphs of Section 4.2. Stochastic Gradient Descent, Backpropagation and Cross-Entropy Loss cover the training procedure and the learning rate schedule.
  6. Section 3, the new models. Vector and Dot Product are all you need to follow the CBOW and skip-gram formulas.
  7. Section 4, results. Vector Norm explains the cosine similarity used to find the nearest word, and the analogy arithmetic in Section 4 is the same vector addition shown in Example 2 above.
  8. Section 5 onward. Section 5 reuses the analogy method and Sections 6 and 7 are summary and follow-up, so they need nothing new.

Check yourself

QuestionWhat does each of the two architectures predict, and from what input?Show answer
CBOW predicts the middle word from the average of the input vectors of the words around it, ignoring their order. Skip-gram takes the middle word as input and predicts the words in a window around it. Both produce word vectors as a by-product of this prediction task.
QuestionA CBOW model has a vocabulary of 30,000 words, vectors of dimension D = 300 and N = 8 context words. Using Q = N x D + D x log2 V, how much work does one training example need? Take log2 of 30,000 as about 14.87.Show answer
The first term is 8 x 300 = 2,400. The second term is 300 x 14.87 = 4,461. The total is about 6,861 operations per example.
QuestionWhy does removing the hidden layer make training so much faster, and why does the Huffman tree help further?Show answer
The hidden layer contributes the term N x D x H, which dominated the cost of the feedforward model. Without it, the cost is a few lookups plus the output layer. The hierarchical softmax reduces the output cost from V to about the logarithm of V, because a word needs only a walk down a tree. The Huffman tree puts frequent words near the root, so the average walk is shorter than the balanced-tree depth when word frequencies are uneven.
QuestionWhy does the analogy test use exact matches, and what does that cost?Show answer
Exact matches make the score objective and easy to compute automatically. The cost is that a correct synonym counts as wrong, so the reported accuracy understates how useful the vectors are for some applications. The authors also discard the three question words from the search, so the answer cannot simply be one of the inputs.
QuestionYou have a corpus of a few million words and want word vectors quickly for a task that depends mainly on syntax, such as verb tenses. Which architecture would you try first, and why?Show answer
CBOW. It is the faster of the two, and the paper reports that CBOW does better than skip-gram on syntactic questions, with skip-gram better on semantic ones. If the task needed more semantic structure, skip-gram would be the choice to test next.

Sources

Read the full paper

Tomas Mikolov, Kai Chen, Greg Corrado et al., 2013. arXiv:1301.3781