Level 3 In-Depth AI · Deep Learning
Word Embeddings
Represent each word as a list of a few hundred numbers, learned so that words used in similar ways end up close together. Directions in this space carry meaning, as in king − man + woman ≈ queen.
- Level
- ●●●●● Easy
- Reading
- 14 min
- To learn it well
- 1 hour to read, an afternoon to practise
- Builds on
- 15 concepts →
- Quiz
- 5 questions ↓
This leads to
Sentence EmbeddingsThe full path from zero — 15 concepts before this one
- What Is AI?
- Vectors
- Derivatives and Slopes
- Probability Basics
- How Machines Learn
- Partial Derivatives and Gradients
- Matrices and Matrix Multiplication
- Dot Product, Norms and Similarity
- Supervised, Unsupervised and Reinforcement Learning
- Gradient Descent
- Supervised Learning
- Linear Regression
- The Perceptron
- Logistic Regression
- Neural Networks
- Word Embeddings
Read them roughly in this order. See it on the concept map →
Why it matters
A neural network only understands numbers. To feed it words, you must first turn each word into numbers. The obvious way, giving each word an ID, says nothing about meaning: "cat" might be word 1,042 and "kitten" word 31,877, with nothing to tell the network they are related.
A word embedding solves this by representing every word as a dense vector, a list of, say, 300 numbers, learned from text so that words used in similar ways get similar vectors. "Cat" and "kitten" end up close together, "cat" and "carburettor" far apart. Even better, directions in this space turn out to mean something. The step from "man" to "woman" is roughly the same as the step from "king" to "queen", or from "uncle" to "aunt".
Word embeddings, popularised by word2vec in 2013, were one of the ideas that brought deep learning into natural language processing. They gave every NLP system a cheap, general-purpose starting point. More importantly, they established the pattern behind all of modern AI: learn useful vector representations from huge amounts of unlabelled data (Self-Supervised Learning). Every The Transformer and large language model begins with an embedding layer of exactly this kind. Sentence Embeddings and Embeddings and Semantic Search extend the same idea from words to whole passages, and retrieval-augmented generation is built on them.
The intuition
"You shall know a word by the company it keeps." — J. R. Firth, 1957
This is the distributional hypothesis: words that appear in similar contexts tend to have similar meanings. You have never seen a "wampimuk", but if you read "the furry wampimuk climbed the tree and ate a nut", you already know a lot about it. It is probably small, an animal, something like a squirrel. You worked that out entirely from the company the word kept.
Word embeddings turn this into a training task. Slide along billions of words of text. For each word, try to predict its neighbours. To predict neighbours well, the network must give "cat" and "kitten" similar internal representations, because they have similar neighbours ("the ___ purred", "feed the ___"). The vector a word gets assigned along the way is its embedding. Nobody tells the network what any word means. Meaning falls out of the statistics of use.
Key idea A word embedding maps each word to a point in a space of a few hundred dimensions, learned so that words with similar contexts land close together. Closeness means similarity, and directions can encode relationships.
How it works
One-hot vectors and why they fail
The simplest way to make a word into a vector is one-hot encoding. With a vocabulary of words, word number becomes a vector of zeros with a single 1 in position . With 50,000 words, "cat" is 49,999 zeros and one 1.
Two problems. The vectors are huge and almost empty. And every pair of different words is equally unrelated: the dot product of any two different one-hot vectors is 0. "Cat" is exactly as similar to "kitten" as to "democracy".
Dense vectors and cosine similarity
An embedding instead gives each word a short, dense vector. Real systems use 50–1,000 numbers, typically 100–300 for word2vec-style vectors. To keep the example readable, imagine just three dimensions that happen to mean "royal", "male" and "person":
| Word | royal | male | person |
|---|---|---|---|
| king | 0.9 | 0.9 | 0.8 |
| queen | 0.9 | 0.1 | 0.8 |
| man | 0.1 | 0.9 | 0.8 |
| woman | 0.1 | 0.1 | 0.8 |
How similar are two words? The standard measure is cosine similarity: the cosine of the angle between their vectors. It is the dot product divided by the two lengths:
Here multiplies matching entries and adds them up, and is the length of (the square root of the sum of its squared entries). The result runs from −1 (opposite directions) through 0 (unrelated, at right angles) to 1 (same direction). Dividing by the lengths means only the direction counts, not how long the vectors are.
By hand for king and queen:
- Dot product:
- Lengths: and
- Cosine:
King and man also come out at 0.85, since they share "male" instead of "royal". King and woman share only "person", giving .
Analogies as vector arithmetic
Now the famous trick, called a word analogy. "Man is to king as woman is to what?" Take the vector for king, subtract man, add woman:
That is exactly the vector for queen. Subtracting man and adding woman removes "male" and keeps "royal". In real embeddings nothing is this tidy. The answer is the word whose vector is nearest (by cosine) to the result, excluding the three input words, and it is often but not always the right one. In the word2vec paper's analogy test set, examples like Paris − France + Italy ≈ Rome and biggest − big + small ≈ smallest worked well enough to make headlines.
No one designs the dimensions to mean "royal" or "male". Real embedding dimensions are not individually interpretable. Meaningful directions emerge as combinations of many dimensions, purely from co-occurrence statistics.
Learning them: word2vec skip-gram
Tomas Mikolov and colleagues at Google introduced word2vec in 2013, in two flavours. The more popular, skip-gram, works like this:
- Slide a window over the text. For each centre word, every word within, say, 2 positions on either side forms a training pair (centre, context).
- Each word has an embedding (a row of the embedding matrix) and a separate "output" vector .
- The model predicts context word from centre word with a softmax over the whole vocabulary:
In words: score every word in the vocabulary by its dot product with the centre word's vector, and turn the scores into probabilities with softmax. Training (Gradient Descent) maximises the probability of the context words that actually occurred. Words with similar contexts get pushed towards similar vectors, because that is the only way to make similar predictions.
The sum in the denominator runs over the whole vocabulary, which is expensive with a million words. Negative sampling replaces it with a cheaper question: is this (centre, context) pair real or fake? For each real pair, draw a handful of random "negative" words (typically 5–20) and train a logistic classifier to say yes to the real pair and no to the random ones:
where is the sigmoid and are the random negative words. This made it practical to train on Google News, about 100 billion words. The resulting 300-dimensional vectors for 3 million words and phrases were released publicly.
The other flavour, CBOW (continuous bag of words), does the reverse: it averages the context vectors and predicts the centre word. It is faster but usually a bit worse for rare words.
GloVe and fastText
GloVe (Global Vectors, Pennington, Socher and Manning at Stanford, 2014) takes a more direct route. It first counts how often each pair of words co-occurs across the whole corpus. Then it fits vectors so that the dot product of two words' vectors approximates the logarithm of their co-occurrence count. The results are similar in quality to word2vec, and pretrained GloVe vectors are still widely downloaded.
fastText (Facebook AI Research, 2016) represents each word as the sum of vectors for its character n-grams, its chunks of 3 to 6 letters. So it can build a sensible vector for a word it has never seen, such as a misspelling or a rare inflection, from its pieces. This matters for languages with rich word forms.
The embedding layer in neural networks
In a neural network, an embedding layer is just a learnable matrix with one row per vocabulary item. Looking up word means taking row , which is mathematically the same as multiplying a one-hot vector by the matrix, only far cheaper. You can initialise this matrix from word2vec or GloVe, or let it learn from scratch along with the rest of the network. Every RNN, LSTM and Transformer language model starts with one, over tokens rather than whole words.
The limit: one vector per word
A static embedding gives "bank" a single vector, whether the sentence is about rivers or money. The vector ends up as a blur of both meanings. Contextual embeddings, from ELMo (2018) and then BERT and its successors, fixed this by computing each word's vector from the whole sentence around it. That is why modern systems use Transformer embeddings rather than word2vec. But the geometry — similarity as closeness, meaning as direction — carried over unchanged.
In code
A tiny skip-gram model in PyTorch, trained in a couple of seconds on a toy corpus. Each sentence pairs a person word with a word that reveals gender (he/his/him or she/her/hers) and a word that reveals status (palace/crown/throne or farm/field/market). The model is never told about gender or royalty:
import random
import torch
import torch.nn as nn
import torch.nn.functional as F
random.seed(0); torch.manual_seed(0)
# Toy corpus: each person word appears with words that reveal its gender and its status
people = {"king": ("he", "royal"), "queen": ("she", "royal"),
"man": ("he", "common"), "woman": ("she", "common"),
"prince": ("he", "royal"), "princess": ("she", "royal"),
"boy": ("he", "common"), "girl": ("she", "common")}
words = {"he": ["he", "his", "him"], "she": ["she", "her", "hers"],
"royal": ["palace", "crown", "throne"], "common": ["farm", "field", "market"]}
sentences = []
for _ in range(3000):
w, (g, s) = random.choice(list(people.items()))
sentences.append([random.choice(words[g]), w, random.choice(words[s])])
vocab = sorted({w for s in sentences for w in s}); idx = {w: i for i, w in enumerate(vocab)}
pairs = [(idx[s[i]], idx[s[j]]) for s in sentences # (centre, context) pairs
for i in range(len(s)) for j in range(len(s)) if i != j]
centre, context = torch.tensor(pairs).T
print(len(vocab), "words,", len(pairs), "training pairs")
emb = nn.Embedding(len(vocab), 8) # the word vectors we want to learn
out = nn.Linear(8, len(vocab), bias=False) # scores every possible context word
opt = torch.optim.Adam([*emb.parameters(), *out.parameters()], lr=0.01)
for epoch in range(30):
for b in range(0, len(pairs), 256):
i = torch.randint(len(pairs), (256,))
loss = F.cross_entropy(out(emb(centre[i])), context[i]) # skip-gram: predict context from centre
opt.zero_grad(); loss.backward(); opt.step()
print(f"final loss {loss.item():.3f}")
E = F.normalize(emb.weight.detach(), dim=1) # unit length, so a dot product is a cosine similarity
def cos(a, b): return round((E[idx[a]] @ E[idx[b]]).item(), 2)
def nearest(vec, exclude):
sims = E @ F.normalize(vec, dim=0)
return [(vocab[j], round(sims[j].item(), 2)) for j in sims.argsort(descending=True) if vocab[j] not in exclude][:3]
v = lambda w: E[idx[w]]
for a, b in [("king", "prince"), ("king", "queen"), ("king", "man"), ("king", "field")]:
print(f"cos({a}, {b}) = {cos(a, b)}")
print("king - man + woman ≈", nearest(v("king") - v("man") + v("woman"), exclude={"king", "man", "woman"}))
# 20 words, 18000 training pairs
# final loss 2.137
# cos(king, prince) = 0.89
# cos(king, queen) = 0.31
# cos(king, man) = 0.29
# cos(king, field) = -0.04
# king - man + woman ≈ [('queen', 0.95), ('princess', 0.92), ('girl', 0.44)]
"King" and "prince" are nearly identical (0.89) because in this corpus they keep exactly the same company. "King" shares one property with "queen" and one with "man", so both are moderately similar, and it has nothing to do with "field". The analogy lands on "queen", with "princess" a close second, which is right: in our toy world the two are used identically.
For real work, download pretrained vectors. With the gensim library (pip install gensim), the GloVe vectors trained on Wikipedia and news text are one call away. This needs a download of roughly 130 MB, so it isn't run here:
import gensim.downloader as api
wv = api.load("glove-wiki-gigaword-100") # 400,000 words, 100 dimensions each
print(wv.most_similar("frog", topn=5)) # nearest neighbours by cosine similarity
print(wv.similarity("coffee", "tea")) # one cosine similarity
print(wv.most_similar(positive=["king", "woman"], negative=["man"], topn=3)) # analogy
Common pitfalls
- Forgetting to exclude the input words in analogies. The vector king − man + woman is usually still closest to "king" itself. Published analogy results exclude the three query words, as our
nearestfunction does. - Using raw dot products instead of cosine. Frequent words tend to have longer vectors. Without normalising, they show up as "similar" to everything.
- Out-of-vocabulary words. word2vec and GloVe have no vector for words they never saw. Use fastText-style subword models, or a modern subword tokenizer.
- Expecting one vector to handle ambiguity. "Bank", "bat" and "apple" (fruit or company) get one blurred vector each. Use contextual embeddings when that matters.
- Comparing vectors from different models. Each training run produces its own coordinate system. A vector from one model means nothing in another.
Watch out Embeddings learn the associations in their training text, including prejudices. Bolukbasi and colleagues showed in 2016 that word2vec vectors trained on Google News completed "man is to computer programmer as woman is to ___" with "homemaker". Systems built on such vectors can quietly reproduce these biases in search, hiring or translation. See Bias and Fairness.
Where it leads
- Tokenization and Transformer embedding layers: the same lookup table, over subword tokens.
- BERT and Encoder Models: contextual embeddings that give each occurrence of a word its own vector.
- Sentence Embeddings, Embeddings and Semantic Search and Vector Databases: embeddings for whole sentences and documents, compared by cosine similarity.
- Recommender Systems: the same trick applied to products and users ("item2vec").
- Graph Neural Networks: node embeddings for networks, in some methods learned with skip-gram over random walks.
- t-SNE and UMAP: how to squash hundreds of dimensions down to two for pictures like the one above.
A bit of history
The distributional hypothesis comes from linguists: Zellig Harris (1954) and J. R. Firth (1957). In the 1990s, latent semantic analysis built word vectors by factorising word–document count matrices. In 2003 Yoshua Bengio and colleagues trained the first neural language model with learned word embeddings (Language Modeling and Next-Token Prediction). Collobert and Weston showed in 2008–2011 that such embeddings helped many NLP tasks. In 2013 Tomas Mikolov and colleagues at Google released word2vec, two papers and open-source code fast enough to train on billions of words on one machine. The king − man + woman ≈ queen demonstration made embeddings famous far beyond NLP. GloVe followed in 2014 and fastText in 2016. From 2018, contextual embeddings from ELMo and BERT took over, but nearly every model today still starts by looking up a vector for each token.
Try it
- By hand, using the three-dimensional table: compute . Then compute . Which word is it?
- In the code, add a third property, for example age with "young/small" versus "old/grey" context words, so that prince and princess become young and king and queen old. Does
king - man + womannow clearly prefer "queen" over "princess"?- Change the embedding size from 8 to 2 and plot the 20 vectors with matplotlib. Do you see the structure? What gets lost?
Hint for 1: the dot product is , and the lengths are and , so the cosine is about 0.75.
Learn more
Hand-picked courses, books, videos and tutorials for going deeper. See all resources →
The Illustrated Word2vec
A gentle, picture-heavy explanation of how words become vectors and why their dot products capture meaning.
Efficient Estimation of Word Representations in Vector Space
word2vec: cheap, high-quality word embeddings with famous vector arithmetic.
Distributed Representations of Words and Phrases and their Compositionality
The second word2vec paper: negative sampling, subsampling of frequent words and phrase vectors.
GloVe: Global Vectors for Word Representation
Project page with the paper and downloadable pretrained word vectors learned from global co-occurrence counts.
Stanford CS224N: NLP with Deep Learning
Word vectors, RNNs, attention, Transformers and LLMs, with lecture videos on YouTube.
Gensim
Python library for training word2vec, fastText and topic models and for loading pretrained word vectors.
Man is to Computer Programmer as Woman is to Homemaker? Debiasing Word Embeddings
Showed that word2vec vectors encode gender stereotypes and proposed a way to reduce them.
Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/dl/word-embeddings.md