Static Word Embeddings: word2vec and After
Count-based vectors are long and sparse; embeddings are the short, dense alternative. This lesson builds them with word2vec's skip-gram and negative sampling — a classifier whose learned weights are the vectors — derives its gradient, and works one update by hand.
╌╌╌╌
This builds on Vector Semantics and Embeddings, which represented each word as a long, sparse vector of context counts, weighted by tf-idf or PPMI. Those vectors work, but they carry one dimension per vocabulary word and are almost all zeros. Here we compress them: instead of counting the contexts a word appears in, we train a small classifier to predict them, and keep the weights it learns as the word's dense vector. Same distributional idea, a far smaller and more useful representation.
Dense embeddings and word2vec
The vectors so far are sparse and long: dimension , mostly zeros. The alternative is a dense vector — short (50 to 1000 dimensions), with real-valued entries that can be negative and no per-dimension interpretation. These are embeddings.1 Dense vectors work better on essentially every NLP task. A classifier over 300 dense dimensions has far fewer weights to fit than one over 50,000 sparse dimensions, so it generalizes better; and a dense space can capture synonymy that a sparse one misses, where car and automobile occupy distinct, unrelated dimensions.1
Word2vec is the method that made dense embeddings routine.1 Rather than computing anything about counts directly, it trains a binary classifier on a pretext task — is context word likely to occur near target word ? — then discards the predictions and keeps the learned weights as the embeddings. Because the training data is just running text (a word and its actual neighbors are positive examples, needing no human labels), this is self-supervision — the same idea that later scales up to language-model pretraining.
Skip-gram with negative sampling
The specific algorithm is skip-gram with negative sampling (SGNS). Take a target word and a window of words around it as its context. Each (target, true-context) pair is a positive example. To teach the classifier what non-neighbors look like, we manufacture negative examples: for each positive pair, sample noise words at random from the vocabulary, each paired with the same target.2
The classifier decides by embedding similarity. It keeps two vectors per word — a target embedding and a context embedding — and models the probability that is a real context of as the sigmoid of their dot product:2
The dot product is a raw similarity; the sigmoid squashes it into a probability. For one positive pair with noise words , the loss is minimized when the positive pair looks like neighbors and every noise pair looks like non-neighbors,
Minimizing this by stochastic gradient descent pulls toward the context embeddings of words it truly occurs with and pushes it away from the noise words. The noise words themselves are drawn not from the plain unigram distribution but from the weighted — the same that tamed PPMI, here giving rare words a slightly higher chance of being sampled as noise.2 The full procedure:
- 1input: corpus, window , negatives per positive , dimension
- 2initialize randomly for each word
- 3for each target word in the corpus do
- 4for each context word within of do
- 5sample noise words
- 6
- 7
- 8for each noise word do
- 9
- 10
- 11return for each word
The learner stores two matrices, the target matrix and the context matrix , each holding one -dimensional vector per vocabulary word. When training ends, the embedding of word is usually taken as (or just , discarding ).2 The predictions are never used; the weights are the embeddings.
The gradient, derived
The three update lines above come from differentiating the loss. Write for the model's current probability that the true pair is a neighbor. Since and , differentiating by the chain rule gives2
Read the signs. For the positive pair, is negative (the probability is below ), so adds a multiple of to : the two vectors move toward each other, raising their future dot product. For a noise pair, pushes away from . Attraction to real neighbors, repulsion from noise — exactly the two goals the loss encodes.
Worked example: one SGNS update step
Take target apricot with two-dimensional embeddings, one positive context jam and one noise word tolstoy, learning rate :
Dot products. , and .
Sigmoids. and . The model currently gives jam a neighbor probability of only (it should be near ) and tolstoy a probability of (it should be near ). Both errors produce useful gradients.
Updates. For the positive context, , so
For the noise word, , so
And the target embedding, which receives both updates at once,
Check the effect on the dot products that matter. The new , up from — apricot and jam grew more similar. The new , down from — apricot and tolstoy grew less similar. One step of the pretext task moved the geometry exactly as intended; a corpus of billions of such steps produces the final space.
The analogy parallelogram
Embeddings trained this way turn out to encode relations, not just similarities, in their geometry. The parallelogram model of analogy, proposed for cognition long before word2vec, solves a is to b as is to what? by vector arithmetic: compute the offset that carries to , add it to , and return the nearest word.3
On real word2vec and GloVe spaces this produces the famous result: the expression lands near , and lands near .3 The embedding space has learned consistent directions for relations like MALE–FEMALE and CAPITAL-CITY-OF, recovered from raw co-occurrence with no relational supervision.
Two axes show the structure of the king analogy. Project the vectors onto a gender direction (male to female) and a royalty direction (commoner to royal), and the four words fall at the corners of a rectangle: man and woman sit low on royalty, king and queen high, with man/king on the male side and woman/queen on the female side. The offset is a step along the gender axis; adding it to king slides along that same axis and lands on queen. That is exactly , and it works because the space assigned the MALE-FEMALE relation one consistent direction shared by both the royal and the common pair — the two horizontal edges of the parallelogram are parallel and equal.
Formally, for the problem the parallelogram answer is
The geometry is real but fragile. The nearest vector is often one of the three input words (so those are excluded by hand), and the method works cleanly only for frequent words and a few relation types, like capitals and inflections; for many relations it fails, and it is too simple to model human analogy in general.3
The embedding papers and what came after
Jurafsky & Martin present skip-gram with negative sampling as a method; the primary sources fix the details. Four public papers frame the static-embedding era, and one theorem ties them together.
word2vec (Mikolov et al., 2013).4 The original paper introduced two architectures, not one: the CBOW model predicts a target word from the average of its surrounding context embeddings, and the skip-gram model predicts each context word from the target — the direction this lesson develops. A companion paper the same year added the negative-sampling objective and the -power noise distribution used here, and reported the analogy result that made the method famous: on a test set of a : b :: c : d relations, the vector recovered for roughly of syntactic and semantic analogies, far above prior methods. The change that made it fast at billion-word scale was the shift from a full softmax over to the -negative-sample sigmoid loss, cutting the per-step cost from to .
GloVe (Pennington, Socher, and Manning, 2014).5 Where word2vec learns from local windows one at a time, GloVe fits vectors to the global co-occurrence counts directly. Its objective is a weighted least-squares regression on log-counts, , where is the number of times word appears in the context of word and is a weighting that damps very frequent pairs. The design goal was to make ratios of co-occurrence probabilities linear in the embedding space, so that analogy directions fall out by construction. On the standard analogy benchmark GloVe matched or beat skip-gram at comparable cost.
The equivalence (Levy and Goldberg, 2014).6 The count-based and prediction-based traditions turned out to be the same object viewed twice. Levy and Goldberg proved that skip-gram with negative sampling, at its optimum, factorizes a word-context matrix whose entries are the shifted PPMI, , where is the number of negative samples. The neural pretext task and the explicit PPMI matrix of this lesson are, up to the shift, computing the same association scores — one by SGD, one by counting. This retroactively explained why the correction helps both, and why simple count models tuned carefully can match word2vec.
fastText (Bojanowski et al., 2017).7 Static word2vec assigns nothing to a word it never saw in training — an out-of-vocabulary word has no vector. fastText fixes this by embedding character n-grams and summing them, so the vector for apricots is built from the sub-pieces of apricot plus a plural suffix. Morphologically rich languages, where a stem appears in dozens of inflected forms, gained the most, and any unseen word can be assigned a vector from its spelling.
All four share the same limitation: one vector per word type, regardless of sentence. ELMo (Peters et al., 2018) removed it by reading each word through a bidirectional LSTM language model and using its internal states as the word's representation, so bank near river and bank near money receive different vectors.8 That is the contextual turn — the same distributional idea, but computed per occurrence rather than per type — and it is where the next lessons lead.
Bias and the road to contextual embeddings
Embeddings inherit whatever is in the text, and text carries human bias.9 The same arithmetic that yields king − man + woman ≈ queen also yields man − computer programmer + woman ≈ homemaker, and father : doctor :: mother : nurse. Worse, embeddings amplify bias: gendered associations come out stronger in the vector space than in the source statistics. When such embeddings feed a hiring or search system they can cause allocational harm, unfairly distributing real resources, and representational harm, demeaning social groups.9 Debiasing transformations reduce these effects but do not remove them — an open problem, and a reason to treat embeddings as artifacts of their training data, not neutral facts about language.
The deepest limitation is architectural. A static embedding assigns each word one vector, so bank (river) and bank (money) are forced to share a single compromise point, and every sense a word ever has is averaged into one location. Meaning, though, depends on context. The next step is a representation that gives a word a different vector in every sentence it appears in — a contextual embedding, computed on the fly by a neural language model and, at scale, by the transformer. Static vectors give each word type one fixed point; contextual vectors recompute the point for each sentence. The ideas built here — the move from word-as-atom to word-as-point, and the self-supervised dot-product-and-sigmoid learning — reappear throughout the deep-learning course.
Footnotes
- Jurafsky & Martin, §6.8 — Word2vec: short dense embeddings versus long sparse vectors, why dense vectors help generalization, and the self-supervised classifier-whose-weights-are-embeddings framing. ↩ ↩2 ↩3
- Jurafsky & Martin, §6.8.1–6.8.2 — The Classifier / Learning Skip-Gram Embeddings: sigmoid-of-dot-product probability, positive and negatively sampled context pairs, the cross-entropy objective (Eq. 6.34), the SGD updates (Eqs. 6.38–6.40), and the noise distribution. ↩ ↩2 ↩3 ↩4 ↩5
- Jurafsky & Martin, §6.10 — Semantic Properties of Embeddings: the parallelogram model of analogy, the result, and its caveats (input-word exclusion, restriction to frequent words and few relation types). ↩ ↩2 ↩3
- Mikolov, Chen, Corrado, and Dean (2013), Efficient Estimation of Word Representations in Vector Space, ICLR Workshop; and Mikolov, Sutskever, Chen, Corrado, and Dean (2013), Distributed Representations of Words and Phrases and their Compositionality, NeurIPS — the CBOW and skip-gram architectures, the negative-sampling objective, the -power noise distribution, and the analogy-completion results on word-vector arithmetic. ↩
- Pennington, Socher, and Manning (2014), GloVe: Global Vectors for Word Representation, EMNLP — a weighted least-squares model fitting embeddings to global log co-occurrence counts, designed so co-occurrence probability ratios are linear in the vector space. ↩
- Levy and Goldberg (2014), Neural Word Embedding as Implicit Matrix Factorization, NeurIPS — the proof that skip-gram with negative sampling implicitly factorizes a word-context matrix of shifted PMI values, . ↩
- Bojanowski, Grave, Joulin, and Mikolov (2017), Enriching Word Vectors with Subword Information, TACL — the fastText model, representing a word as the sum of its character-n-gram embeddings so that out-of-vocabulary and morphologically inflected words receive vectors. ↩
- Peters, Neumann, Iyyer, Gardner, Clark, Lee, and Zettlemoyer (2018), Deep Contextualized Word Representations, NAACL — ELMo, deriving a word's vector from the internal states of a bidirectional LSTM language model so that each occurrence of a word gets a context-dependent representation. ↩
- Jurafsky & Martin, §6.11 — Bias and Embeddings: gendered and stereotyped analogies reproduced and amplified by embeddings, allocational and representational harms, and the open problem of debiasing. ↩ ↩2
╌╌ END ╌╌