Skip to content

4.2 Embeddings and language modeling

ready≈ 13 hoursNeeds: 4.1Unlocks: 4.3, 4.4
  1. 1 Learn
  2. 2 Bridge & derive
  3. 3 Explore (Embedding explorer)
  4. 4 Do
  5. 5 Check

n-gram models. Module 3.8 predicted characters from the previous few characters. The same idea over words, with counts instead of a network, is the n-gram model: assume the next word depends only on the previous n−1n-1 (the Markov assumption) and estimate P(w∣context)P(w \mid \text{context}) as a ratio of counts. Longer contexts predict better but are seen less often, and most trigrams in new text never occurred in training (Jurafsky & Martin, SLP3 ch. 3).

Interpolation mixes the orders: P=λ1P1+λ2P2+λ3P3P = \lambda_1 P_1 + \lambda_2 P_2 + \lambda_3 P_3 with weights that sum to 1, where P1P_1 is an add-one unigram so that no word ever gets probability zero. Because each term is a distribution, so is the mixture. The weights are tuned on held-out data, and the model is compared by perplexity, the exponential of the mean negative log probability, exactly as in 3.8 (SLP3 §3.2, §3.6).

Interpolated n-gram probabilities sum to 1step 1 of 4
  1. ∑wP1(w)=∑wc(w)+1N+V=N+VN+V=1\sum_{w} P_1(w) = \sum_w \frac{c(w)+1}{N+V} = \frac{N + V}{N+V} = 1

Meaning from company. An n-gram model treats “king” and “queen” as unrelated symbols. Distributional semantics represents each word by the words around it: count how often each pair occurs within a few positions, and words used alike get similar rows (CS224n lecture 1 notes). Raw counts are dominated by “the” and “and”, so reweight them by positive pointwise mutual information, max⁡(0,log⁡P(i,j)P(i)P(j))\max(0, \log \frac{P(i,j)}{P(i)P(j)}), which keeps only pairs that co-occur more than chance. A truncated SVD then compresses the rows to dense vectors, as PCA did in 1.2. Word2vec’s skip-gram objective implicitly factorizes a shifted version of the same PMI matrix (Levy & Goldberg 2014).

Using the vectors. Similarity is the cosine of the angle between vectors, so frequent words with long vectors do not win by length. Analogies take vb−va+vc\mathbf{v}_b - \mathbf{v}_a + \mathbf{v}_c and find the nearest other word. They work when a relation, such as gender, shows up as a consistent offset, (Mikolov et al. 2013), and they also expose biases in the training text (Bolukbasi et al. 2016).

Embedding explorer

Similarity, analogies, clusters

Static view on small screens. Open this page on a laptop to interact.

Nearest to king (cosine, 64-D)

  1. 0.78
  2. 0.78
  3. 0.72
  4. 0.72
  5. 0.68
  6. 0.66
  7. 0.59
  8. 0.59
  9. 0.58
  10. 0.57
kinglovegoodnighttheandfatherbloodsweetromegoddeathrichardedwardviivhenryiiixilewisiiwarwickking
Analogy is to as is to her (then i'll, will, take, me)

These vectors come from counting, not training: how often each of the 1,500 most frequent words in Tiny Shakespeare appears within four words of each other, reweighted by PPMI and compressed to 64 dimensions with an SVD (references/gen_embeddings.py, the same pipeline as your exercise). Words used in similar contexts get similar vectors, so kings cluster with kings and eyes with tears. Analogies take b − a + c and find the closest word: he : she :: him : her works; king : queen :: man : ? does not (its runners-up include elizabeth, a queen), because in these plays "king" and "queen" mostly name particular people. The 2-D picture is a PCA projection of the 64 dimensions and squashes most of the structure; the neighbour list is computed in all 64.

A word box with suggestions from 1,500 frequent Shakespeare words. A list shows the ten nearest words by cosine similarity with bars; a scatter plot shows all 1,500 words in a 2-D PCA projection with the query and its neighbours highlighted. Below, three boxes form an analogy a is to b as c is to ?, with the answer and runners-up, and preset analogies as buttons. Keyboard: Type a word and press Enter; Tab to the neighbour links and analogy presets.
n-grams and count-based word vectors stubs/m4_2_ngrams_and_vectors.py

Loading starter file…

Prefer your own editor? Edit exercises/stubs/m4_2_ngrams_and_vectors.py and run mlc check 4.2. The tests are identical; import the results on the progress page.

Hints · interp_prob 0/3 revealed
Hints · cooccurrence 0/3 revealed
Hints · ppmi 0/3 revealed

Then run both parts on Tiny Shakespeare (locally; the text is cached if you did 4.1):

Terminal window
cd exercises && python projects/shakespeare_ngrams_vectors.py

With the reference solution, held-out perplexity falls from 589 (unigram) to 345 (bigram) and 337 (trigram): most trigrams in new text were never seen, so the third order adds little. The vectors find richard, edward, henry next to king and solve he : she :: him : her.

1. What does the Markov assumption in a trigram model say?
2. Why interpolate with lower orders instead of using trigram counts alone?
3. A word pair has PPMI 0. What does that mean?
4. Why compare word vectors with the cosine rather than the dot product?
  • not yet: All tests pass (0/?)
  • not yet: Checkpoint quiz ≥ 80%
Finish the items above first.
Learner log: time spent and points of confusion

Every confusion you note becomes a fix before the module is marked stable. Export it from the progress page and attach it to an issue.