08 / 28 · Distributed Representations
Word2Vec
Derive CBOW, skip-gram and negative sampling, check repeated-row gradients, and run a reproducible expected-loss experiment on independently specified messages.
On this page 9
The library has many short equipment descriptions and few task labels. An embedding table initialized at random will not organize lamp, charge and inspect usefully by itself. The descriptions nevertheless contain a repeated prediction problem: given one word, predict a nearby word. Word2Vec uses that problem to train shared vectors without requiring a person to annotate each pair.
Baseline: fit the embeddings with a labelled task#
A supervised text classifier can learn its embedding table together with the classifier. Errors on a label flow backward into the word rows used in that message. This is useful when enough relevant labels exist, but the signal covers only distinctions rewarded by that task. Words absent from the labeled training set receive no direct evidence through its inputs.
Unlabeled text supplies a different signal. We can generate input–target pairs from positions in a sentence, keeping the original boundaries. This is self-supervised learning: the targets come from the data, while the choice of prediction task is still a design decision. The corpus has no promise that adjacent words are synonyms; they merely occurred in the selected context relation.
A network whose first layer is the table#
Use an input table and a separate output table , both with rows and columns. The input word selects ; a candidate context word selects . Their score is
There is no hidden nonlinear layer in this basic score. The two roles nevertheless need separate parameters: predicting a word as context and using it as an input are different contributions to the objective. A word’s final representation might use its input row or another explicitly chosen combination. Evaluations must state that choice.
The lookup explains the sharing. Every occurrence of lamp updates the same input row. Its interactions with several output words must fit in the same coordinates, so those interactions cannot all be adjusted independently when the dimension is small.
Two prediction tasks: CBOW and skip-gram#
Continuous bag of words, or CBOW, averages the input vectors of selected neighboring positions and predicts the center word. With context positions, its representation is
The average ignores their order unless extra position-dependent structure is introduced. A repeated neighbor contributes once per occurrence. The gradient through this mean is divided by for each occurrence, then accumulated if several positions use the same row.
Skip-gram uses the center word to predict each selected neighbor separately. A radius-one window around is in lamp is ready produces two targets, lamp and ready. Do not treat these as a single categorical event whose correct class must be unique: they are two training pairs. Sentence boundaries prevent an unrelated following message from becoming context.
Why both tasks give useful vectors#
The targets couple many words through shared parameters. In CBOW, contexts useful for predicting similar centers can develop compatible representations. In skip-gram, input words that need similar output scores can develop related rows. Finite-dimensional sharing creates this pressure; it does not prove that the resulting nearest neighbors match every human notion of similarity.
A larger context window changes the relation being learned and the number of pairs. A distance-weighted or randomly shortened window changes their effective weights. We use a fixed radius-one context in the executed case, so the counting rule is fully visible.
Why the softmax is the problem#
A categorical model normalizes over the vocabulary:
For a positive target , the derivative of the negative log probability with respect to score is the predicted probability minus the indicator that is the target. Every candidate appears in the denominator. A straightforward exact update therefore computes vocabulary-wide scores and changes all output rows, with cost proportional to per pair.
A tree-structured softmax offers a normalized alternative with a path of binary decisions. Negative sampling makes a different change: it replaces the categorical task with a binary discrimination objective. Its output scores are not automatically normalized next-word probabilities, so a language-model perplexity cannot be read directly from them.
Negative sampling#
For one observed pair , draw noise words from a chosen distribution . With sigmoid , minimize
Each term is binary logistic loss. The observed pair has label one; each sampled noise event has label zero. Noise events are not statements that a word can never co-occur with the input. The same pair can be observed in the corpus and also drawn from noise.
The gradient with respect to the input row is
Output-row gradients have the corresponding scalar error multiplied by . At most distinct output rows are involved; repeated sampled IDs reduce that number. Their gradient contributions must accumulate. All simultaneous-update gradients use the parameters from before the update, rather than mixing already updated output vectors into the input gradient.
Worked example#
Choose an input vector (0.5, -0.25) and three output rows. Row A is the positive; the supplied negative list is B, B, C.
| Row | Coordinates | Score |
|---|---|---|
| A | (0.2, 0.4) | 0 |
| B | (-0.3, 0.1) | -0.175 |
| C | (0.6, -0.2) | 0.35 |
These coordinates and noise events are chosen inputs, not pretrained vectors. The saved logistic loss is 2.795470. Because B occurs twice, its output gradient is twice its single-event contribution. The input gradient is approximately (-0.021846, -0.226051). A simultaneous step of size 0.1 produces input (0.502185, -0.227395) and reduces the loss to 2.746670, after updating the output rows as well.
The executable fixture checks every coordinate against centered finite differences. It also computes the exact three-class softmax on these same scores: approximately 0.306887, 0.257619 and 0.435494. Those three values sum to one. The individual sigmoid scores used by the binary objective do not have that constraint.
Which words are negatives#
The noise distribution affects both the frequency of updates and the optimum. A common Word2Vec choice uses unigram frequency raised to power 3/4:
This reduces frequency imbalance relative to sampling directly from counts while still giving common words more noise mass than rare ones. It is a method choice, not a universal law. The original paper specifies this distribution; the pinned C implementation constructs a table approximating it.
Our mathematical expectation below samples from the entire vocabulary, including possible collisions with the positive target. The original C code skips a noise draw equal to that target, so its precise event distribution differs. Keeping this distinction explicit prevents a small didactic optimizer from being mistaken for a reproduction of the production implementation.
Subsampling frequent words#
Frequent words also dominate positive pairs. Subsampling removes some occurrences before context pairs are formed, changing the observed training distribution. The 2013 paper proposes a discard probability based on a frequency threshold; its C implementation uses a related retention rule. These choices should not be interchanged silently when reproducing a run.
Removing positions can affect which remaining words become neighbors, depending on the implementation. Thus subsampling is more than lowering a learning rate for frequent rows. Our tiny fixture performs no subsampling or random window shortening, so all pair counts remain directly traceable to the specified messages.
What negative sampling optimizes#
Consider one input–output score in isolation. Let be its positive count, the total positive count for input , and its expected negative count. Its expected contribution is
For positive and , the stationary condition gives
The score compares observed co-occurrence with expected noise. It is not a conditional probability. If is zero and positive, the isolated optimum tends toward negative infinity. A finite low-dimensional model ties scores together, so it cannot generally realize every isolated optimum simultaneously. Regularization, early stopping and optimization choices further change fitted values.
A small run on the invented corpus#
Reuse the sixteen independently specified two-word messages from word embeddings. A symmetric radius-one window produces 32 directed positive events over six word types. Their frequencies are 6, 6, 4, 6, 6 and 4 in the declared order. With the 3/4-power rule, the two lower-frequency words each receive noise probability about 0.134742, and each remaining word receives about 0.182629.
To remove sampling variability, enumerate the exact expected negative loss for every output word. This deliberately costs a full vocabulary sweep and teaches the objective, not the computational speedup of sampling. Use two negatives in expectation per positive event, dimension two, two separate tables and no biases. Divide the loss by the 32 positive events.
The original script initializes its 24 parameters with the deterministic modular rule recorded in code, then performs 1,200 full-batch steps of size 0.4. Its saved losses are:
| Step | Mean expected loss |
|---|---|
| 0 | 2.110931 |
| 100 | 1.688096 |
| 400 | 1.386473 |
| 1200 | 1.352867 |
This is an actual local optimization result. It is not a held-out language score or a claim about useful real-world neighbors. Initial and final analytic gradients agree with finite differences. For the isolated lamp–charge score, the unconstrained optimum formula gives about 0.601685; the fitted rank-two system is not required to match that value exactly.
Hyperparameters and what they do#
Dimension controls how many distinct interaction patterns the two tables can fit. Window size and weighting determine which pairs count as evidence. The number of negatives and the noise distribution change the expected objective, not merely the work per step. Minimum frequency changes which words have dedicated rows and therefore changes vocabulary coverage.
Learning rate, passes and subsampling determine the optimization path and observed events. A larger number of epochs does not automatically improve a downstream task. Tune these choices against the actual application with held-out data, and separate training-loss reductions from quality claims. Save preprocessing, vocabulary, configuration and table-export choice together with the vectors.
What changed#
Supervised training required labels for the final task. Context prediction creates many learning events from unlabeled strings. Negative sampling limits each sampled update to a small collection of rows by changing the loss. The resulting table remains static, and its scores inherit the context and noise conventions used during training.
GloVe and FastText#
GloVe starts from aggregated co-occurrence counts and fits weighted log-count relations. FastText shares parts of an input representation across character sequences, allowing an unseen spelling to use learned subword components. These are distinct mechanisms; neither follows simply from increasing the Word2Vec dimension.
Limitations#
An unseen word has no dedicated learned row in basic Word2Vec. Multiple meanings share a static vector. Frequent associations can encode irrelevant or undesirable relations. Small training loss can coexist with poor task performance, especially under a different domain or preprocessing scheme. Low-dimensional constraints and nonconvex optimization also make individual coordinates and nearest-neighbor lists sensitive to the training setup.
What you should remember#
CBOW predicts a center from context; skip-gram predicts context from a center. Input and output tables have separate roles. Full softmax normalizes over the vocabulary. Negative sampling trains binary data-versus-noise scores. Duplicate sampled rows need accumulated gradients. Its optimum depends on the noise distribution.
Reproducible example#
Run the original standard-library cases, and inspect word2vec in the saved output. It contains the supplied one-step calculation, softmax comparison, exact-expectation training, final parameters and gradient checks. Python 3.9.7 reproduces the recorded floating-point output; other runtimes can differ in final digits. No external training text, weights or library implementation is used.
Next#
The repeated context pairs can be counted once. GloVe uses that matrix to fit log-count relations and makes the treatment of rare and missing pairs explicit.
References#
- Tomas Mikolov, Kai Chen, Greg Corrado, Jeffrey Dean. Efficient Estimation of Word Representations in Vector Space, 2013, sections 3.1–3.2: CBOW and skip-gram.
- Tomas Mikolov, Ilya Sutskever, Kai Chen, Greg Corrado, Jeffrey Dean. Distributed Representations of Words and Phrases and their Compositionality, 2013, sections 2.2–2.3: negative sampling and subsampling. The isolated-score optimum above is derived explicitly from the stated expected loss.
- Google Inc.; Word2Vec contributors. Original C implementation, revision
20c129a, Apache-2.0.InitUnigramTableand negative-sampling/subsampling branches were checked as implementation references. Its code, training data, weights, figures and benchmark results are not copied into our executable case.