Word embeddings: word2vec and doc2vec
Practical and exam-focused notes on word embeddings: word2vec (skip-gram, CBOW, negative sampling, hierarchical softmax) and doc2vec (PV-DM, PV-DBOW), with definitions, derivations, formulas, worked examples and a short Python demo of softmax / negative-sampling computations.
Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.
Why it matters
Word embeddings convert words (discrete symbols) into dense real-valued vectors so that semantic and syntactic relationships are captured as geometric relations. Engineers use embeddings in many NLP systems — e.g., as input features to classifiers, sequence models, information retrieval, clustering, and historically to initialise embedding layers in non-contextual or shallow models; large contextual models like BERT are pretrained end-to-end and do not use word2vec initialisation (see Contextual embeddings and BERT).
Key ideas
- Word embedding (defined): a function that maps each vocabulary word to a low-dimensional real vector (embedding). We denote embedding dimension by d.
- One-hot vector (defined): a binary vector of length V (vocabulary size) with exactly one 1 at the index of the word and 0 elsewhere. One-hot vectors are sparse and high-dimensional; embeddings are dense, low-dimensional alternatives.
Two classic architectures for learning embeddings (word2vec family):
- Skip-gram (defined): for each centre word w_c, predict its context words w_o within a chosen window. Training maximises probability of context given centre.
- CBOW (continuous bag-of-words) (defined): predict the centre word from the surrounding context (a bag, order ignored).
Probabilistic core and loss:
- Use a softmax (defined) over the vocabulary to convert scores to probabilities. The training loss is the negative log-likelihood (equivalently cross-entropy loss defined) of observed context words.
Computation problems and solutions:
- Softmax normalisation costs O(V) per example (V is vocabulary size). For large V this is prohibitive.
- Two scalable alternatives: hierarchical softmax (defined) — arranges words in a binary tree and reduces cost to O(log V); and negative sampling (defined) — converts the multiclass problem into several binary logistic regression problems using sampled negatives.
- Training tricks that improve word2vec quality/efficiency: subsampling frequent words (discard token w with probability 1 - sqrt(t/f(w)), t≈1e-5 where f(w) is relative frequency) and using a dynamic context window (sample window size uniformly from 1..W for each centre word).
Mathematical relationship:
- Skip-gram + softmax model parameters are two sets of embeddings: input (centre) embeddings and output (context) embeddings. The score for pair (w_c, w_o) is the dot product of their vectors.
- For skip-gram with negative sampling (SGNS), under standard assumptions it implicitly factorises a shifted PMI matrix: u_w·v_c ≈ PMI(w,c) − log K (Levy & Goldberg, 2014).
Doc vectors (doc2vec):
- PV-DM (Paragraph Vector Distributed Memory) (defined): the document id has a vector that is concatenated/averaged with word-context vectors to predict a target word (like CBOW but with a document vector).
- PV-DBOW (Paragraph Vector Distributed Bag of Words) (defined): the document vector is used to predict words sampled from the document; word vectors need not be learned or used in the prediction step; training updates document vectors similar to skip-gram.
- Inference for a new document: keep word vectors fixed, randomly initialise the doc vector and optimise it (e.g., SGD) to maximise the same objective — this finds a vector that fits into the trained word-space.
Exact derivations universities commonly ask for (step-by-step): gradient of softmax + cross-entropy for one training pair (centre -> context).
- Let scores s_i for i in {1..V} be s_i = u_i · v_c where u_i is output vector for word i, v_c is input (centre) vector.
- Softmax probability p_i = exp(s_i) / Σ_j exp(s_j).
- Cross-entropy loss for true index o: L = -log p_o.
- Compute ∂L/∂s_k. Using standard derivative of softmax + log: ∂L/∂s_k = p_k - 1_{k=o} (i.e. p_k minus 1 if k is true class, else p_k).
- Therefore, gradients on vectors: ∂L/∂v_c = Σ_k (p_k - 1_{k=o}) u_k, and ∂L/∂u_k = (p_k - 1_{k=o}) v_c.
Explain computational cost: computing all p_k requires all s_k = u_k · v_c, O(V·d), and normalisation O(V). This is why negative sampling/hierarchical softmax are used.
Negative sampling derivation (short):
- Replace multiclass softmax with objective: for a positive pair (c,o) maximise log σ(u_o·v_c) + Σ_{k=1..K} E_{w_k~P_n}[log σ(-u_{w_k}·v_c)], where σ is sigmoid and P_n a noise distribution. This equals training a binary logistic classifier that discriminates true context pairs from noise samples. Gradients are cheap: they involve only the vectors of the positive and K negatives.
Draw diagrams to show (describe exactly what to draw):
- For skip-gram: draw a centre word in middle labelled w_c, arrows to context words w_{c-1}, w_{c+1}, etc. Beside each word draw its input vector v_w (left) and output vector u_w (right). Label dot product u_o·v_c feeding into softmax.
- For hierarchical softmax: draw a binary tree whose leaves are words; label internal nodes with binary classifiers; path from root to a leaf encodes the probability of that word.
Hyperparameter defaults (tune per corpus): negatives per positive K≈5–20; noise distribution P_n(w) ∝ U(w)^{0.75} (unigram counts to the 3/4 power); window size W≈2–10; subsampling threshold t≈1e-5 to 1e-3.
Formulas
p_i = exp(s_i) / Σ_j exp(s_j) — p_i: softmax probability of class i; s_i: score for i (no unit); applies when converting scores to probabilities over V classes.
L = - log p_o — cross-entropy loss for true class o; p_o: probability assigned to true class.
∂L/∂s_k = p_k - 1_{k=o} — derivative of loss wrt score s_k; 1_{k=o} is 1 if k==o else 0.
s_i = u_i · v_c — score is dot product of output vector u_i and centre input vector v_c; dot product is sum over d dimensions.
Negative-sampling objective: J = - [ log σ(u_o·v_c) + Σ_{i=1..K} log σ(-u_{n_i}·v_c) ] — loss form to minimise; σ(x)=1/(1+exp(-x)).
∂J/∂v_c = (σ(u_o·v_c)-1) u_o + Σ_{i=1..K} σ(u_{n_i}·v_c) u_{n_i} — gradient w.r.t centre vector.
∂J/∂u_o = (σ(u_o·v_c)-1) v_c; ∂J/∂u_{n_i} = σ(u_{n_i}·v_c) v_c — gradients w.r.t output vectors.
cosine(u,v) = (u · v) / (||u|| · ||v||) — cosine similarity between vectors; dimensionless.
Units: embeddings are dimensionless real numbers (no physical SI units). Use these formulas when training or analysing word2vec/doc2vec.
Worked examples
Example 1 — model-answer derivation (theory question): Question: "Derive ∂L/∂v_c for skip-gram with softmax and cross-entropy." Model answer (short, exam-style):
- Scores s_k = u_k·v_c. Softmax p_k = exp(s_k)/Σ_j exp(s_j). Loss L = -log p_o.
- Using chain rule, ∂L/∂s_k = p_k - 1_{k=o}.
- ∂s_k/∂v_c = u_k. Therefore ∂L/∂v_c = Σ_k (p_k - 1_{k=o}) u_k. QED.
Example 2 — small deterministic Python program: compute softmax probabilities, cross-entropy loss and negative-sampling loss for fixed numbers; prints gradients. This demonstrates the numeric values used in theoretical updates.
Program (Python 3; needs only numpy):
import numpy as np
np.set_printoptions(precision=6, suppress=True)
# deterministic
scores = np.array([2.0, 1.0, 0.1])
true_index = 0
exp_scores = np.exp(scores - np.max(scores)) # numeric stability
probs = exp_scores / np.sum(exp_scores)
loss_ce = -np.log(probs[true_index])
grad_scores = probs.copy()
grad_scores[true_index] -= 1.0
# Negative sampling example
s_pos = 1.5
s_negs = np.array([-0.5, 0.2])
def sigmoid(x):
return 1.0 / (1.0 + np.exp(-x))
loss_ns = - (np.log(sigmoid(s_pos)) + np.sum(np.log(sigmoid(-s_negs))))
# gradients wrt scores: pos -> sigmoid(s_pos)-1 ; each neg -> sigmoid(s_neg)
grad_pos = sigmoid(s_pos) - 1.0
grad_negs = sigmoid(s_negs)
print('Softmax probs =', probs)
print('Cross-entropy loss =', round(loss_ce,6))
print('Gradient wrt scores =', grad_scores)
print('--- Negative sampling ---')
print('Loss (neg-sample) =', round(loss_ns,6))
print('grad_pos =', round(grad_pos,6), 'grad_negs =', np.round(grad_negs,6))
Sample input: (program has no runtime input) Sample output (exact): Softmax probs = [0.659001 0.242433 0.098566] Cross-entropy loss = 0.417029 Gradient wrt scores = [-0.340999 0.242433 0.098566] --- Negative sampling --- Loss (neg-sample) = 1.473629 grad_pos = -0.182426 grad_negs = [0.377541 0.549834]
I checked the loss and gradients by hand: they follow formulas in the Formulas section.
Example 3 — model-answer exam-style question about doc2vec inference: Question: "Explain how to infer a vector for a new (unseen) document using trained PV-DM/PV-DBOW model." Model answer:
- Keep all word vectors (and softmax/output weights) fixed from training.
- Initialise document vector d randomly (or zeros) of same dimension as trained doc vectors.
- Run several steps of SGD (or Adam) to minimise the same objective used in training (e.g., in PV-DBOW minimise negative log probability of words sampled from doc using sigmoid or softmax). Update only d; word vectors are fixed.
- After convergence, d is the inferred vector of the new document; use cosine similarity to compare to other doc vectors.
Common mistakes
- Forgetting to subtract 1 from the true class in softmax gradient (i.e., ∂L/∂s_k = p_k - 1_{k=o}).
- Using too few negatives K for a large vocabulary (K should grow with corpus size; common heuristic: K=5..20 depending on corpus).
- Not using numeric-stability tricks for softmax (subtract max score before exponentiation).
For your exam
Kinds of questions:
- Definitions: "Define skip-gram, CBOW, negative sampling, hierarchical softmax, doc2vec PV-DM and PV-DBOW."
- Short notes: explain advantages of negative sampling vs hierarchical softmax.
- Derivations: gradient of softmax + cross-entropy; gradient of negative-sampling loss.
- Numericals/programs: compute softmax probabilities, loss and gradients for given scores (like Example 2), or write a small SGD update for embeddings.
- Diagrams: draw skip-gram diagram with input/output vectors and show flow to softmax; draw hierarchical binary tree with path labelled by bits.
What a full-marks answer includes:
- Precise definitions with bolded term names, assumptions (vocabulary size V, embedding dim d, window size), clear notation.
- Step-by-step derivation with chain rule and final compact gradient formulas (showing the p_k - 1_{k=o} result).
- Correct complexity analysis O(V) and explanation of why negative sampling reduces cost to O(K).
- For doc2vec questions: explanation of inference for unseen doc, and difference between PV-DM and PV-DBOW.
Quick check
- What is the derivative ∂L/∂s_k for cross-entropy with softmax when true class is o?
- Name two techniques to avoid O(V) cost of full softmax.
- In doc2vec PV-DBOW, what is directly predicted during training: words from doc, or context words around a position?
Answers: 1) p_k - 1_{k=o}. 2) hierarchical softmax and negative sampling. 3) Words from the document (the doc vector predicts words sampled from the doc).
Finished this topic? Mark it so your progress, study plan and readiness keep up.
Stuck on something here?