ai/courses

AI Fundamentals/Lesson 4 of 8

What Are Embeddings? Meaning as Numbers, Explained

How a list of numbers can capture meaning, and why king − man + woman ≈ queen.

Lesson
4 of 8
Time
25 min
Updated

TL;DR

The short answer

An embedding is a list of numbers that represents the meaning of something (a word, a sentence, a document, an image) so that things with similar meanings get similar numbers. Think of it as coordinates on a map of meaning, where "puppy" lands next to "dog" and far from "invoice."

Because meaning becomes geometry, a computer can compare meanings with simple math: measure the distance or angle between two lists. That one trick powers semantic search, recommendations, duplicate detection and the retrieval step of RAG, and every language model starts by turning its tokens into embeddings.

A token ID says nothing

In the last lesson, "strawberry" became token 101830. That number is just a position in the vocabulary list, like a seat number. Token 101830 is not "close" to token 101829 in any meaningful way, and nothing about the number says "fruit," "red" or "sweet."

A network needs a representation where meaning is built in, so that what it learns about one word can carry over to similar words. If it learns that "puppies are playful," it should guess that kittens might be too. That requires numbers that place "puppy" and "kitten" near each other.

The solution: give every token a list of numbers, say a few hundred or a few thousand of them, and let training adjust those numbers like any other weight. That list is the token's embedding. The word means "embedded in a space": each token becomes a point in a space with many dimensions.

A map of meaning

Real embeddings have hundreds or thousands of dimensions, which no one can picture. But the idea works the same in two dimensions, where you can see it. Play with this map:

DemoTap two words to measure how similar they are. Then run the word math examples and watch the arrows add up. An illustration in 2D; real embedding spaces work the same way with far more dimensions.

Two things happen in a good embedding space. Similar things cluster: animals near animals, foods near foods, cities near cities. And, more surprisingly, directions carry meaning. The step from "man" to "woman" points in roughly the same direction as the step from "king" to "queen." The step from "France" to "Paris" matches the step from "Japan" to "Tokyo": that direction means something like "capital of."

That's why you can do arithmetic with meaning. Take "king," subtract "man," add "woman," and the nearest word to where you land is "queen." When researchers at Google showed this with word2vec in 2013, it was a genuine surprise: nobody had told the model about royalty, gender or geography.

Fig. 1In an embedding space, related words cluster, and the same relationship (here, male to female) points the same way for different word pairs.

Measuring similarity

To use embeddings you need a way to compare two of them. The standard measure is cosine similarity, and it's friendlier than it sounds. Picture each embedding as an arrow from the center of the space to its point. Cosine similarity measures the angle between two arrows:

  • Close to 1: the arrows point the same way. Very similar meaning ("puppy" and "kitten").
  • Around 0: the arrows are at right angles. Unrelated ("puppy" and "tax return").
  • Negative: the arrows point in opposite directions. In practice, rare with modern text embeddings.

Why the angle and not the distance? Because the direction captures what something is about, while the length often reflects things like how common or how long the text is. Two documents about the same topic, one short and one long, point the same way even if their arrows differ in length.

similarity.py
import numpy as np

def cosine(a, b):
    return a @ b / (np.linalg.norm(a) * np.linalg.norm(b))

# Toy embeddings with 3 numbers: [animal, young, food]
words = {
    "dog":    np.array([0.9, 0.1, 0.0]),
    "puppy":  np.array([0.9, 0.9, 0.0]),
    "kitten": np.array([0.8, 0.9, 0.1]),
    "pizza":  np.array([0.0, 0.1, 0.9]),
}
for a, b in [("dog", "puppy"), ("puppy", "kitten"), ("dog", "pizza")]:
    print(f"{a:>6} vs {b:<6} {cosine(words[a], words[b]):.2f}")
CodeCosine similarity with toy three-number embeddings. Output: dog vs puppy 0.78, puppy vs kitten 0.99, dog vs pizza 0.01.

With a real embedding model, you send text to an API and get the list back. OpenAI's text-embedding-3-small, for example, returns 1,536 numbers for any text up to about 8,000 tokens:

embed.py
from openai import OpenAI

client = OpenAI()   # reads OPENAI_API_KEY from the environment
resp = client.embeddings.create(
    model="text-embedding-3-small",
    input=["puppy", "kitten", "invoice"],
)
vectors = [item.embedding for item in resp.data]
print(len(vectors[0]))   # 1536 numbers per text
CodeGetting real embeddings from OpenAI’s API with the official Python SDK. Other providers and open-source models work the same way.

Where embeddings come from

In 1957 the linguist J. R. Firth wrote a line that became the motto of the whole approach: "You shall know a word by the company it keeps." Words that appear in similar contexts tend to have similar meanings. "I fed the ___ some kibble" could be dog, puppy or cat, never invoice.

word2vec turned that into a training task: given a word, predict the words around it (or the reverse). To get good at the task, the network has to give similar words similar embeddings, because they have similar neighbors. The embeddings are a by-product of learning to predict context, and they're the part everyone kept.

Two upgrades since then matter:

Context-aware embeddings. In word2vec, "bank" has one embedding whether it's a river bank or a savings bank. Inside a modern language model, a token's embedding is only the starting point. As it passes through the layers, attention mixes in information from the surrounding words, so by the middle of the network, "bank" in "we sat on the bank and fished" has moved far from "bank" in "the bank froze my card." Lesson 5 shows how.

Embeddings for whole texts and other media. Dedicated embedding models turn a whole sentence, paragraph or document into a single list, so you can compare documents by meaning. Models like OpenAI's CLIP (2021) put images and text into the same space, so the photo of a beach and the words "sunny beach" land near each other. That's how you can search your phone's photos by typing a description.

“You shall know a word by the company it keeps.”
J. R. Firth, A Synopsis of Linguistic Theory, 1957

What embeddings are used for

Most of what feels "smart" about search and recommendations today is a nearest-neighbor lookup in an embedding space. Turn everything into embeddings once, store them, and then any question becomes "which stored points are closest to this one?"

UseHow embeddings helpExample
Semantic searchFind documents that mean the same thing as the query, even with different words“How do I get my money back” finds the page titled “Refund policy”
RAGPick the passages to paste into a model’s promptA support bot answering from your help center
RecommendationsSuggest items whose embeddings are near what you liked“More like this” for articles, products, songs
DeduplicationSpot near-identical texts even when the wording differsMerging duplicate support tickets
ClusteringGroup many texts by topic without reading them allSorting 10,000 survey answers into themes

Storing millions of embeddings and finding the nearest ones quickly is its own engineering problem, solved by vector databases and vector indexes: dedicated databases, or extensions to ordinary ones such as pgvector for PostgreSQL. They use clever approximate search so you don't have to compare the query against every stored item. You'll meet them again in lesson 8, where they power RAG.

Exercise · about 5 minutes

Build an embedding by hand

Pick five movies, songs or books you know well. Invent three "dimensions" that describe them, each scored from 0 to 10. For movies, maybe energy, darkness and how much it makes you think.

  1. Score all five on your three dimensions. Each item is now a list of three numbers: an embedding.
  2. Find the two items whose numbers are most alike. Are they really the two most similar ones, in your opinion?
  3. Add a sixth item you haven't scored yet. Before scoring it, guess which of the five it will land closest to. Then score it and check.

Real embedding models do this with thousands of dimensions that nobody named, learned from billions of examples. But you just did the core of semantic search: represent things as numbers, then compare the numbers.

Quiz

  1. 1.What is an embedding?

  2. 2.In a good embedding space, what does king − man + woman land closest to?

  3. 3.Two texts have a cosine similarity of 0.95. What does that mean?

  4. 4.Which idea is behind learning word embeddings from text?

  5. 5.Why is a pure embedding search not enough to check whether a statement is true?

0 of 5 answered

Key takeaways

  • An embedding is a list of numbers that places meaning in space: similar things sit close together.

  • Directions mean something: man → woman points the same way as king → queen.

  • Cosine similarity compares embeddings by the angle between them: near 1 means very similar.

  • Embeddings are learned from context: you shall know a word by the company it keeps.

  • They power semantic search, RAG, recommendations and clustering, but similar is not the same as true.

Go deeper

AI Fundamentals: How Modern AI Actually Works

  1. 01How machines learn25 min
  2. 02Neural networks30 min
  3. 03Tokens20 min
  4. 04Embeddings25 min
  5. 05Attention and transformers30 min
  6. 06How LLMs are trained30 min
  7. 07How LLMs generate text25 min
  8. 08RAG, tools and agents30 min