Search

Search papers and lessons

Word Embedding

Level 3 · 10 min read

A word embedding gives each word a list of numbers, learned from text so that words used in similar ways get nearby vectors.

On this page

  • Colour = topic mix
  • Language & LLMs
  • Representation learning
  • Linear algebra
  • Sign in to see your progress

TL;DR

A word embedding gives every word a short list of numbers, a Vector. The numbers are not written by hand. They are learned from large amounts of text, adjusted until they help predict the words around each word. Words that are used in similar ways end up with similar vectors.

Once each word is a vector, arithmetic can work on text. Closeness and direction between vectors carry meaning: "cat" and "dog" end up close together, and "car" ends up far from both.

Where you'll see it: at the input of nearly every language model, in search and recommendation systems that match words by meaning, and in classic tools such as word2vec and GloVe.

Intuition

Words as points in a room

A computer sees a word as a string of letters, or as an index such as 4817 in a dictionary. Neither says anything about meaning. To a plain index, "cat" is as unrelated to "dog" as it is to "carburettor".

Picture a large room in which every word is a point. Place the points so that words that behave alike stand close together: animals in one corner, vehicles in another, numbers in a third. A word embedding is that placement, written down as coordinates. With 300 numbers per word, each word is a point in 300-dimensional space. You cannot picture that space, but the same geometry works in it.

Why "used alike" is the right signal

Linguists have long noticed that a word's neighbours tell you much of what it means. J. R. Firth put it as "you shall know a word by the company it keeps". Words that fit the same blank tend to mean similar things. "The ___ barked all night" fits dog, puppy and wolf. It does not fit carburettor.

An older approach counted co-occurrences into very long, mostly empty vectors. An embedding compresses that information into a short, dense vector, usually a few hundred numbers, where every number carries a little of everything.

flowchart LR
  A["word: dog"] --> B["index 4817"]
  B --> C["row 4817 of the table E"]
  C --> D["vector of 300 numbers"]
  D --> E["fed to the network"]

The math

The vocabulary and the one-hot vector

Let VV be the number of distinct words we keep, the vocabulary, and give each word an index i∈{1,…,V}i \in \{1, \dots, V\}. The one-hot vector for word ii is ei∈RV\mathbf{e}_i \in \mathbb{R}^V. It has zeros everywhere except a single 1 in position ii. It identifies the word exactly, but it carries no similarity: for two different words i≠ji \ne j, ei⋅ej=0\mathbf{e}_i \cdot \mathbf{e}_j = 0, so every pair of words is equally unrelated.

The embedding matrix

Choose an embedding size dd, commonly between 50 and a few thousand. Store a matrix E∈Rd×VE \in \mathbb{R}^{d \times V} whose ii-th column is the embedding of word ii:

vi=E ei.\mathbf{v}_i = E\,\mathbf{e}_i.

Multiplying EE by the one-hot vector ei\mathbf{e}_i simply picks out column ii. In practice a lookup does the same job faster. The matrix form matters for training: an embedding is a linear layer applied to a one-hot input, so its entries are weights that gradient methods can adjust like any other matrix weights.

Measuring closeness

The dot product u⋅v=∑kukvk\mathbf{u} \cdot \mathbf{v} = \sum_k u_k v_k is the usual starting point. Its size depends on the length of the vectors, so for meaning we usually use cosine similarity:

cos⁡(u,v)=u⋅v∥u∥ ∥v∥,∥u∥=∑kuk2.\cos(\mathbf{u}, \mathbf{v}) = \frac{\mathbf{u} \cdot \mathbf{v}}{\lVert \mathbf{u} \rVert \, \lVert \mathbf{v} \rVert}, \qquad \lVert \mathbf{u} \rVert = \sqrt{\textstyle\sum_k u_k^2}.

It lies between −1-1 and 11 and ignores length. Near 1 means the two vectors point the same way, near 0 means they are unrelated, and near −1-1 means they point in opposite directions.

How the numbers are learned

The table starts as random numbers. Training picks a task that uses word vectors and adjusts EE to improve it. In the skip-gram version of word2vec (Mikolov et al., 2013), a centre word ww must predict the words cc around it. Each word gets an input vector vw\mathbf{v}_w (a column of EE) and an output vector uc\mathbf{u}_c. The probability of context word cc given centre word ww is a Softmax over the vocabulary:

P(c∣w)=exp⁡(uc⋅vw)∑c′=1Vexp⁡(uc′⋅vw).P(c \mid w) = \frac{\exp(\mathbf{u}_c \cdot \mathbf{v}_w)}{\sum_{c'=1}^{V} \exp(\mathbf{u}_{c'} \cdot \mathbf{v}_w)}.

Training maximises log⁡P(c∣w)\log P(c \mid w) over observed pairs. Its gradient with respect to vw\mathbf{v}_w is

∂log⁡P(c∣w)∂vw=uc−∑c′=1VP(c′∣w) uc′.\frac{\partial \log P(c \mid w)}{\partial \mathbf{v}_w} = \mathbf{u}_c - \sum_{c'=1}^{V} P(c' \mid w)\, \mathbf{u}_{c'}.

Read it as: move vw\mathbf{v}_w toward the output vector of the word that really appeared, and away from the average output vector the model currently expects. The full sum over VV words is expensive for a large vocabulary, so word2vec replaces it with negative sampling: the model learns to tell the real pair from a few randomly drawn words.

Worked examples

Example
A tiny two-dimensional vocabulary

Vocabulary: cat, dog, car. Embedding size d=2d = 2. Suppose training produced:

cat=(0.9,0.8),dog=(0.8,0.9),car=(−0.7,0.1).\mathbf{cat} = (0.9, 0.8), \qquad \mathbf{dog} = (0.8, 0.9), \qquad \mathbf{car} = (-0.7, 0.1).
  1. Dot product: cat⋅dog=0.9×0.8+0.8×0.9=0.72+0.72=1.44\mathbf{cat} \cdot \mathbf{dog} = 0.9 \times 0.8 + 0.8 \times 0.9 = 0.72 + 0.72 = 1.44.
  2. Lengths: ∥cat∥=0.81+0.64=1.45≈1.2042\lVert \mathbf{cat} \rVert = \sqrt{0.81 + 0.64} = \sqrt{1.45} \approx 1.2042. The same squares appear for dog, so ∥dog∥≈1.2042\lVert \mathbf{dog} \rVert \approx 1.2042.
  3. Cosine: cos⁡(cat,dog)=1.44/(1.2042×1.2042)=1.44/1.45≈0.993\cos(\mathbf{cat}, \mathbf{dog}) = 1.44 / (1.2042 \times 1.2042) = 1.44 / 1.45 \approx 0.993.
  4. Dot product: cat⋅car=0.9×(−0.7)+0.8×0.1=−0.63+0.08=−0.55\mathbf{cat} \cdot \mathbf{car} = 0.9 \times (-0.7) + 0.8 \times 0.1 = -0.63 + 0.08 = -0.55.
  5. Length: ∥car∥=0.49+0.01=0.5≈0.7071\lVert \mathbf{car} \rVert = \sqrt{0.49 + 0.01} = \sqrt{0.5} \approx 0.7071.
  6. Cosine: cos⁡(cat,car)=−0.55/(1.2042×0.7071)=−0.55/0.8515≈−0.646\cos(\mathbf{cat}, \mathbf{car}) = -0.55 / (1.2042 \times 0.7071) = -0.55 / 0.8515 \approx -0.646.

Interpretation: in this toy, cat and dog point almost the same way (0.993), while cat and car point away from each other (-0.646). The geometry has put the animals on one side and the vehicle on the other.

Example
An analogy by vector arithmetic

Toy coordinates: the first number measures royalty, the second measures maleness.

king=(0.9,0.8),queen=(0.9,0.1),man=(0.1,0.8),woman=(0.1,0.1).\mathbf{king} = (0.9, 0.8), \quad \mathbf{queen} = (0.9, 0.1), \quad \mathbf{man} = (0.1, 0.8), \quad \mathbf{woman} = (0.1, 0.1).
  1. king−man=(0.9−0.1, 0.8−0.8)=(0.8, 0.0)\mathbf{king} - \mathbf{man} = (0.9 - 0.1,\ 0.8 - 0.8) = (0.8,\ 0.0).
  2. Add woman: (0.8+0.1, 0.0+0.1)=(0.9, 0.1)(0.8 + 0.1,\ 0.0 + 0.1) = (0.9,\ 0.1).
  3. This is exactly queen\mathbf{queen}.

Interpretation: subtracting man removes maleness and leaves royalty, and adding woman supplies femaleness. Learned embeddings never line up this neatly. In word2vec the analogy holds only approximately: the word whose vector is closest by cosine to king−man+woman\mathbf{king} - \mathbf{man} + \mathbf{woman}, excluding the three query words, is often "queen". Mikolov et al. reported examples of this kind.

Example
The size of a real table

Vocabulary of 50,000 words, embedding size d=300d = 300.

  1. Entries in EE: 50,000×300=15,000,00050{,}000 \times 300 = 15{,}000{,}000.
  2. Stored as 32-bit floats (4 bytes each): 15,000,000×4=60,000,00015{,}000{,}000 \times 4 = 60{,}000{,}000 bytes, about 60 MB.
  3. A one-hot vector of length 50,000 holds 50,000 numbers, nearly all zero. The 300-number embedding is about 170 times shorter: 50,000/300≈16750{,}000 / 300 \approx 167.

Interpretation: the whole table fits in ordinary memory, and one lookup costs almost nothing. Most of a large model's parameters sit elsewhere, but this table is already a substantial part of a small model.

Tradeoffs and failure modes

Static embeddings give one vector per word, whatever the sentence. That is cheap and easy to inspect, and it fails in predictable ways.

SituationWhat goes wrongBetter choice
A word with several meanings ("bank" the riverside and "bank" the lender)One vector must cover every sense, so its neighbours are a blendContextual embeddings from a Transformer, which give each occurrence its own vector
Rare words, misspellings, namesToo few examples to learn a good vector; some words are missing entirelySubword Tokenization, which splits unknown words into pieces that are known
Meaning of a whole sentence or documentAveraging word vectors loses word order and emphasisA sentence encoder, or the pooled output of a transformer
Biased training textThe vectors absorb associations in the text. A 2016 study found gender stereotypes in word2vec neighboursAudit neighbours before use, debias, or use better-curated data
One fixed table for every taskThe vectors are not tuned to your taskFine-tune the embedding table with the rest of the model

Use static embeddings when you need a cheap, fast representation for search, clustering or a small classifier trained on limited data. Avoid them when the sense of a word depends on its context.

History

The idea goes back to the mid-1950s. Firth's remark about the company a word keeps came in 1957. In 1986 Geoffrey Hinton argued that concepts could be represented as patterns across many units, which he called distributed representations.

Count-based methods came first in practice. Latent semantic analysis, around 1990, factored a word-document count matrix into dense dimensions. Learned neural embeddings followed. In the early 2000s Yoshua Bengio and colleagues trained word vectors jointly with a neural language model, and the vectors were a by-product of predicting the next word.

Mikolov and colleagues released word2vec in 2013. It trained on very large corpora quickly, and its vectors showed the arithmetic analogies that made the idea famous. Pennington, Socher and Manning's GloVe (2014) combined counts with a learning objective. Both spread because the vectors were pretrained once, shared, and useful in other people's systems. From about 2018, contextual embeddings from transformer models such as BERT largely replaced static vectors for demanding tasks, though static embeddings remain common for simpler ones.

Check yourself

QuestionRecall: what is a one-hot vector, and why does it say nothing about similarity between words?Show answer
A one-hot vector has a 1 in the position of one word and 0 everywhere else. The dot product of any two different one-hot vectors is 0, so every pair of distinct words looks equally unrelated. The representation identifies words but cannot express closeness.
QuestionComputation: find the dot product and the cosine similarity of a = (3, 4) and b = (4, 3).Show answer
The dot product is 3×4+4×3=243 \times 4 + 4 \times 3 = 24. Both lengths are 32+42=5\sqrt{3^2 + 4^2} = 5. So the cosine is 24/(5×5)=0.9624 / (5 \times 5) = 0.96. The vectors point in quite similar directions, so the score is high.
QuestionWhy: why does looking up row i of E give the same result as multiplying E by the one-hot vector for word i, and why does that equivalence matter for training?Show answer
Multiplying a matrix by a one-hot vector selects the column whose position holds the 1, so E eiE\,\mathbf{e}_i is exactly column ii. The equivalence matters because the embedding is then a linear layer. Its entries are ordinary weights, and gradients flow into them, so the table can be trained by the same methods as any other weights.
QuestionApplied: you have 2,000 medical notes and need search to match 'heart attack' with 'myocardial infarction'. Would you train word vectors from scratch on these notes alone?Show answer
Probably not. Two thousand notes is a small corpus, and the two terms may rarely co-occur, so their vectors would be poor. Start with vectors or a sentence encoder pretrained on a large corpus, ideally one that includes medical text. Then check the nearest neighbours of key terms on your own notes, and fine-tune only if the results are still weak.

Sources