Sub topic 3
Dense embeddings: words as points in a vector space
This chapter assumes you know basic Python and NumPy, and that you can read a vector, a dot product and a norm. It builds on the previous chapters. One-hot vectors treat every word as equally different from every other word, and the distributional hypothesis says that a word's meaning shows up in the contexts it appears in. Here we turn those two ideas into a concrete object: the dense embedding.
What a dense embedding is
A dense embedding maps each word in a vocabulary to a real-valued vector of fixed, small length, usually 50 to 300 dimensions. Nearly every component is nonzero. Compare that with a one-hot vector, which has the vocabulary size V as its length (often 100,000 or more), with a single 1 and V − 1 zeros.
The collection of vectors is stored as one matrix E with shape (V, d). Row i is the vector for the word with index i. Looking up a word is a row selection, nothing more.
import numpy as np
vocab = ["the", "cat", "dog", "mat", "sits"]
word_to_id = {w: i for i, w in enumerate(vocab)}
rng = np.random.default_rng(0)
d = 4
E = rng.normal(size=(len(vocab), d)) # one row per word
def embed(word):
return E[word_to_id[word]]
print(E.shape) # (5, 4)
print(embed("cat")) # a dense vector of 4 floatsHere E is random, so the vectors carry no meaning yet. Training (covered in later chapters) adjusts the rows so that geometry reflects usage.
The lookup is a one-hot product
Multiplying a one-hot vector by E selects a row. This is why embedding layers in neural networks are implemented as table lookups rather than matrix multiplications.
one_hot_cat = np.zeros(len(vocab))
one_hot_cat[word_to_id["cat"]] = 1.0
print(np.allclose(one_hot_cat @ E, embed("cat"))) # TrueThe two computations give the same result. The lookup costs O(d), while the full product costs O(V·d). With a large vocabulary that difference matters.
Why dense beats sparse
Three properties explain the improvement.
- Compactness. A vocabulary of 200,000 words with 100-dimensional vectors needs 20 million floats, about 80 MB at float32. The vectors are also small enough to feed into downstream models without a huge input layer.
- Similarity is expressible. In a one-hot space, the dot product between any two different words is exactly 0. In a dense space, related words can have vectors that point in similar directions, so "cat" and "dog" can be closer than "cat" and "mortgage".
- Generalization. If a classifier learns that a sentence containing "excellent" is positive, it can transfer some of that to "superb" when their vectors are close. With one-hot inputs, "superb" shares nothing with "excellent", so the classifier must see it in training data.
Dimensions are not interpretable features
A common mistake is to read dimension 17 as "animacy" or dimension 42 as "royalty". Training gives no such guarantee. Any invertible rotation of the whole space, applied to every vector, preserves all dot products, distances and angles between words. The rotated embedding is equally good, yet every individual coordinate has changed. Meaning lives in the relative geometry: directions, distances and angles between vectors, not in single coordinates.
# A random orthogonal matrix (rotation/reflection) keeps all cosines unchanged
Q, _ = np.linalg.qr(rng.normal(size=(d, d)))
E_rot = E @ Q
def cos(u, v):
return float(u @ v / (np.linalg.norm(u) * np.linalg.norm(v)))
print(cos(E[1], E[2])) # cat vs dog
print(cos(E_rot[1], E_rot[2])) # same value, different coordinatesThis also means that embeddings trained separately, even on the same corpus, cannot be compared coordinate by coordinate. Two runs produce spaces that are similar only up to such a transformation, plus noise from random initialization. Averaging or concatenating vectors from different runs without aligning them first gives nonsense.
How the choice of d affects results
The dimensionality d is a hyperparameter with a trade-off.
| Dimensions | Effect |
|---|---|
| Too small (e.g. 5 to 10) | The space cannot separate many distinct relations. Unrelated words are forced close together. |
| Typical (50 to 300) | Good balance of quality, memory and speed for most tasks. |
| Very large (1000+) | Little gain on most benchmarks, more memory and more risk of overfitting with small corpora. |
Gains usually flatten somewhere around 200 to 300 dimensions for corpora of around a billion tokens. For a small corpus, a smaller d is often better, because there is not enough data to pin down many dimensions.
A picture of the space
Think of each word as a point. Words used in similar contexts land near each other, and groups form without anyone labeling them. The diagram below sketches this as a flow from raw text to a usable space.
Common errors
- Treating coordinates as features. As shown above, only relative geometry is meaningful.
- Mixing embedding spaces. A vector from one trained model means nothing in another model's space.
- Forgetting the vocabulary. The matrix has rows only for words seen during training, subject to any frequency cutoff. A word with no row has no vector. Later chapters return to this under unknown words.
- Comparing raw lengths. Vector norms often correlate with word frequency. Comparing similarity by Euclidean distance can therefore be misleading. The next chapter introduces cosine similarity, which removes length from the comparison.
- Expecting small-corpus vectors to be good. Dense vectors are estimated from co-occurrence evidence. With a few thousand tokens, neighbours are mostly noise.
Checking the properties yourself
This short check confirms the key claims: one-hot vectors are all mutually orthogonal, and a dense lookup is the same as a one-hot product.
import numpy as np
V, d = 6, 3
rng = np.random.default_rng(1)
E = rng.normal(size=(V, d))
I = np.eye(V) # rows are one-hot vectors
# Every pair of distinct one-hot vectors has dot product 0
off_diagonal = I @ I.T - np.eye(V)
print(np.abs(off_diagonal).max()) # 0.0
# Lookup equals one-hot product
print(np.allclose(I @ E, E)) # TrueExercise
A colleague inspects a trained embedding and says "dimension 5 encodes gender, because king and man have large positive values there". You apply a random orthogonal rotation to every vector in the matrix. Which of these change: the cosine between king and man, the value in dimension 5 for king, or the nearest neighbours of king? What does this say about the colleague's claim?
Show answer
Only the value in dimension 5 for king changes. The cosine between king and man and the nearest neighbours of king stay the same, because rotation preserves dot products, norms and angles. Since a rotated space is just as valid as the original, no single coordinate has a fixed meaning. The claim is unfounded. Meaning is carried by relative geometry such as directions and distances, not by individual dimensions.
Exercise
A vocabulary has 50,000 words and you use 100-dimensional float32 embeddings. How many bytes does the matrix E need, and how many bytes would a full one-hot representation of a single word need if stored densely at float32?
Show answer
The matrix has 50,000 × 100 = 5,000,000 floats, and at 4 bytes each that is 20,000,000 bytes (about 20 MB). A single dense one-hot vector has 50,000 floats, which is 200,000 bytes. The embedding is 100 floats, or 400 bytes, per word. The one-hot vector is 500 times longer than the embedding.