AI from scratch · Word vectors · Stage 5: seeing and reading

Word vectors

The tokens lesson turned text into ids, and chapter 7 said every id looks up a learned vector, its embedding, with similar words placed close together. Where do those vectors come from, and what's in them? This lesson answers with the idea that started modern NLP in 2013: train vectors so that a word can predict its neighbors, and meaning appears as geometry. You'll train a tiny version from scratch, then explore 20,000 real vectors learned from six billion words of Wikipedia and news: nearest neighbors, analogies, and the biases they absorbed from the text.

1. You shall know a word by the company it keeps

That's the linguist J. R. Firth in 1957, and it's the whole trick. Words that appear in the same contexts ("I took the ___ to work": train, bus, subway) tend to mean related things. So give each word a vector and adjust the vectors until words that share contexts point in similar directions. Then cosine similarity (chapter 7: the dot product of the directions) measures relatedness. Try it on GloVe vectors, 50 numbers per word:

Loading 20,000 word vectors (1 MB)…

Try jazz, pizza, brooklyn, gradient. Then bank, apple and python, which are worth a second look (section 5).

Words that appear in the same contexts get nearby vectors, so closeness in the vector space stands in for closeness in meaning.

2. word2vec: predict the neighbors

Skip-gram (word2vec, Mikolov and colleagues at Google, 2013) turns the idea into a training task. Slide a window over the text; for each word, its neighbors within 2 positions are "context". The model gives each word two vectors, \(w\) for when it's the center and \(c\) for when it's context, and wants \(\sigma(w \cdot c)\) (chapter 3's neuron) to be close to 1 for real pairs and close to 0 for random negative samples, words drawn at random that probably aren't neighbors:

\[ L = -\ln \sigma(w \cdot c_{\text{true}}) - \sum_{k=1}^{K} \ln \sigma(-\,w \cdot c_{\text{neg},k}) \]

That's log loss on a yes/no question, "were these two words neighbors?", with the vectors as the only weights. Words that share neighbors get pulled toward the same context vectors, so they end up near each other. A tiny version, on a made-up corpus where cats and dogs do the same things:

Why do "cat" and "dog" end up close, although they never appear in the same sentence here?

Every update moves a center vector toward its true contexts' vectors. Two words with the same contexts get moved toward the same places. That's Firth's idea, turned into gradient descent.

Skip-gram trains each word's vector to say "yes" to its real neighbors and "no" to random words, so words with shared neighbors drift together.

Why the dot products end up measuring co-occurrence
  1. Define the pointwise mutual information of two words, \(\operatorname{PMI}(w, c) = \ln \frac{P(w, c)}{P(w) P(c)}\): how much more often they appear together than they would by chance (0 if independent). Probability 5's mutual information is its average over all pairs.
  2. For one pair \((w, c)\), the skip-gram loss above is minimized, over the single number \(x = w \cdot c\), where its slope is zero. Real pairs pull \(x\) up in proportion to how often they occur; negatives push it down in proportion to \(K\) times how often \(c\) is drawn at random.
  3. Setting the slope to zero gives \(\sigma(x) / \sigma(-x) = e^x = \frac{P(w, c)}{K\, P(w) P(c)}\), so \(w \cdot c = \operatorname{PMI}(w, c) - \ln K\) (Levy and Goldberg, 2014).
  4. So skip-gram is secretly factoring a huge table of word-pair PMIs into two thin matrices: every word's 50 or 300 numbers summarize its row of that table (the SVD lesson's low-rank idea).
  5. GloVe, the vectors in this page, fits the log co-occurrence counts directly with a weighted least-squares loss, and lands in much the same place.

3. Analogies: relations as directions

If the step from man to king and the step from woman to queen are the same "royalty" direction, then \(\text{king} - \text{man} + \text{woman}\) should land near queen. Chapter 7 drew this with 16 hand-placed words; here are the real vectors (the three input words are excluded from the answer).

is to as is to …

Some that work: paris : france :: tokyo : ? (japan), walk : walked :: swim : ? (swam), good : better :: bad : ? (worse). Not every relation is a clean straight line, and the answer list often shows the near misses.

Without excluding the input words, what does king − man + woman return first?

Measured on these vectors: "king" first, "queen" second. The famous analogy results all exclude the input words, which makes them look cleaner than the geometry really is.

Relations like royalty, tense and capital-of often show up as roughly constant directions, so vector arithmetic can complete an analogy, imperfectly.

4. The biases words carry

The vectors learned whatever patterns the text has, including the ones nobody wants. Project occupation words onto the direction from she to he: positive leans "he", negative leans "she".

In these GloVe vectors nurse and dancer lean strongly toward she, captain and boss toward he, and the analogy man : doctor :: woman : ? answers nurse. The words come from 2014 Wikipedia and news text, and the vectors faithfully compress how that text used them. Surprises cut both ways: secretary leans he, probably from "Secretary of State" and "general secretary" in news. A model built on these vectors (a résumé screener, a search ranker) inherits the leanings unless someone measures and corrects them.

A team uses these vectors to rank résumés by similarity to a job ad that says "engineer". What's the risk?

Chapter 12's advice applies: measure the results per group (slices) before shipping, and check the features themselves. Debiasing methods exist (removing the gender direction from neutral words) but only reduce what's measurable.

Word vectors compress how their training text used words, stereotypes included, so anything built on them can inherit those leanings unless they're measured.

5. One vector per word, and what came next

Look again at the neighbors of bank: banks, banking, securities, credit. The river bank is gone. apple's neighbors are blackberry, iphone, microsoft: the fruit lost out to the company in news text. A word2vec or GloVe vector is one point per word, an average over every sense the word was used in, dominated by the most common one.

Chapter 7's attention is the fix: a transformer starts each token with an embedding like these, then mixes in its context, so bank next to river ends up somewhere else than bank next to loan. These contextual embeddings replaced static word vectors almost everywhere by 2019. The idea of "meaning as a point you can measure distances between" lives on, scaled up to whole sentences and documents: stage 6's retrieval lesson searches this site's pages by embedding similarity.

Where it breaks: points that can't say everything

6. What to carry forward

All lessons: AI from scratch. Vectors: GloVe 6B 50d (Pennington, Socher and Manning, Stanford, 2014; Public Domain Dedication and License), the 20,000 most frequent words, stored as 8-bit unit vectors. Bias: Bolukbasi et al., "Man is to Computer Programmer as Woman is to Homemaker?" (2016).

Last updated