◆ AI All-in-One

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
↗ Plan a path here

Read first

Neural NetworksDot Product, Norms and Similarity

This leads to

Sentence Embeddings
The full path from zero — 15 concepts before this one
  1. What Is AI?
  2. Vectors
  3. Derivatives and Slopes
  4. Probability Basics
  5. How Machines Learn
  6. Partial Derivatives and Gradients
  7. Matrices and Matrix Multiplication
  8. Dot Product, Norms and Similarity
  9. Supervised, Unsupervised and Reinforcement Learning
  10. Gradient Descent
  11. Supervised Learning
  12. Linear Regression
  13. The Perceptron
  14. Logistic Regression
  15. Neural Networks
  16. 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.

man woman king queen boy girl France Paris Japan Tokyo Spain Madrid king − man + woman ≈ queen start at king, take the “male → female” step (orange) that leads from man to woman purple dashed: “ordinary → royal” green: “country → capital”, another consistent direction
Fig. 1 An embedding space, flattened to two dimensions for drawing. Similar words sit near each other, and consistent relationships become parallel arrows: male → female (orange), ordinary → royal (purple), country → capital (green). Following the orange arrow from "king" lands near "queen".

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 VV words, word number kk becomes a vector of VV zeros with a single 1 in position kk. 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:

cos⁡(a,b)=a⋅b∥a∥ ∥b∥\cos(\mathbf{a}, \mathbf{b}) = \frac{\mathbf{a} \cdot \mathbf{b}}{\lVert \mathbf{a} \rVert \, \lVert \mathbf{b} \rVert}

Here a⋅b\mathbf{a} \cdot \mathbf{b} multiplies matching entries and adds them up, and ∥a∥\lVert \mathbf{a} \rVert is the length of a\mathbf{a} (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: 0.9×0.9+0.9×0.1+0.8×0.8=0.81+0.09+0.64=1.540.9 \times 0.9 + 0.9 \times 0.1 + 0.8 \times 0.8 = 0.81 + 0.09 + 0.64 = 1.54
  • Lengths: ∥king∥=0.81+0.81+0.64=2.26≈1.503\lVert \text{king} \rVert = \sqrt{0.81 + 0.81 + 0.64} = \sqrt{2.26} \approx 1.503 and ∥queen∥=0.81+0.01+0.64=1.46≈1.208\lVert \text{queen} \rVert = \sqrt{0.81 + 0.01 + 0.64} = \sqrt{1.46} \approx 1.208
  • Cosine: 1.54/(1.503×1.208)≈0.851.54 / (1.503 \times 1.208) \approx 0.85

King and man also come out at 0.85, since they share "male" instead of "royal". King and woman share only "person", giving 0.82/(1.503×0.812)≈0.670.82 / (1.503 \times 0.812) \approx 0.67.

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:

king−man+woman=(0.9−0.1+0.1,  0.9−0.9+0.1,  0.8−0.8+0.8)=(0.9,  0.1,  0.8)\text{king} - \text{man} + \text{woman} = (0.9 - 0.1 + 0.1,\; 0.9 - 0.9 + 0.1,\; 0.8 - 0.8 + 0.8) = (0.9,\; 0.1,\; 0.8)

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:

the quick brown fox jumps over the lazy dog window: 2 words each side of the centre word 1 · slide a window over the text and collect (centre, context) pairs (fox, quick) (fox, brown) (fox, jumps) (fox, over) 2 · train a tiny network to predict the context word from the centre word 0 0 0 0 1 0 0 0 0 0 “fox”one-hot,length V embedding matrixV rows × d columns:pick the row for “fox” word vectord numbers (e.g. 300)this is the embedding output+ softmax brown quick jumps over lazy … P(context | fox)probability for everyword in the vocabulary
Fig. 2 Skip-gram in two steps. Slide a window over the text, collecting (centre, context) word pairs. Then train a tiny network: look up the centre word's vector in the embedding matrix and use it to predict which words appear around it. The rows of the embedding matrix become the word vectors.
  1. 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).
  2. Each word ww has an embedding vw\mathbf{v}_w (a row of the embedding matrix) and a separate "output" vector uw\mathbf{u}_w.
  3. The model predicts context word oo from centre word cc with a softmax over the whole vocabulary:
P(o∣c)=exp⁡(uo⋅vc)∑w=1Vexp⁡(uw⋅vc)P(o \mid c) = \frac{\exp(\mathbf{u}_o \cdot \mathbf{v}_c)}{\sum_{w=1}^{V} \exp(\mathbf{u}_w \cdot \mathbf{v}_c)}

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:

log⁡σ(uo⋅vc)+∑k=1Klog⁡σ(−unk⋅vc)\log \sigma(\mathbf{u}_o \cdot \mathbf{v}_c) + \sum_{k=1}^{K} \log \sigma(-\mathbf{u}_{n_k} \cdot \mathbf{v}_c)

where σ\sigma is the sigmoid and n1,…,nKn_1, \dots, n_K 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 kk means taking row kk, 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 nearest function 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

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

  1. By hand, using the three-dimensional table: compute cos⁡(queen,woman)\cos(\text{queen}, \text{woman}). Then compute queen−woman+man\text{queen} - \text{woman} + \text{man}. Which word is it?
  2. 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 + woman now clearly prefer "queen" over "princess"?
  3. 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 0.09+0.01+0.64=0.740.09 + 0.01 + 0.64 = 0.74, and the lengths are 1.46\sqrt{1.46} and 0.66\sqrt{0.66}, so the cosine is about 0.75.

Check your understanding

5 quick questions. Pick an answer to see whether you were right and why. Your best score is saved on this device.

  1. With one-hot vectors over a 50,000-word vocabulary, what is the dot product between 'cat' and 'kitten'?

  2. Using the toy vectors king (0.9, 0.9, 0.8), man (0.1, 0.9, 0.8) and woman (0.1, 0.1, 0.8), what is king − man + woman?

  3. You run the analogy king − man + woman on real embeddings and the nearest word is 'king'. What did you forget?

  4. Why did word2vec use negative sampling?

  5. A search system using static word2vec vectors confuses river banks with banks that hold money. What is the underlying limit, and what fixes it?

Finished this chapter?

Learn more

Hand-picked courses, books, videos and tutorials for going deeper. See all resources →

Article

The Illustrated Word2vec

Jay Alammar · 2019 · Beginner · Free

A gentle, picture-heavy explanation of how words become vectors and why their dot products capture meaning.

Paper

GloVe: Global Vectors for Word Representation

Pennington, Socher & Manning (Stanford) · 2014 · Intermediate · Free

Project page with the paper and downloadable pretrained word vectors learned from global co-occurrence counts.

Tool

Gensim

Radim Řehůřek and contributors · Intermediate · Free

Python library for training word2vec, fastText and topic models and for loading pretrained word vectors.

Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/dl/word-embeddings.md