AILearn AI
LearnGlossarySources
ID/EN
Learn AI — open material for learning AIEvery lesson cites its original sources.
▦Deep Learning Architectures
  1. Convolutional Neural Networks (CNNs)
  2. CNN Architectures and Transfer Learning
  3. Recurrent Networks: RNN, LSTM and GRU
  4. Embeddings: Meaning as Vectors
  5. Attention and Transformers
Modules
  1. ◎ AI Foundations
  2. ∿ Classical Machine Learning
  3. ⌬ Neural Networks
  4. ↘ Training Results & Evaluation
  5. ▦ Deep Learning Architectures
  6. ✎ Large Language Models
  7. ◐ Image Generation
  8. ♪ Audio & Speech AI
  9. ◈ Multimodal, Video & 3D
  10. ↻ Reinforcement Learning
  11. ⚙ ML Development & MLOps
  12. ★ Advanced & Frontier Topics
Learn/Deep Learning Architectures

Embeddings: Meaning as Vectors

How neural networks turn words, tokens, products or images into dense vectors where distance means similarity. One-hot vs embeddings, word2vec, cosine similarity, vector analogies, and contextual embeddings.

Intermediate~25 min·6 references
Key terms
Embeddingword2vecOne-hot encodingCosine similarityVectorToken

Neural networks only do arithmetic on numbers, so every discrete thing — a word, a Token, a user, a product, a movie — has to become a Vector. An Embedding is a learned, dense vector (typically 64–4096 numbers) chosen so that similar things end up close together. Embeddings are the first layer of every language model, the core of semantic search and RAG, and the engine of recommender systems.

≈
A map of meaning
Think of a city map. Restaurants cluster in the food district, banks in the financial district. You can describe any shop by two numbers (its coordinates), and nearby shops tend to be similar. An embedding is a map like that, but with hundreds of dimensions instead of two: “cat” lives near “dog”, “Jakarta” near “Bandung”. Even directions on the map carry meaning — the step from “man” to “woman” is roughly the same as from “king” to “queen”.

From one-hot to dense vectors

The naive encoding is one-hot: with a vocabulary of 50,000 words, each word is a 50,000-long vector with a single 1. It has two problems: it's huge and sparse, and every pair of words is equally different — the dot product of any two different one-hot vectors is 0, so “cat” is as far from “dog” as from “carburettor”. An embedding layer replaces this with a dense vector of, say, 300 numbers that the model learns.

E ∈ ℝ^(V × d) embed(i) = E[i] = onehot(i) · E
An embedding layer is just a lookup table: row i of a V × d matrix. Multiplying by a one-hot vector would select the same row, but a lookup is far cheaper. V = 50,000 and d = 300 → 15 million parameters.
In words: The embedding matrix has one row of d learned numbers for each of the V words. Embedding word number i just means taking row i — written mathematically as a one-hot vector times the matrix, which picks out exactly that row.
Symbols(hover a symbol in the formula)
E
the Embedding matrix (learned during training)
∈
“is an element of / has the type”
ℝ^(V × d)
the set of real-valued matrices with V rows and d columns
V
vocabulary size (number of distinct tokens), e.g. 50,000
d
embedding dimension, e.g. 300
embed(i)
the vector for token id i
E[i]
row i of E
onehot(i)
a length-V vector of zeros with a single 1 at position i (One-hot encoding)
▸Worked example
V = 4, d = 2, E = [0.1 0.3; 0.5 −0.2; 0.9 0.4; −0.7 0.8] Token id i = 2 (counting from 0): onehot(2) = [0, 0, 1, 0] onehot(2) · E = 0·[0.1, 0.3] + 0·[0.5, −0.2] + 1·[0.9, 0.4] + 0·[−0.7, 0.8] = [0.9, 0.4] = E[2] Real size: V = 50,000, d = 300 → 50,000 · 300 = 15,000,000 parameters.

Where does the meaning come from?

From the distributional hypothesis: “You shall know a word by the company it keeps” (J. R. Firth, 1957). Words that appear in similar contexts tend to have similar meanings — “coffee” and “tea” both appear near “cup”, “drink”, “hot”. If we train vectors to predict a word's context, words with similar contexts are pushed toward similar vectors. Embeddings can also be learned as a side effect of any task: the first layer of a sentiment classifier or a language model learns embeddings by backpropagation like any other weights.

word2vec

Mikolov et al. (2013) made this fast enough to train on billions of words[1]. word2vec has two variants: CBOW predicts a word from its surrounding words; skip-gram predicts the surrounding words from the centre word. Instead of a full softmax over the vocabulary, skip-gram with negative sampling turns it into a cheap binary task: tell real (word, context) pairs apart from k random “negative” pairs[2].

maximize log σ(u_oᵀ v_c) + Σ_{k=1..K} log σ(−u_kᵀ v_c)
v_c = vector of the centre word, u_o = context vector of a real neighbour, u_k = context vectors of K random words. Real pairs get pulled together, random pairs pushed apart.
In words: Make the model confident that the real neighbour is real (first term) and that each random word is fake (second term). Each σ is a probability between 0 and 1, so each log is ≤ 0; the best possible value is 0.
Symbols(hover a symbol in the formula)
maximize
training adjusts the vectors to make this sum as large as possible (equivalently, minimize its negative)
log
natural logarithm; log of a probability near 1 is near 0, near 0 it goes to −∞
σ
Sigmoid (logistic function): turns a score into a probability
v_c
input vector of the centre word (a row of W)
u_oᵀ v_c
Dot product of the real context word's output vector u_o with v_c (ᵀ = transpose, i.e. row × column)
Σ_{k=1..K}
sum over the K negative (noise) samples
−u_kᵀ v_c
minus the score of noise word k: σ of it is the probability that the pair is fake
▸Worked example
d = 2, K = 1: v_c = [1, 0.5], u_o = [0.8, 0.6], u_1 = [−0.5, 0.2] Real pair: u_oᵀv_c = 0.8 + 0.3 = 1.1 σ(1.1) = 0.7503 log = −0.2873 Noise pair: u_1ᵀv_c = −0.5 + 0.1 = −0.4 σ(0.4) = 0.5987 log = −0.5130 Objective = −0.2873 − 0.5130 = −0.8004 → gradient ascent pushes it toward 0 by moving v_c closer to u_o and away from u_1.
Loading interactive…
One skip-gram training example with negative sampling. Walk through it and match each part to the formula above: the top row is the log σ(u_oᵀ v_c) term, the bottom row the K noise terms. Notice that the network is just two lookup tables and a dot product — the “embedding” is simply a row of W.

GloVe (Pennington et al., 2014) reaches similar vectors by factorizing global word co-occurrence counts[3], and fastText adds sub-word pieces so it can build vectors for unseen or misspelled words (Bojanowski et al., 2016) — useful for morphologically rich languages like Indonesian (makan, makanan, dimakan, memakan).

Measuring similarity and vector arithmetic

cos(a, b) = (a · b) / (‖a‖ · ‖b‖) ∈ [−1, 1]
Cosine similarity compares directions and ignores length: 1 = same direction, 0 = unrelated (orthogonal), −1 = opposite.
In words: Cosine similarity measures the angle between two vectors and ignores their lengths: 1 = pointing the same way, 0 = unrelated (perpendicular), −1 = opposite. Dividing the dot product by both lengths is what removes the length.
Symbols(hover a symbol in the formula)
cos(a, b)
Cosine similarity of vectors a and b (the cosine of the angle between them)
a · b
Dot product: multiply matching entries and add them up
‖a‖
length (Euclidean norm) of a: √(a₁² + a₂² + …)
‖b‖
length of b
∈ [−1, 1]
the result always lies between −1 and 1
▸Worked example
a = [1, 2], b = [2, 3] a · b = 1·2 + 2·3 = 8 ‖a‖ = √(1 + 4) = 2.2361 ‖b‖ = √(4 + 9) = 3.6056 cos = 8 / (2.2361 · 3.6056) = 8 / 8.0623 = 0.9923 → almost the same direction Doubling b to [4, 6] gives the same 0.9923: length does not matter.

Cosine similarity is the standard way to compare embeddings (if vectors are normalized to length 1, it equals the Dot product). word2vec vectors famously encode relations as directions: vector(“king”) − vector(“man”) + vector(“woman”) is closest to vector(“queen”); similar offsets appear for country → capital and verb tenses[1]. Caveats: the analogy search usually excludes the input words, and many analogies work far less cleanly than the famous examples suggest. Jay Alammar's illustrated guide walks through all of this visually[4].

Loading interactive…
A rotatable 3D map of ~40 words. Coordinates are hand-crafted for illustration (real embeddings have hundreds of dimensions).
  1. Clusters: drag to rotate and find the groups — animals, fruits, countries/capitals, royalty/gender, verbs. Which clusters sit close to each other, and why might that be?
  2. Nearest neighbours: click a word (e.g. an animal). The neighbour list is sorted by cosine similarity — check that the top ones are from the same cluster.
  3. Analogy: in the analogy panel compute king − man + woman. Watch the arrows: the “man → woman” offset is added to “king”, and the nearest word is highlighted.
  4. Country → capital: try a capital − its country + another country. Does the offset carry over? Try one where it fails, and think about why real embeddings are less tidy.
  5. Projection caveat: rotate until two clusters seem to overlap. In 3D they are separate — and real 300-D embeddings squeezed into 2D/3D (PCA, t-SNE) suffer the same distortions.

Static vs contextual embeddings

Static (word2vec, GloVe)Contextual (BERT, GPT hidden states)
One vector per…word type (“bank” always the same)token occurrence (“river bank” ≠ “bank loan”)
Produced byA lookup tableA deep network reading the whole sentence
Typical useLightweight NLP, features, teachingModern NLP, semantic search, RAG (sentence embeddings)

Modern models still start with a static lookup table (token embeddings), but every Transformer layer mixes in context, so the hidden states are contextual. Sentence/document embeddings (e.g. from Sentence-Transformers models) pool these into one vector per text — the basis of semantic search and retrieval-augmented generation. The same idea works for any modality: CLIP (CLIP) embeds images and captions into a shared space.

knobEmbedding dimension d
What it is
Length of each embedding vector.
↑ If you increase it
Can encode more fine-grained distinctions; parameters grow linearly (V × d) and so do storage and search cost in a vector database. With little data, extra dimensions are noisy and gains saturate.
↓ If you decrease it
Smaller and faster, but unrelated items get squeezed together and similarity becomes less precise.
Typical values
word2vec: 100–300. Sentence embedding models: 384–1024. LLM token embeddings: 768–8192+.
knobContext window (word2vec)
What it is
How many words on each side of the centre word count as its context.
↑ If you increase it
Captures broader, more topical similarity (“doctor” near “hospital”).
↓ If you decrease it
Captures tighter, more syntactic/functional similarity (“doctor” near “nurse”, “surgeon”).
Typical values
2–10; gensim default 5.
knobNegative samples K
What it is
How many random “wrong” context words are contrasted with each real one.
↑ If you increase it
Better vectors on small corpora, but slower training.
↓ If you decrease it
Faster; on very large corpora a few negatives are enough.
Typical values
5–20 for small datasets, 2–5 for large ones (Mikolov et al.).
python
from gensim.models import Word2Vec
import torch
import torch.nn as nn

# 1) Train word2vec (skip-gram + negative sampling) on tokenized sentences
sentences = [["the", "king", "rules", "the", "land"], ["the", "queen", "rules", "too"]]  # use a real corpus!
w2v = Word2Vec(sentences, vector_size=100, window=5, min_count=1, sg=1, negative=5, epochs=20)
print(w2v.wv.most_similar("king", topn=3))
print(w2v.wv.most_similar(positive=["king", "woman"], negative=["man"], topn=1))  # needs a big corpus

# 2) A learned embedding layer inside a PyTorch model
emb = nn.Embedding(num_embeddings=50_000, embedding_dim=300)
ids = torch.tensor([[12, 512, 7]])                # (batch, seq_len) of token ids
vectors = emb(ids)                                # (1, 3, 300)
sim = nn.functional.cosine_similarity(vectors[0, 0], vectors[0, 1], dim=0)
word2vec with gensim (the analogy line only gives meaningful answers with a large corpus), and PyTorch's nn.Embedding lookup table[6].
!
Common pitfalls
Watch out for these:
  • Embeddings inherit biases from their training text: Bolukbasi et al. found analogies like “man : computer programmer :: woman : homemaker” in word2vec trained on news[5]. Audit before using them in decisions about people.
  • Mixing models: vectors from two different embedding models live in different spaces — never compare them directly.
  • Out-of-vocabulary words get no vector in word2vec/GloVe; use subword models (fastText, BPE-based models).
  • Cosine vs dot product: if vectors aren't normalized, dot product favours long vectors (often frequent words). Use the metric the model was trained with.
  • Trusting 2D plots: t-SNE/UMAP projections distort distances; check claims in the original space.
▸Go deeper: why embedding gradients are sparse, and what word2vec really learns

In one training step only the rows of E for tokens in the batch receive gradient — the rest are untouched. That's why embedding tables can be enormous (recommendation systems use billions of rows) and why nn.Embedding(sparse=True) with a sparse optimizer exists. Theoretically, Levy & Goldberg (2014) showed skip-gram with negative sampling implicitly factorizes a shifted pointwise mutual information (PMI) matrix of word–context counts — linking word2vec to older count-based methods and to GloVe[3].

Quiz

1.
Why is one-hot encoding a poor representation of word meaning?
2.
What does an nn.Embedding(50000, 256) layer contain?
3.
You increase word2vec's window size from 2 to 10. What changes in the nearest neighbours of “doctor”?
4.
Why do contextual embeddings (e.g. from BERT) handle “bank” better than word2vec?
5.
Two vectors point in exactly opposite directions. What is their cosine similarity?
Score: 0/5

References

  1. [1]
    Efficient Estimation of Word Representations in Vector Space
    PaperMikolov, Chen, Corrado & Dean2013arxiv.org
  2. [2]
    Distributed Representations of Words and Phrases and their Compositionality
    PaperMikolov et al.2013arxiv.org
  3. [3]
    GloVe: Global Vectors for Word Representation
    PaperPennington, Socher & Manning2014aclanthology.org
  4. [4]
    The Illustrated Word2vec
    ArticleAlammar2019jalammar.github.io
  5. [5]
    Man is to Computer Programmer as Woman is to Homemaker? Debiasing Word Embeddings
    PaperBolukbasi et al.2016arxiv.org
  6. [6]
    torch.nn.Embedding
    DocsPyTorchdocs.pytorch.org
← Previous
Recurrent Networks: RNN, LSTM and GRU
Next →
Attention and Transformers