Vibe Engines
YouTube

Vibe Engines is free, interactive AI engineering & system design — runs in your browser. Pick a learning path

LABS · 05  /  EMBEDDINGS

The Meaning Map.

Turn every word into a point in space, arranged so that closeness means similar meaning. Click a word to find its neighbours, then do the impossible-sounding math: king − man + woman lands right on top of queen.

THE GIST · 20 SECONDS

An embedding is a word as a vector. Trained on context, words used alike end up pointing the same way. Similarity is the cosine of the angle between two vectors — 1 = same direction, 0 = unrelated. Because concepts become consistent directions, you can add and subtract meaning: king − man + woman ≈ queen. Geometry becomes semantics.

  • Embeddinga word as a vector
  • Cosineangle = similarity
  • Neighbourclosest by cosine
  • Analogyadd & subtract meaning

Click any word to see its nearest neighbours — or hit an analogy button on the right and watch the arithmetic land.

UNDER THE HOOD

What you just played, written down

Meaning becomes direction. Once every word is a vector, similarity is an angle and analogies are arithmetic — the two ideas that power semantic search and RAG.

How embeddings work — four ideas

  1. A word is a vector. Each word maps to a list of numbers, learned so words in similar contexts get similar vectors.
  2. Similarity is cosine. Compare two words by the angle between their vectors, not their distance — direction carries the meaning.
  3. Neighbours are meaning. The nearest vectors to a word are its closest relatives: cat → kitten, dog; tokyo → japan.
  4. Analogies are arithmetic. Concepts become consistent directions, so king − man + woman shifts along the gender axis and lands on queen.
WHY COSINE, NOT DISTANCE?

A word's vector can be long or short for reasons unrelated to meaning (frequency, magnitude). Cosine ignores length and compares only direction, so "cat" and "kitten" score high even if their raw magnitudes differ.

The whole thing in code

import numpy as np

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

def nearest(word, embeds, k=3):
    v = embeds[word]
    scored = [(w, cosine(v, u)) for w, u in embeds.items()
              if w != word]
    return sorted(scored, key=lambda t: -t[1])[:k]

def analogy(a, b, c, embeds):        # a - b + c
    target = embeds[a] - embeds[b] + embeds[c]
    scored = [(w, cosine(target, u)) for w, u in embeds.items()
              if w not in (a, b, c)]
    return max(scored, key=lambda t: t[1])   # → queen
COSINE−1 … 11 = identical direction
REAL DIMS100s–1000s2D here is a projection
THE 2D MAP IS A SHADOW

Real embeddings live in hundreds of dimensions. Tools like PCA or t-SNE flatten them to 2D so you can see the clusters — but the neighbours and analogies here are computed on the full vectors, not the flattened dots.

⚠ They inherit bias

Because embeddings learn from human text, they absorb its biases — analogies can surface stereotypes. Auditing and debiasing embeddings is an active area of fairness research.

↔ Static vs contextual

word2vec/GloVe give each word one fixed vector. Modern contextual embeddings (from Transformers) give a word a different vector per sentence, so "bank" differs by context.

★ Where it's used

Semantic search & RAG, recommendations, clustering, classification — and the very first layer of every Transformer, which embeds its input tokens.

STEP BY STEP

Word embeddings, step by step

How word2vec builds the space, the formula behind every similarity score, and this page's own vectors worked by hand: the numbers the map shows when you click.

How the space is learned, then searched

  1. Collect context pairs. Slide a window over the text (5 words on each side is a common default) and record every (word, neighbor) pair as a positive example.
  2. Add negatives. For each positive pair, draw k random words (k = 5 is typical), sampled in proportion to frequency0.75 so the most common words do not swamp the sample.
  3. Score with a dot product and train. Word2vec's skip-gram loss pushes σ(u·v) toward 1 for real pairs and toward 0 for the negatives. Words that share contexts get the same pushes, so their vectors end up pointing the same way.
  4. Search by cosine. Embed the query and rank stored vectors by cos(a, b). Once every vector has length 1, cosine is just the dot product, and ||a − b||² = 2 − 2·cos(a, b), so Euclidean distance gives the same ranking.
# skip-gram, negative sampling
loss = −log σ(u_c · v_w)
       − Σ_n log σ(−u_n · v_w)
# similarity of two vectors
cos(a, b) = a · b / (|a| · |b|)

Worked example: this page's vectors

  1. The axes. Each word here is a 0/1 vector over 11 readable dimensions: royal, male, female, animal, cat, dog, young, city, country, Europe, Asia. cat is animal + cat; kitten is animal + cat + young.
  2. cat vs kitten. Dot product 2, lengths √2 and √3, so cos = 2/√6 ≈ 0.82, cat's top neighbor.
  3. kitten vs puppy, cat vs dog. Sharing animal + young gives 2/3 ≈ 0.67; sharing only animal gives 1/2 = 0.50.
  4. king's neighbors. Click king and the nearest word is man (0.71), not queen (0.50). Each shares one axis with king, but man has no second axis to dilute the match.
  5. The analogies. king − man + woman = royal + female, which is exactly queen: cosine 1.00. paris − france + japan = city + Asia, exactly tokyo: also 1.00.
  6. Why the inputs are excluded. Against that same king − man + woman target, woman scores 0.71 and king 0.50. In real word2vec vectors an input word often scores highest, so analogy tests skip a, b and c, as the code above does.

⚠ Scores are relative

A cosine of 0.8 means different things in different models, and in many models even unrelated texts score well above 0. Rank by similarity, and calibrate any cut-off on labeled pairs from your own data. Vectors from two models are not comparable: switching models means re-embedding the corpus.

↔ Size and storage

One million vectors of 1,536 float32 values take 6.14 GB. int8 quantization cuts that to 1.54 GB and 1-bit codes to 192 MB, usually with a rescoring pass over the top hits. Some models, such as OpenAI's text-embedding-3 family, can be truncated to fewer dimensions.

★ In production

Normalize at write time and use the dot product. Embed queries and documents with the same model, including any query/passage prefixes it expects. Chunk long documents, since one vector averaged over many pages blurs every topic in it, and serve the search from an approximate nearest-neighbor index such as HNSW.

QUICK CHECK

Did it stick?

See every answer, with the reasoning
  1. In an embedding space, what does it mean for two words to be close?

    Answer: They have similar meaning / appear in similar contexts — Embeddings are trained so words used in similar contexts get similar vectors. Geometric closeness (high cosine similarity) therefore corresponds to semantic closeness, which is why cat sits near kitten.

  2. Why use cosine similarity instead of straight-line distance?

    Answer: It compares direction and ignores vector length, which carries no meaning — A vector’s magnitude can vary for reasons unrelated to meaning. Cosine measures only the angle (direction) between vectors, so similarity reflects meaning rather than length.

  3. Why does king − man + woman land on queen?

    Answer: Because the man→woman gender direction, added to king, shifts it to the female-royalty region — Concepts become consistent directions in embedding space. Subtracting man and adding woman applies a gender shift; applied to king, the nearest word to the result is queen.

FAQ

Embeddings, answered

What is a word embedding?

A word represented as a vector of numbers, learned so words used in similar contexts get similar vectors. Closeness in the space means closeness in meaning.

What is cosine similarity?

The angle between two vectors — dot product over the product of magnitudes. It runs from 1 (same direction) through 0 (unrelated) to −1 (opposite), and ignores vector length.

How does king − man + woman ≈ queen work?

Concepts become consistent directions. The man→woman direction is a gender shift; adding it to king lands nearest to queen. The analogy is literal vector arithmetic.

Why show them in 2D?

Real embeddings have hundreds of dimensions. PCA/t-SNE project them to 2D so clusters are visible; the math here still uses the full vectors.

Where are embeddings used?

Semantic search and RAG, recommendations, clustering, classification, and as the first layer of every Transformer.

RESULT

—

Next → rank a whole document store by cosine to a query embedding and you've built the retrieval half of RAG.

Finished this one? 0 / 61 Labs done
NextThe Skip-List of Space: HNSW Next on the “Structure, and making new things” ladder · rung 4 of 6

Explore the topic

See this alongside everything else on the same subject — handbooks, system designs, challenges and tools, in one place.

More Labs