AI
Word2vec Explained: How Word Embeddings Began
Word2vec explained: how this 2013 method turns words into vectors, skip-gram vs CBOW, negative sampling, a worked example, gensim code and its limits.
Word2vec is a method, published by researchers at Google in 2013, that learns a list of numbers (a vector) for every word in a vocabulary by reading a large amount of text. Words that are used in similar ways end up with similar vectors, so "king" lands near "queen" and "Paris" near "Rome". The vectors are called word embeddings, and word2vec was the technique that made them cheap enough to train on billions of words and good enough to change how language software was built.
This guide gives you word2vec explained step by step: what it is and why it mattered, how the two architectures, skip-gram and CBOW, work, the training tricks that made it fast, a worked example you can follow by hand, how to train a model with gensim, how word2vec compares with GloVe, fastText and BERT-style models, and where it falls short. You don't need to know any maths beyond "vectors are lists of numbers".
What Is Word2vec?
What is word2vec? It's a shallow neural network trained to predict words from their neighbours, and the useful by-product is the set of weights it learns, which become the word vectors. It was introduced by Tomas Mikolov and colleagues in two 2013 papers: "Efficient Estimation of Word Representations in Vector Space", which presented the two architectures, and "Distributed Representations of Words and Phrases and their Compositionality", which added the training improvements and phrase handling.
The first paper's headline claim was speed: high-quality word vectors could be learned in less than a day from a data set of 1.6 billion words. Earlier neural methods were far slower. Speed mattered because the quality of embeddings depends mostly on how much text you can train on.
The second striking result was that the vectors captured relationships as directions. The best-known example is that the vector for "king" minus "man" plus "woman" lands closest to "queen". The papers give others, such as Paris minus France plus Italy giving Rome, and Madrid minus Spain plus France landing closest to Paris. This wasn't programmed in: it emerged from the text.
Why Word Embeddings Matter
Before embeddings, most text software treated words as separate labels. A common representation was one-hot encoding: if your vocabulary has 100,000 words, each word is a list of 100,000 numbers with a single 1 and the rest 0. Two different words are exactly equally unlike each other, so "good" is as far from "great" as it is from "granite". The vectors are also huge and mostly empty.
Word embeddings replace that with a short dense vector, typically 100 to 300 numbers, where meaning is spread across all of them and distance is meaningful: similar words are close. This idea comes from the distributional hypothesis in linguistics: words that appear in similar contexts tend to have similar meanings. If "coffee" and "tea" both appear near "drink", "cup" and "hot", a model trained to predict context will give them similar vectors. That's all word2vec does, at scale.
| One-hot vector | Word embedding | |
|---|---|---|
| Length | Vocabulary size (tens of thousands or more) | Typically 100 to 300 |
| Values | Single 1, rest 0 | Dense real numbers |
| Similar words | No relationship | Close together |
| Learned from data | No | Yes |
| Captures analogies | No | Often, as directions |
If you want the general concept behind these vectors, including how modern models use them, see our guide to embeddings.
How Word2vec Works
Word2vec trains a small network with one hidden layer on a made-up prediction task, and then throws the task away and keeps the weights. The steps:
- Build a vocabulary from the corpus and give each word an index.
- Slide a window across the text. For each position, the word in the middle is the centre word and the words within a fixed distance on either side are its context.
- Train a network to predict the context from the centre (or the reverse). Each word starts with a randomly initialised vector, and every training example nudges the vectors of the words involved so the predictions improve.
- Keep the input weights. After training, the output layer is discarded. The weights from each word to the hidden layer are the word's embedding.
The network has no hidden non-linearity worth mentioning, which is why it's so fast. Everything depends on the quantity of text and on the two architectures below.
Worked Example: Training Pairs from One Sentence
Take the sentence "the cat sat on the mat" with a window of 2 (two words on each side). For the centre word "sat" the context words are "the", "cat", "on" and "the". Here is what each architecture would train on:
| Architecture | Input | Target to predict | Training examples from "sat" |
|---|---|---|---|
| Skip-gram | The centre word | Each context word, one at a time | (sat, the), (sat, cat), (sat, on), (sat, the) |
| CBOW | All the context words together | The centre word | ([the, cat, on, the], sat) |
Doing the same for every position gives skip-gram 18 pairs for this six-word sentence (2 + 3 + 4 + 4 + 3 + 2) and CBOW 6 examples, one per word. That difference explains much of the next section: skip-gram does more updates per sentence, and each rare word gets many chances to learn.
Skip Gram vs CBOW
The two architectures use the same network shape and differ only in what is predicted from what. Skip gram vs CBOW is a trade between quality on rare words and speed.
| CBOW (continuous bag of words) | Skip-gram | |
|---|---|---|
| Predicts | The centre word from its context | The context words from the centre word |
| Context handling | Averages the context vectors (order is ignored) | Treats each context word as a separate example |
| Training speed | Faster | Slower |
| Rare words | Weaker | Better |
| Small corpora | Weaker | Better |
| Default in gensim | Yes (sg=0) | No (sg=1) |
The original paper compared them on a test of analogy questions (8,869 semantic and 10,675 syntactic ones) with 300-dimensional vectors trained for three epochs on 783 million words:
| Model | Semantic accuracy | Syntactic accuracy | Total | Training time |
|---|---|---|---|---|
| CBOW | 15.5% | 53.1% | 36.1% | 1 day |
| Skip-gram | 50.0% | 55.9% | 53.3% | 3 days |
Skip-gram is far better on the semantic questions (for example, country and capital pairs), while the two are close on syntactic ones (plural forms, tenses), and CBOW is about three times faster. In practice, skip-gram with negative sampling became the popular choice, and many later libraries default to it for quality. Choose CBOW when training time is tight and the corpus is large; choose skip-gram when words are rare or the data is limited.
The Tricks That Made Word2vec Fast
Training a straightforward version means computing a score for every word in the vocabulary after each example, which is very slow when the vocabulary has millions of entries. The 2013 follow-up paper introduced several improvements that made the method practical:
- Negative sampling. Instead of updating the network for every word in the vocabulary, update it for the real context word (a positive example) and a handful of randomly chosen wrong words (negative examples). With 5 negatives per positive, a gensim default, each step is a tiny fraction of the full cost. The paper found that drawing negatives from a distribution based on word frequency raised to the power 3/4 worked well.
- Subsampling of frequent words. Words like "the", "in" and "a" appear hundreds of millions of times but carry little information about their neighbours. Word2vec randomly discards each occurrence with a probability that rises with its frequency, typically using a threshold around 10 to the power -5. The authors report speed-ups of roughly two to ten times and better vectors for rarer words.
- Hierarchical softmax. An alternative to negative sampling that organises the vocabulary as a tree so a word's probability takes a few steps to compute instead of one per word.
- Phrase detection. The paper also describes joining frequent word pairs into single tokens, so "Boston Globe" is treated as a unit rather than "Boston" plus "Globe".
Word2vec Analogies: What They Show and Don't
The analogy results made word2vec famous, but they need careful reading. The vector offset trick works like this: to answer "man is to king as woman is to what?", compute vector("king") - vector("man") + vector("woman") and look for the word whose vector is closest by cosine similarity, excluding the three input words.
| Question | Typical answer |
|---|---|
| king - man + woman | queen |
| Paris - France + Italy | Rome |
| Madrid - Spain + France | Paris |
| biggest - big + small | smallest |
Two cautions. First, the results are often cherry-picked: analogies work well for frequent, clean relationships like capitals, and poorly for many others. Second, the vectors absorb the biases in their training text. A 2016 study by Bolukbasi and colleagues showed that embeddings trained on Google News articles exhibited gender stereotypes to a disturbing extent, which is where the title "Man is to computer programmer as woman is to homemaker?" comes from, and proposed ways to reduce it. If you use embeddings in anything that affects people, test for bias.
How to Train Word2vec with gensim
The most common way to train word2vec in Python is the gensim library. These are the main settings and their defaults, from the gensim documentation:
| Parameter | Default | What it controls |
|---|---|---|
vector_size | 100 | Length of each word vector |
window | 5 | Context words considered on each side |
min_count | 5 | Ignore words that appear fewer times |
sg | 0 | 0 for CBOW, 1 for skip-gram |
negative | 5 | Number of negative samples per positive example |
sample | 0.001 | Threshold for down-sampling frequent words |
epochs | 5 | Passes over the corpus |
workers | 3 | Threads for training |
A minimal example, adapted from gensim's documentation. Here sentences is an iterable of token lists, such as [["the", "cat", "sat", "on", "the", "mat"], ...]:
from gensim.models import Word2Vec
model = Word2Vec(
sentences=sentences,
vector_size=100,
window=5,
min_count=5,
sg=1, # skip-gram
workers=4,
)
vector = model.wv["cat"]
print(model.wv.most_similar("cat", topn=10))
model.wv.save("word2vec.wordvectors")The input must already be tokenised: a list of lists of words. For large corpora, pass a streaming iterable instead of loading everything into memory. The saved KeyedVectors file is smaller and faster to load than the full model, which is all you need if you won't continue training. Training on a handful of sentences produces meaningless vectors: word2vec needs millions of words to be useful, which is why many people start from pre-trained vectors instead. (Mikolov's team released vectors trained on roughly 100 billion words of Google News text, covering about 3 million words and phrases.)
Word2vec vs GloVe, fastText and BERT
Word2vec started a family. These are the methods people compare it with:
| Method | How it learns | Key trait | Handles unseen words? | Context-aware? |
|---|---|---|---|---|
| Word2vec (2013) | Predicts neighbours with a shallow network | Fast, simple, strong baseline | No | No |
| GloVe (2014) | Factorises global word co-occurrence statistics | Uses counts for the whole corpus at once | No | No |
| fastText (2016 paper) | Skip-gram extended with character n-grams | Each word is the sum of its character n-gram vectors | Yes, builds vectors from parts | No |
| BERT-style models (2018 onward) | Transformers read the whole sentence | A word's vector depends on its sentence | Yes, via subword tokens | Yes |
The word2vec vs GloVe question comes down to method, not quality: both give one fixed vector per word, and on most tasks they perform similarly. Word2vec learns from local windows with a prediction task, GloVe from a global count matrix. fastText fixes one of word2vec's weaknesses: because each word is made of character n-grams, it can build a vector for a word it never saw in training, which helps with typos and languages with rich word forms.
The biggest change came with contextual models. Word2vec gives "bank" a single vector, whether the sentence is about rivers or money. A transformer produces a different vector for each occurrence, based on the surrounding words. That's why modern language systems moved to transformers; our BERT vs GPT guide explains how those models work, and the natural language processing overview shows where embeddings sit in the field's history.
Limitations of Word2vec
- One vector per word. "Bank", "bat" and "apple" each get a single blended vector, so different senses are mixed.
- No unseen words. A word not in the vocabulary has no vector, unlike fastText or subword models.
- Needs lots of text. Small corpora give noisy vectors; quality depends on data volume and domain.
- Inherits bias. Stereotypes in the text appear in the geometry.
- Not directly comparable across models. Two separately trained models live in different coordinate systems, so you can't compare or combine their vectors directly.
- Word order inside the window is mostly ignored. CBOW averages the context, and skip-gram only sees pairs.
Where Word2vec Is Still Used
Word2vec is no longer the state of the art for language understanding, but it remains useful because it's small, fast to train and easy to explain:
- A baseline. Training word2vec on your own domain text gives vectors for specialised vocabulary (medical, legal, product names) that general models may lack.
- Recommendations and search. Treating items in a user's session like words in a sentence and training skip-gram gives item vectors that capture "bought together" similarity.
- Features for classic models. Averaged word vectors are a quick feature set for text classification when you don't have the budget for a transformer.
- Teaching. It is the clearest way to see how meaning can become geometry.
Common Mistakes
- Training on too little text. A few thousand sentences won't produce usable vectors. Use a large corpus or pre-trained vectors.
- Inconsistent preprocessing. Mixed case, stray punctuation and different tokenisation split the same word into several. Normalise before training.
- Leaving `min_count` at the default blindly. On small data, the default of 5 can drop most of your vocabulary; on huge data, a higher value saves memory.
- Trusting analogies as proof of understanding. They work for a few clean relations and fail for many others.
- Ignoring bias. Test for stereotypes before using embeddings in decisions about people.
- Mixing vectors from different training runs. Each run has its own space.
- Averaging word vectors for long documents and expecting nuance. Averaging loses order and context; use a sentence-embedding model when meaning matters.
FAQ
What is word2vec used for?
Word2vec is used to turn words into dense vectors that capture meaning, which then feed text classification, search, recommendation and clustering. It is also a common baseline and teaching example for embeddings.
What is the difference between skip-gram and CBOW?
Skip-gram predicts the surrounding words from one centre word, and CBOW predicts the centre word from its surrounding words together. Skip-gram is slower but better on rare words and small data, CBOW is faster.
Is word2vec still used?
Yes, though transformer-based embeddings have replaced it for most language tasks. Word2vec still appears as a lightweight baseline, for domain-specific vocabulary and for recommendation-style problems where items behave like words.
What is the difference between word2vec and GloVe?
Both learn one fixed vector per word. Word2vec learns by predicting words from their local context, while GloVe fits vectors to global co-occurrence counts. On most tasks their quality is similar.
Can word2vec handle new words?
No. A word that wasn't in the training vocabulary has no vector. fastText and subword-based transformer models solve this by building vectors from pieces of words.