3.5.11 · D4Sequence Models

Exercises — Word embeddings (Word2Vec, GloVe)

2,165 words10 min readBack to topic

This page is a self-test ladder. Each rung is harder than the last. Cover the solution, try it, then reveal. Every symbol here was built in the parent note Word embeddings — if a symbol feels unfamiliar, re-read that note first.

A tiny reminder of the notation you will use, in plain words:

Definition Symbol cheat-sheet (tap to open)
  • ::: the vocabulary — the set of all distinct words. is how many words there are.
  • ::: the input embedding of word — a short list of numbers (a vector) that is the "meaning coordinates" of .
  • ::: the output embedding of word — a second vector per word, used only when plays the role of a thing-to-be-predicted.
  • ::: the dot product — multiply the two vectors slot-by-slot and add up. One number. Big and positive when the two vectors point the same way.
  • ::: the sigmoid — squashes any real number into , read as a probability.
  • ::: turns a whole list of scores into probabilities that sum to (see Softmax function).

Level 1 — Recognition

Exercise 1.1

For a vocabulary of words with embeddings of dimension : (a) How long is one one-hot vector? (b) How long is one embedding vector? (c) How many numbers does the input embedding matrix store?

Recall Solution

(a) A one-hot vector has one slot per word, so its length is . All slots are except a single . (b) An embedding vector has numbers — that is the whole point: dense and short. (c) The input embedding matrix has one row (or column) per word, each of length : So we replaced -long sparse vectors with -long dense ones, at the cost of storing a M-parameter lookup table.

Exercise 1.2

Match each phrase to CBOW or Skip-gram: (a) "predict the missing centre word from its neighbours"; (b) "predict the neighbours from the centre word"; (c) "averages the context embeddings into one hidden vector".

Recall Solution

(a) CBOW — Continuous Bag of Words takes context in, guesses the target. (b) Skip-gram — target in, guesses each context word. (c) CBOW — its hidden layer is , an average. Skip-gram uses the single target vector with no averaging.


Level 2 — Application

Exercise 2.1

CBOW hidden layer. Context is ["cat", "on"] with input embeddings Compute the hidden vector with .

Recall Solution

What: average the context vectors. Why: CBOW throws away word order and keeps only the "centre of mass" of the context, so one blended vector represents "the surroundings".

Exercise 2.2

Using from above, the vocabulary is sat, ran, mat with output embeddings (a) Compute the three scores . (b) Convert to probabilities with softmax. (c) Which word is predicted?

Recall Solution

(a) Score = dot product = how aligned the candidate's output vector is with the context vector. (b) Softmax: . The denominator is . (c) "sat" — because its output vector points exactly along , giving the biggest dot product, which softmax then amplifies into near-certainty.

Exercise 2.3

Negative sampling, single step. A real pair has . One negative word has . Compute the loss

Recall Solution

Why sigmoid here, not softmax? Negative sampling reframes the task as a yes/no question — "is this pair real?" — so each pair needs one probability, and turns one score into one probability. No -sized sum needed.

  • Real term: , so .
  • Negative term: , so . The negative term is large because the model still thinks the fake pair looks somewhat real ( is not close to ) — that is exactly the mistake we are pushing down.

Level 3 — Analysis

Exercise 3.1

Cosine similarity measures direction, ignoring length. Given compute and . Explain what each result says about the words.

Recall Solution

Cosine similarity: . Why cosine and not raw dot product? Frequent words tend to get long vectors; cosine divides that length out so only direction (meaning) is compared.

  • , , , so . Same direction identical meaning, even though is twice as long.
  • , so . Orthogonal unrelated words. See figure below for the geometry.
Figure — Word embeddings (Word2Vec, GloVe)

Exercise 3.2

GloVe's insight is about ratios of co-occurrence probabilities. With , , , , compute the two ratios and and interpret.

Recall Solution
  • Ratio for "solid": . Large — "solid" strongly distinguishes ice from steam (it belongs with ice).
  • Ratio for "water": . ≈1 — "water" relates to both equally, so it does not separate them. The point: raw probabilities are noisy, but the ratio cleanly answers "does this probe word tell ice and steam apart?" That is why GloVe fits vectors to log-co-occurrences rather than raw counts.

Exercise 3.3

The negative-sampling noise distribution is . Two words have raw frequencies and . Compute the ratio of their sampling probabilities with the exponent and without it (exponent ). Explain the design choice.

Recall Solution

Without smoothing (exponent ): ratio . "the" gets sampled more. With : ratio . Raising to compresses the gap (): common words are still sampled more, but rare words like "cat" get a fairer share of negative slots. Why not exponent ? That would sample every word equally and waste updates on words that never occur; is the empirical sweet spot between "sample by frequency" and "sample uniformly".


Level 4 — Synthesis

Exercise 4.1

Analogy arithmetic. With embeddings and candidate answers and : (a) compute ; (b) pick the candidate with higher cosine similarity to .

Recall Solution

(a) Why subtract then add? "kingman" isolates the royalty minus maleness direction; adding "woman" re-injects femaleness — the arithmetic navigates meaning-space. (b) equals queen exactly, so . For prince: ; ; ; . Winner: queen (). See figure.

Figure — Word embeddings (Word2Vec, GloVe)

Exercise 4.2

Compare the softmax cost of full softmax vs. hierarchical softmax vs. negative sampling for and negatives. Give the number of score computations per training step for each.

Recall Solution
  • Full softmax: one score per vocabulary word dot products. .
  • Hierarchical softmax: a balanced binary tree over leaves has depth . So node-decisions. .
  • Negative sampling: real negatives dot products. . Speed-up of negative sampling over full softmax: . This is why the parent note calls full softmax "expensive" — the denominator sum is the bottleneck.

Level 5 — Mastery

Exercise 5.1

Derive why GloVe uses (not, say, a polynomial) to link vectors and probability ratios. Start from the requirement that the linking function must turn a difference of dot products into a ratio of probabilities.

Recall Solution

What we require: we want . Why a difference maps to a ratio: the left input is (a subtraction of scalars), the right output is (a division). We need one function that satisfies Solve it. Set : , forcing . Set : , consistent. The unique continuous function turning subtraction into division is the exponential: . (Any works, but is the natural choice and rescales into the vectors anyway.) Finish. So . Taking logs turns the product into the additive relation GloVe fits: where was absorbed into the bias . This is why the log appears in the loss.

Exercise 5.2

GloVe weighting for , else , with . Compute and explain each case, including the degenerate .

Recall Solution
  • . Degenerate but essential: pairs that never co-occur have ; weight deletes that infinite term from the loss so training stays finite.
  • . A once-seen pair is noisy — weight is tiny.
  • . Moderate pair, moderate weight.
  • . At the cap.
  • (since , the "otherwise" branch). Cap prevents dominance: without the cap, ultra-frequent pairs like ("of","the") would swamp the loss and drown out informative rare pairs. The three behaviours — at zero, rising for rare, flat-capped for frequent — are exactly the three cases the parent note lists.

Exercise 5.3

Prove that if two words and have identical output embeddings , then softmax assigns them equal probability for every possible hidden state . What does this tell you about identifiability?

Recall Solution

Softmax probability of word is . The denominator is the same for all words, so probabilities differ only through the numerators. If then for every , hence , giving always. Identifiability lesson: the model cannot tell and apart from any context — they are the "same word" to it. So distinct words must get distinct vectors; training is precisely the pressure that separates words appearing in different contexts. (This is the same identifiability issue transfer learning relies on when reusing a well-separated embedding table.)


Recall One-line self-check summary

CBOW averages context, Skip-gram fans out ::: both feed dot-product scores into softmax Cosine ignores length, dot product does not ::: cosine synonyms, unrelated, opposite Negative sampling cost vs full softmax ::: instead of GloVe fits vectors to ::: of co-occurrence counts, weighted by

Related deeper reading: Attention mechanism, BERT, Subword tokenization, t-SNE, Backpropagation, LSTM, GRU.