Sub topic 2
Dense Embeddings: Words as Points in a Vector Space
Assume you know basic Python and NumPy, vectors, dot products, norms, conditional probability, and gradient descent. You should also know that tokenization turns text into tokens such as words or subwords.
From sparse vectors to dense vectors
A vocabulary is the set of tokens in a collection of text. A one-hot vector represents one vocabulary item with a single 1 and 0 everywhere else. If the vocabulary has 100,000 words, every one-hot vector has 100,000 components.
One-hot vectors identify words, but they do not express relationships. The vectors for cat and dog are equally distant from each other as cat and airplane. The representation contains no information about meaning.
A dense embedding is a relatively short vector of real numbers learned from text. For example, a word might have a 100-dimensional embedding:
import numpy as np
cat = np.array([0.21, -0.44, 0.08, 0.67])
dog = np.array([0.19, -0.39, 0.12, 0.61])
print(cat.shape)
print(np.linalg.norm(cat))Real models use many more dimensions. Each dimension usually does not have a clear human label such as “animalness.” Meaning is distributed across the dimensions and across relationships between vectors.
The distributional idea
The distributional hypothesis says that words appearing in similar contexts tend to have similar meanings. For example, these sentences provide related contexts:
- “The cat chased the mouse.”
- “The dog chased the ball.”
Because cat and dog occur near similar words, a learning algorithm can place their vectors near each other. This does not require a dictionary definition. It uses patterns in the surrounding text.
The vectors are learned parameters. Word2vec learns them by predicting words from nearby words or nearby words from a word. GloVe learns them from aggregated word co-occurrence counts. In both cases, the training signal comes from context.
Why the geometry matters
Once words have vectors, vector operations become useful:
| Operation | What it tells you |
|---|---|
| Dot product | Alignment, affected by vector length |
| Euclidean distance | Straight-line separation |
| Cosine similarity | Directional similarity, mostly ignoring length |
Cosine similarity compares the angle between two vectors:
import numpy as np
def cosine(u, v):
return float(np.dot(u, v) / (np.linalg.norm(u) * np.linalg.norm(v)))
a = np.array([1.0, 0.0])
b = np.array([1.0, 1.0])
print(cosine(a, b)) # about 0.707A value near 1 means similar directions. A value near 0 means weak alignment. These values are useful signals, not guaranteed measures of human meaning.
Exercise
Why can dense embeddings represent relationships that one-hot vectors cannot?
Show answer
Dense embeddings are learned from context, so distances and directions can encode recurring relationships. One-hot vectors only identify vocabulary entries.