0101010101cat0kitten1dog2car3truck4d00.80d10.60d0−0.60d1−0.50d00.60d10.80d00.60d1−0.80d00.80d1−0.601−11−1d0d11v = E[ids["cat"]]2s = cos(E[a], E[b])3g = 1 - sigmoid(E[k] @ E[c])4E[k] += lr * g * E[c]next layers0.80 0.60catkittendogcartruck
Lamps: a one-hot vector · khaki cells: word IDs · slate cells: the embedding tableGlass map: the embedding space · pink points: animals, orange points: vehiclesViolet card: the NumPy lines · rose block: the network's next layersOn the left, the one-hot lamps, the word IDs and the embedding table: one row of two learned numbers per word. On the right, the embedding space, where each row is a point. Words with similar meanings sit close together, and the cosine of the angle between two arrows from the centre measures how similar they are. Training moves kitten's point toward cat in three gradient steps. Two numbers per word keep the picture flat. Real word vectors use 50 to 300 numbers (word2vec, GloVe), and language models use hundreds to thousands, so they cannot be drawn directly; "near" still means the same thing.

Words as numbers

  1. A network only does arithmetic, so each word in its vocabulary (the list of words it knows) gets an ID: cat 0, kitten 1, dog 2, car 3, truck 4. An ID is only a name tag: dog, 2, is not "between" kitten and car.

The embedding table

Meaning as distance

How embeddings learn

What happens

;; step 1/9 · ids
vocabulary   ids = {w: i for i, w in enumerate(words)}
  "cat"     -> 0
  "kitten"  -> 1
  "dog"     -> 2
  "car"     -> 3
  "truck"   -> 4

the numbers are arbitrary: sorting the list differently
would give every word a different ID

The rows for cat, dog, car and truck were chosen by hand (all length 1, so the cosines are clean). Kitten's three training steps are computed exactly. Real word2vec keeps two tables (one for each word, one for its neighbours), updates both, and also pushes each word away from a few random "negative" words. Here only kitten moves, toward one neighbour, with learning rate 1.