Computers can only do maths, so before a model can work with words it has to turn them into numbers. Not just any numbers: ones where words that mean similar things get similar numbers. An embedding is a list of numbers that places a word on a map of meaning, where close means similar. Here you’ll train one yourself, watch it work out that cats and dogs belong together without being told, and then do arithmetic with meaning.
Words as points#
The obvious ways of numbering words don’t help. Number them in alphabetical order and “apple” sits next to “apricot” but miles from “banana”, which says nothing about what they mean. Give every word its own on-off switch and every word is exactly as different from every other word: “cat” is no closer to “dog” than to “carburettor”.
Instead, give each word a short list of numbers, called a vector, and treat the numbers as coordinates. With two numbers per word you can draw every word as a point on a page. Real models use a few hundred numbers per word, which we can’t draw, but the idea is the same.
To compare two words, draw an arrow from the centre of the map to each one and compare the directions they point. That’s cosine similarity: 1 when the arrows point the same way, 0 when they’re at right angles, −1 when they point in opposite directions. How long the arrows are doesn’t matter, only the direction.
You shall know a word by the company it keeps#
So where do the numbers come from? Nobody types them in. They’re learned from ordinary text, using an idea the linguist J.R. Firth summed up in 1957: “You shall know a word by the company it keeps.” Words that turn up in the same kinds of sentences tend to mean similar things. You’ve never seen a “wampimuk”, but if you read that a wampimuk sleeps all day and eats and plays, you’d guess it’s an animal.
In 2013, Tomas Mikolov and colleagues at Google turned that idea into word2vec, a simple training game played over a huge pile of text. One version, called skip-gram, goes like this: take each word in turn and try to guess which words appear near it, say within two words either side. To keep it fast, the model doesn’t score every word in the vocabulary each time. It’s shown the real neighbour plus a few random words, and learns to tell them apart. That trick is called negative sampling.
Each round nudges the numbers a little, the same way training works everywhere: the word is pulled towards the words it really appears with and pushed away from the random ones. Words that keep the same company get pulled towards the same places.
Predict first
Below are 64 short sentences about animals, fruit, vehicles and colours. The model is never told those groups exist. After training, will “cat” end up near “dog”?
At the start, the words are scattered at random: cat’s nearest neighbours are yellow and bike. As training runs, the colours gather, and well before the 40 epochs are up (an epoch is one pass over all the sentences) every word sits nearest its own kind. Nothing told the model what an animal is. The groups come entirely from which words share sentences.
Now tick “Include every word in the corpus” and pick cat. Its nearest neighbours now include “hungry”, because in these sentences “hungry” only ever appears in animal company. The model has learned something about “hungry” too: it’s a word you say about animals.
Directions mean things#
Here’s the part that made word2vec famous. It isn’t only the positions that carry meaning, it’s the directions between them. In the 2013 papers, the arrow from “man” to “king” came out pointing roughly the same way as the arrow from “woman” to “queen”. So if you start at “king”, subtract “man” and add “woman”, you land near “queen”. The same trick turned “Paris − France + Italy” into “Rome”.
Predict first
In a real model, does king − man + woman land right on top of “queen”?
The dashed grey arrow is the relationship: from man to king. The yellow arrow is the same arrow, moved to start at woman. Where it ends is the answer to “man is to king as woman is to what?”, and the nearest word is queen. Try Paris − France + Italy: the arrow is now “capital of”, and it points a different way.
Then try king − man + Japan. The arithmetic happily answers “Rome”. The maths always returns some word; it has no idea whether your question made sense.
Embeddings today#
word2vec gives each word one vector, whatever sentence it’s in, so “bank” gets the same numbers in “river bank” and “bank account”. Modern language models fix that with contextual embeddings: a word’s vector is worked out from the words around it, which is exactly what attention does (our transformers explainer shows it happening).
The idea you’re most likely to use is a text embedding: one vector for a whole sentence or paragraph. Embed every document you have, embed the question, and return the documents whose vectors point most nearly the same way. That’s search by meaning, and it’s the retrieval step in RAG (see chunking for RAG). Text embeddings typically have a few hundred to a few thousand numbers each; the word2vec vectors Google released in 2013 have 300 numbers for each of 3 million words and phrases.
In code#
The gensim library trains the same kind of model in a few lines. Save the 64 sentences (open the list under the first figure) as corpus.txt, one per line:
from gensim.models import Word2Vec
sentences = [line.split() for line in open("corpus.txt")]
model = Word2Vec(sentences, vector_size=20, window=2, min_count=1,
sg=1, negative=5, epochs=200, seed=1, workers=1) # sg=1: skip-gram
print(model.wv.most_similar("cat", topn=3))
# [('rabbit', 0.99...), ('horse', 0.99...), ('all', 0.99...)]Notice “all” sneaking in: it only ever appears in “the cat sleeps all day” and the same sentence for the other animals, so it keeps animal company too. With 64 sentences, that’s as much as the model can know. Trained on billions of words, the same code learns far subtler company. For ready-made vectors, gensim can download Google’s (about 1.6 GB) with gensim.downloader.load("word2vec-google-news-300").
What to remember
- An embedding turns a word into a list of numbers, a point on a map of meaning, and cosine similarity compares the directions two words point.
- word2vec learns the numbers from plain text by pulling each word towards the words it appears with, so words that keep the same company end up close together.
- Directions between words can carry meaning (king − man + woman ≈ queen), but only approximately; modern models build contextual and whole-text embeddings on the same idea.