Course contents 07 / 28

07 / 28 · Distributed Representations

Word embeddings

Build word representations from context evidence, distinguish lookup tables from learning objectives, and check cosine, rotation, projection and sentence-pooling limits.

On this page 7

A message mentions a microphone, but the training examples mostly mention a lamp. Both can occur beside charge and inspect. A table of independent word IDs gives a predictor no reason to transfer anything between them. A useful representation should make shared evidence accessible while retaining distinctions needed for the task. Merely replacing an ID with a list of numbers does not accomplish that: the numbers need a construction or learning rule.

Baseline: one-hot vectors#

For a vocabulary of size VV, a one-hot vector has one at the word’s index and zero elsewhere. Different words have dot product zero and the same Euclidean distance. They are distinct symbols with no built-in graded similarity.

ei⊤ej=0(i≠j),∥ei−ej∥2=2.\begin{aligned} e_i^\top e_j&=0\quad(i\ne j),\\ \lVert e_i-e_j\rVert_2&=\sqrt2. \end{aligned}

This is often a sensible interface. A linear model can still learn different coefficients for every word, and sparse implementations do not materialize all those zeros. The limitation appears when a rare word needs evidence gathered for another word: the representation supplies no parameter sharing by itself.

A single integer ID is more compact, but its numerical distance is arbitrary. Assigning lamp ID 0 and tripod ID 1 does not establish that they are closer than words with IDs 0 and 5. IDs should select rows, not serve as ordinal measurements unless the application really has an ordered quantity.

Four attempts#

One approach specifies features by hand: whether an item needs charging, folds for storage or has an adjustable mount. Such coordinates have clear meanings, but they require domain knowledge and coverage of every relevant property. A general text vocabulary contains ambiguous and abstract words for which this scheme quickly becomes difficult. The feature designer also decides which distinctions disappear.

A second approach counts contexts. Words with similar context distributions then have similar rows even if they never appear next to one another. Context might mean a neighboring token, an entire document or a syntactic relation. That definition changes the representation; “appears with” is not a uniquely determined statistic.

A third approach compresses a context matrix to lower rank. Shared latent directions can summarize recurring patterns and reduce storage, at the cost of reconstruction error. The answer depends on the matrix, weighting and error measure. Factorizing raw counts emphasizes different evidence from factorizing transformed counts. A small dimension is a capacity choice, not a certificate that the coordinates correspond to human concepts.

A fourth approach learns vectors through a prediction task. Update a word’s row whenever it helps predict a label or neighboring word. Two words can acquire compatible roles because the objective rewards similar predictions in relevant contexts. Word2Vec makes this mechanism explicit. Supervised embeddings instead reflect the supplied labels, which may emphasize different distinctions from context prediction.

These constructions produce different objects under the same name. A fixed feature vector, a co-occurrence row and a learned dense vector should not be compared as though only their dimension differed. Ask what observations influence a row, which loss organizes the space and how that space is evaluated.

The embedding table#

An embedding table is a matrix EE with one row per vocabulary item and dd numerical coordinates per row:

E∈RV×d,vi=E⊤ei∈Rd.\begin{aligned} E&\in\mathbb R^{V\times d},\\ v_i&=E^\top e_i\in\mathbb R^d. \end{aligned}

The matrix expression describes a row lookup. No dense one-hot multiplication is necessary in an implementation. A sequence of LL IDs produces an array with shape L×dL\times d; a padded batch of BB such sequences produces B×L×dB\times L\times d. Padding positions still require masks in later pooling or attention operations. The table itself does not know which positions should count toward a sentence representation.

For a supplied three-row example, take

E=[10013/41/4].E=\begin{bmatrix}1&0\\0&1\\3/4&1/4\end{bmatrix}.

Let the rows correspond to lamp, tripod, microphone. IDs [2, 0, 2] return the third, first and third rows, producing shape 3 by 2. These coordinates are chosen to expose the lookup operation; they are not vectors learned from a corpus. The same ID always returns the same row in this static representation.

Learning sends gradients back to selected rows. If an ID appears twice, contributions from both positions add to that row. Rows absent from an input can still receive updates through an output layer, regularization or another part of the objective, so “only touched input rows change” describes lookup backpropagation rather than every possible training setup.

Storage scales with VdVd rather than V2V^2 for a dense pairwise table. For a hypothetical vocabulary of 12,000 items and 48 coordinates, one table contains 576,000 numbers, or 2,304,000 bytes in float32 before metadata, gradients or optimizer state. A method with separate input and output tables doubles this parameter storage. The example is arithmetic, not a measured process-memory report.

Reading a vector space#

For nonzero vectors, cosine similarity compares directions:

cos⁡(u,v)=u⊤v∥u∥2∥v∥2.\operatorname{cos}(u,v)=\frac{u^\top v}{\lVert u\rVert_2\lVert v\rVert_2}.

Multiplying a vector by a positive scalar leaves its cosine similarities unchanged. Euclidean distance generally changes. Neither metric is automatically correct for every objective: an inner-product model may use vector length as part of its score. A zero vector has no defined cosine direction and needs an explicit handling rule.

Worked example#

We independently specify sixteen two-word equipment descriptions. The table lists each distinct string and its repetition count:

StringCount
lamp charge4
lamp inspect2
tripod inspect3
tripod adjust3
microphone charge2
microphone inspect1
microphone adjust1

Treat the other word in each two-word string as context. No context crosses a message boundary. Looking only at the three action columns gives the following rows:

Wordchargeinspectadjust
lamp420
tripod033
microphone211

The dot product of the lamp and microphone rows is ten. Their squared lengths are twenty and six. Write vLv_L, vMv_M and vTv_T for the lamp, microphone and tripod rows. The cosines are

cos⁡(vL,vM)=10120≈0.912871,cos⁡(vL,vT)=6360≈0.316228.\begin{aligned} \operatorname{cos}(v_L,v_M)&=\frac{10}{\sqrt{120}}\approx0.912871,\\ \operatorname{cos}(v_L,v_T)&=\frac6{\sqrt{360}}\approx0.316228. \end{aligned}

The first pair shares a larger proportion of its observed action pattern. It does not follow that lamps and microphones are synonyms, interchangeable tools or equally safe to charge. The relation is defined by this invented corpus and the chosen context columns. A table of maintenance faults or storage locations could organize the same words differently.

The coordinates of a learned dense space usually lack such direct labels. Rotating every vector by the same orthogonal matrix preserves dot products and distances. In our hand-chosen table, a quarter turn maps the first row to (0, 1), the second to (-1, 0) and the third to (-1/4, 3/4). All pairwise dot products remain unchanged. A claim that a particular coordinate inherently means “chargeability” would depend on an arbitrary orientation.

A two-dimensional visualization can discard important evidence. Consider supplied vectors

a=(1,0,4),b=(1,0,−4).\begin{aligned} a&=(1,0,4),\\ b&=(1,0,-4). \end{aligned}

Their cosine is −15/17-15/17. Dropping the last coordinate maps both to (1, 0), whose cosine is one. This simple projection is enough to show why visual proximity in a plot does not prove proximity in the original space. When inspecting a projection, compute the actual neighbor relation in the original representation and state which projection was used.

Vector differences can also be tested as relations. If a transformation is consistently expressed by a similar offset across many held-out pairs, offset retrieval may succeed. One attractive analogy is weak evidence: choices of vocabulary, excluded query words, similarity metric and the test set all affect the result. The training objective does not guarantee that every linguistic relationship becomes a straight line.

Intrinsic and extrinsic evaluation#

Intrinsic evaluation measures a property of the representations directly: agreement with a specified similarity judgment, retrieval of held-out relations or stability of nearest neighbors. It needs an explicit target relation. Topic association and synonymy are different labels; opposite words can share many contexts and therefore be close.

Extrinsic evaluation asks whether the representation helps a downstream task. For an equipment-message classifier, compare a fixed evaluation protocol with and without the vectors. Keep splits, preprocessing and the classifier’s capacity under control. Otherwise a better score can come from a larger classifier or changed data rather than the representation.

Freezing the table tests the usefulness of the existing representation. Fine-tuning tests the initialization together with task-specific adaptation. These are different experiments. If external vectors are introduced, check the exact model’s license, training-data documentation, vocabulary coverage and domain; the software library’s license alone does not cover downloaded weights.

Our context table and chosen coordinates establish no benchmark performance. They demonstrate algebraic properties with known inputs. A useful evaluation would need unseen messages, task labels, uncertainty estimates and failure slices, including rare words and newly introduced equipment names.

From words to sentences, for now#

A simple sentence vector averages its token vectors:

vˉ=1L∑t=1LEwt.\bar v=\frac1L\sum_{t=1}^{L}E_{w_t}.

This yields a fixed dimension regardless of message length. Repeated words contribute repeatedly; padding must be excluded from both the sum and its denominator. Weighting can emphasize selected words, but the weighting rule becomes another part of the representation contract.

A mean loses order. With our supplied table, lamp tripod and tripod lamp both produce (1/2, 1/2). A downstream model receiving only that mean cannot recover which item came first. This is an information loss before classification, not a problem that additional classifier training can necessarily repair.

Static lookup also gives a word the same vector in every sentence. A token with different meanings must share its row until a later context-dependent mechanism distinguishes its uses. We will keep this limitation explicit when moving from word representations to sequence models.

Limitations#

An embedding inherits the coverage and associations of its training evidence. Rare tokens have less reliable estimates; unseen tokens may share one unknown row. Co-occurrence reflects many relations, including patterns that are irrelevant or undesirable for the intended task. Dense representations do not remove those issues merely by hiding the original counts.

Similarity changes with preprocessing, training objective, dimension and evaluation metric. Different runs can produce different coordinates while preserving useful relations. Compare task behavior and invariant quantities before interpreting an individual coordinate or declaring a particular geometric pattern stable.

What you should remember#

IDs identify words; embeddings provide numerical features. A table lookup is shared across positions. The objective determines which relationships receive training pressure. Cosine compares nonzero directions. Projection can hide disagreement. Averaging static word vectors loses order and does not resolve context-dependent meanings.

Reproducible example#

The embeddings section of the original executable cases constructs all sixteen strings, the symmetric co-occurrence matrix, context cosines, the supplied lookup table, a rotation and the projection counterexample. Saved JSON records the values. The code uses Python’s standard library and exact fractions where applicable; no pretrained vectors are loaded. Chosen vectors are labeled separately from the trained examples in later sections of that script.

Next#

The table tells us where the vectors live, but not which gradients should shape them. Word2Vec builds prediction targets directly from neighboring words and replaces an expensive vocabulary-wide update with a sampled binary objective.

References#

  • Tomas Mikolov, Kai Chen, Greg Corrado, Jeffrey Dean. Efficient Estimation of Word Representations in Vector Space, 2013, sections 3.1–3.2: shared projection tables, CBOW and skip-gram. The method is a factual reference; none of its analogy examples, figures, pretrained vectors or benchmark results is reproduced.
  • Armand Joulin, Edouard Grave, Piotr Bojanowski, Tomas Mikolov. Bag of Tricks for Efficient Text Classification, 2016, section 2: averaging learned feature vectors for a linear text classifier. The table and averaging counterexample here are independently specified.