Skip to main content
Natural Language Processing

CBOW, GloVe, and Statistical Language Modeling

Published: 2026-08-13
Level: postgraduate
Audience: Postgraduate students in Natural Language Processing

Prerequisite Knowledge

This lecture builds on the following concepts from earlier lectures. If any feel unfamiliar, review the linked notes before proceeding.

Previously Covered in This Subject

  • Skip-gram with negative sampling — the training objective and update mechanics — covered in Lecture 3
  • Static versus contextual word embeddings — the fixed-vector idea this lecture builds on — covered in Lecture 3
  • Sigmoid and log-loss optimization — the math behind the update step — covered in Lecture 3
  • Self-supervised Word2Vec training — context windows and training-sample generation — covered in Lecture 3
  • Word–word co-occurrence matrices — the counting tables GloVe builds on — covered in Lecture 2
  • Dot product and cosine similarity — how closeness between word vectors is measured — covered in Lecture 2
  • The garbage-in, garbage-out principle — why corpus quality decides everything downstream — covered in Lecture 1
  • Foundational corpora — the ready-made datasets this lecture refers to — covered in Lecture 1

4.1 Skip-gram with Negative Sampling: Recap of the Update Procedure

4.1.1 Why Static Word Embeddings Still Matter

This session completes the family of static word-embedding algorithms: skip-gram with negative sampling (SGNS), continuous bag of words (CBOW), and GloVe. The word "static" matters. A static embedding gives each word one fixed vector, unlike the contextual embeddings inside transformer models, which change a word's vector depending on its neighbors. Even though contextual embeddings now dominate modern NLP, the static algorithms remain useful and are widely used in production environments. The intuition behind contextual word embeddings actually grew out of these static methods, so understanding SGNS, CBOW, and GloVe is the foundation for the transformer material later in the course.

Why learn three old algorithms when transformers exist? Because they are the cheapest way to turn text into useful numbers, and every modern model stands on their shoulders. SGNS and CBOW invented the trick of training embeddings on a self-supervised "fake task" (predict a word from its neighbors), and GloVe invented the trick of training directly on global word counts. Transformers kept both ideas and added context. If you understand the static algorithms, the jump to contextual embeddings is a small one.

These algorithms are low-resource by design: they run comfortably on a local CPU, with no GPU cluster needed. Pre-trained word-embedding models can be downloaded and plugged into an application, much like downloading GPT or LLaMA checkpoints. The gensim open-source library provides ready implementations of all these word-embedding algorithms, in the same spirit that scikit-learn provides implementations of classical machine-learning algorithms and TensorFlow provides deep-learning primitives. You only pass the hyperparameters; the algorithms themselves are already implemented, and a demo codebase and a spreadsheet walkthrough of the SGNS update accompany this material.

Static embeddings, especially SGNS, are popular in production precisely because they are cheap to train and cheap to run. A search or recommendation system that needs to compare millions of words cannot afford a transformer for every lookup; a precomputed table of vectors does the same job for a fraction of the cost, and it still appears in real applications today.

4.1.2 The Update Procedure, Step by Step

The previous session walked through one full SGNS update cycle on a worked example, and this recap retraces every step. The setup starts with initial word embeddings for a target word and for its context words. In the worked example, the positive context word appears as "stark" in the recording — likely "start", the exact word name does not change the math — and the target word as "net". We retrace the same six steps below, and in 4.1.4 we run them with explicit numbers.

Purpose. SGNS trains word embeddings by teaching the model to tell real word pairs from fake ones. For a target word, the words that truly appeared near it are positive samples (label 1) and a handful of randomly chosen words are negative samples (label 0). Moving the embeddings so the positives score high and the negatives score low automatically places words that occur together close in vector space.

Inputs.

  • : the target word embedding — the vector we are improving for the center word, a row of real numbers (say 300 of them).
  • : a context word embedding — the vector of one positive context word or one sampled negative word.
  • : the learning rate, set to in the worked example — the step size of each update.
  • Labels: for the positive context word, for every negative sample.

Outputs. Updated (better) vectors for the target word, the positive context word, and each negative context word.

Steps. The six-step update procedure:

  1. Take the dot product of the target word embedding with each context-word embedding, and push each dot product through the sigmoid function. This gives a predicted probability for each word.
  2. Compare against the actual labels. The positive context word should give a value of 1, and every negative sample should give 0. With the initial embeddings, the sigmoid values are neither 1 nor 0, so there is an error.
  3. The error for each word is the difference between the actual value and the predicted value.
  4. Compute the partial derivative of the objective with respect to the target word embedding. These error values are pre-computed. The update multiplies the positive word's error by the positive word's vector, multiplies each negative word's error by its vector, and takes the sum of all these vectors.
  5. Update the target word embedding using the learning rate 0.05: the new target embedding is the old one, moved by the learning rate times this gradient.
  6. Repeat the same partial-derivative update for the positive context word and for each negative context word.

The purpose of these updates is that the positive context word's embedding should move closer to the target's embedding, and the negative samples should move away from it. The partial derivatives are built to do exactly that.

Why does this work? Because the sigmoid score measures how "real" the model thinks a pair is. When the score for the positive pair is too low, the error is large and the update pulls the two vectors together. When the score for a negative pair is too high, the error is large in the other direction and the update pushes the vectors apart. After billions of such pushes and pulls across the corpus, words that appear in the same contexts (like "coffee" and "tea") settle near each other, and words that never co-occur sit far apart.

4.1.3 The Mathematics Behind the Update

Let us write the procedure in symbols, one formula at a time. Every symbol is named where it first appears.

Step 1 — the prediction. For a target embedding and a context embedding , the raw similarity score is their dot product . The sigmoid function squashes any real number into the range , so it turns the score into a probability-like prediction:

A large positive dot product gives close to 1; a large negative dot product gives close to 0; a dot product of exactly 0 gives .

Step 2 — the error. The label is 1 for the positive context word and 0 for a negative sample. The error is actual minus predicted:

For the positive word: , a number between 0 and 1 — small when the model is right, large when it is wrong. For a negative sample: , a number between and 0.

Step 3 — the gradient. The partial derivative of the SGNS objective with respect to the target embedding is the sum of each error times that word's own vector:

The sum runs over all negative samples; is the positive context vector and is the vector of negative sample .

Step 4 — the update. With the error defined as actual minus predicted, the update that moves the positive pair together and the negative pairs apart adds the learning-rate-scaled gradient:

This is gradient ascent on the SGNS objective. Context word embeddings (positive and negative) get updated through the same formula with their own partial derivatives, where each context vector is scaled by the same error but multiplied by the target vector instead.

Sign convention note (worth one careful read). The lecture describes the error as actual minus predicted and the update as subtracting the learning rate times the gradient. Those two choices together would move the positive word away from the target — the opposite of the intended behavior. The two conventions that are equivalent:

  • Error = actual − predicted, and update by adding times the error-weighted sum (the gradient-ascent form above — the standard SGNS update).
  • Error = predicted − actual, and update by subtracting times the sum (the gradient-descent form used by many spreadsheet implementations).

Both describe the same arithmetic: the positive word's error pulls its vector toward the target, and each negative word's error pushes its vector away. On the exam, follow the worked numerical pattern from the lecture spreadsheet; the numbers below show the update that achieves the stated goal.

Two sanity checks on the sign convention before we compute anything. First, if the model is already perfect on the positive pair (), then and nothing moves — correct, there is nothing to fix. Second, if the model wrongly scores a negative pair at , then and the update subtracts from the target vector — pushing it away from the negative word. Both checks match the intended push-pull behavior.

4.1.4 Fully Worked Example: One Update Cycle with Real Numbers

Here is a complete numerical cycle in two dimensions, with the learning rate 0.05 used in the lecture. The words are illustrative; the arithmetic is the exact pattern of the lecture's spreadsheet example.

Setup. Target word "net", positive context "start", one negative sample "table" (one negative sample keeps the arithmetic short; real training uses 5–20). Initial 2-dimensional embeddings:

Step 1 — forward pass (dot products and sigmoids).

Positive pair: , so

Negative pair: , so

The model gives the real pair only 57% (wants 1) and the fake pair 52% (wants 0). It is almost guessing — training has work to do.

Step 2 — errors (actual minus predicted).

Step 3 — gradient for the target vector.

Step 4 — update the target vector (add times the gradient).

Step 5 — update the context vectors with the same errors. For the positive context vector, scale the target vector by the positive error:

For the negative context vector, scale the target vector by the negative error (which is negative, so this subtracts):

Sense check. Recompute the two dot products with the updated vectors. Positive: , up from 0.29. Negative: , down from 0.10. The real pair scored higher and the fake pair scored lower — exactly what one update cycle should do. The final answer: , with the context vectors and .

4.1.5 Assumptions & Scope

Assumptions. SGNS assumes the distributional hypothesis: words that appear in similar contexts have similar meanings. It also assumes that a small sample of noise is enough to approximate the full vocabulary normalization — that is what makes training fast. And it assumes the context window captures all the co-occurrence signal that matters.

Scope. The gradient update applies to exactly the vectors involved in one training step: the target, the one positive context word, and the sampled negatives. Nothing else moves in that step. The update works for any embedding dimension, but the push-pull geometry becomes harder to visualize beyond 2 or 3 dimensions. If the sampled negatives accidentally include a true context word of the target (possible when sampling randomly from frequent words), that pair gets pushed apart even though it is real — a known weakness that the power-3/4 sampling heuristic in Word2Vec reduces but does not remove.

4.1.6 Visual Intuition

Picture a flat map with one arrow per word. The target "net" sits at coordinates . Draw the positive word "start" at , high up and to the right; draw the negative word "table" at , far to the right and low down. The gradient points up-and-left — toward "start" and away from "table" — and the update nudges "net" exactly of the way along that arrow. After the step, "net" sits closer to "start" and farther from "table". Repeat this millions of times for every word, and the map settles into a shape where words that share contexts share neighborhoods. The takeaway: each training step is one small tug-of-war between friends pulling words together and strangers pushing them apart.

4.1.7 Pitfalls

  • Sign errors. Mixing the two conventions (error = actual − predicted with a subtracting update) flips the whole geometry: positives get pushed away and negatives get pulled in. Decide on one convention and check the two sanity tests from 4.1.3 after every change.
  • Ignoring the context vector updates. Updating only the target vector trains half the model. The context vectors (positive and negative) must be updated with the same errors, using the target vector as the multiplier.
  • Too few negative samples. With only 1 or 2 negatives, the model sees almost no repulsion signal and the embeddings stay flat. Typical practice is 5–20 negative samples per positive pair.
  • Too large a learning rate. is a small, safe step. A large makes vectors overshoot and oscillate instead of settling.

4.1.8 Recap, Exam Note, and Real-World Connection

Recap. SGNS turns "do these two words belong together?" into a binary classification game: score the pair with a sigmoid over the dot product, compare with the label (1 for real, 0 for fake), and move each vector by the learning rate (0.05) times its error-weighted neighbor — pulling real pairs together, pushing fake pairs apart.

Exam note: expect an exam numerical similar to this worked example — dot products, sigmoid values, errors, the gradient update, and the new embeddings with learning rate 0.05.

Bridge. We assumed a context window decides who counts as a neighbor — the next subsection asks how big that window should be. After that, the same neighbor-prediction idea is mirrored by CBOW, which predicts the target from the context instead.

Where this matters in the real world: SGNS-style embeddings power production search, recommendation, and document-ranking systems that must run on modest hardware. A news app can embed every headline once with a static model and then rank by vector similarity in microseconds per query — a job that would cost far more with a transformer. This is why the low-resource property praised in 4.1.1 is not nostalgia; it is a budget decision made daily in industry.

4.1.9 Choosing the Context Window

How big should the context window be? A smaller window is easier and faster. But a small, domain-specific corpus may need a larger window to produce enough context and out-of-context words. For a larger training corpus, a window of plus/minus 2 to plus/minus 4 words is enough. This window choice determines which words count as context, which is why the training data itself plays such a big role in what these embeddings learn.

The window is a dial that trades two kinds of quality. A narrow window captures syntax (how words combine); a wide window captures topic (what words tend to appear in the same discussion). Systems that need synonym-style similarity (search, recommendations) often widen the window; systems that need grammatical patterns keep it narrow. There is no single right answer — which is why the window is a hyperparameter you choose, and why two teams with the same code and different windows end up with visibly different vector spaces.

4.2 Training Data Quality and Bias in Word Embeddings

4.2.1 Data Shapes Meaning

Because embeddings are built from context, the training data shapes everything. The quality of the training data, the ethics, and responsible AI concerns all matter at the word-embedding step itself, because these embeddings are the input layer to every fancy model downstream — GPT, transformers, large language models, small language models. If the embeddings come from noisy data, everything downstream inherits the noise. The meanings of words also change with the data, and meanings are domain-specific.

The hook: your model can only know the world you showed it. An embedding is not a dictionary definition stored in the word itself; it is a summary of every sentence the word appeared in. Change the sentences, and you change the "meaning". That single fact explains everything in this section — why words drift over time, why meanings are domain-specific, and why biased training articles produce biased embeddings.

This pattern shows up in every model seen so far — SGNS, CBOW, GloVe, and later the attention mechanism — context plays the central role in generating word embeddings. Good context gives a good output.

4.2.2 Words Change Meaning: The "Broadcast" Story

Think of the word "broadcast". It started in the farming industry, where it meant scattering seeds over a wide area. Today we use it for news channels and social media. The same string of letters, two completely different contexts, and so two different neighborhoods in a modern vector space — the farming sense would sit near "sow" and "harvest", while the media sense sits near "channel" and "audience".

The language keeps growing: new words appear constantly, and the context keeps changing. Word embeddings adapt themselves to the context they are trained on. This is why embeddings are never trained once and frozen forever: an embedding model trained on 1990s newspapers does not know what "tweet" means as a verb, and one trained on 1950s texts places "virus" only in medicine, never in computing. Every embedding has a birthday — the date of its training corpus — and its blind spots match that date.

4.2.3 Bias Enters at the Embedding Layer

If the training articles are biased, the embeddings will carry that bias, which is not a good thing. There are practices and mathematical formulations from fairness in ML and Responsible AI coursework that try to remove these biases from the training data so you get better quality embeddings. Cultural biases, gender biases, and similar problems must be removed because of the classic rule: garbage in, garbage out. Since these embeddings sit at the very input of the pipeline, they play a critical role in everything that follows.

Garbage in, garbage out — amplified. A biased corpus does not just produce biased embeddings; it propagates them. Because embeddings are the input layer to every downstream model — GPT, transformers, LLMs, small language models — a bias baked into the input layer resurfaces in everything built on top, however carefully those later layers are trained. This is why the lecture stresses fixing the data at the embedding step itself rather than hoping downstream models will clean it up.

A concrete example: if a corpus of news articles mentions "nurse" mostly near female pronouns and "engineer" mostly near male pronouns, the trained vectors will encode that association as a geometric fact — "nurse" will sit closer to female-gendered words. A resume-screening system built on such embeddings can then downgrade candidates in ways nobody explicitly programmed. The fix has two halves: curate and balance the training data (the lecture's emphasis), and apply debiasing techniques from the fairness-in-ML toolbox, such as removing the gender direction from the vector space or projecting neutralized words away from it.

4.2.4 Pitfalls and How to Respond

  • Treating embeddings as neutral measurements. They are statistics of a corpus, and every corpus has an author, an era, and a culture. Always ask "trained on what?" before trusting a vector.
  • Filtering bias only in the final model. If the input embeddings are biased, cleaning the downstream classifier alone leaves the baked-in geometry untouched.
  • Ignoring domain drift. An embedding trained on general web text will mislead a medical or finance application; domain-specific corpora give domain-specific meanings.

4.2.5 Recap and Bridge

Recap. Embeddings inherit everything from their training data — meaning, era, and bias. Context is the central ingredient in every word-embedding method, so data quality at this first layer determines the quality of the entire pipeline. Good context gives a good output.

Bridge. With the training-data warning in place, we return to algorithms: next, CBOW — the mirror image of skip-gram, which predicts the target word from its context instead of the other way around.

Real-world placement: the data-quality conversation is not a side note — it is the reason companies with production NLP systems maintain their own corpora and periodically retrain embeddings. Search engines, recommendation platforms, and LLM vendors all face the same trade-off the lecture describes: pre-trained embeddings are cheap and fast, but only as trustworthy as the corpus they were trained on, which is why responsible-AI review of training data happens at the embedding layer first.

4.3 Continuous Bag of Words (CBOW)

4.3.1 The CBOW Idea

The second static word-embedding algorithm is CBOW, which stands for continuous bag of words. The name says it: it takes into consideration a bag of words that are continuous — the nearby words in a window, treated as a bag.

The hook: can you fill in the blank? "The cat ___ on the mat." Any human instantly says "sat". CBOW is the algorithm that learns to do exactly that, for every word in the vocabulary, from millions of examples. No labels are written by hand — the corpus itself is the teacher.

CBOW is the mirror image of skip-gram. In skip-gram, we give a target word and try to predict the probability of the context words (and out-of-context words) around it. In CBOW, we give the context words for a given target word and try to predict the target word itself. This is a fill-in-the-blanks problem. The same idea shows up later in the attention mechanism, where certain words in a sentence are masked and the model predicts them using probabilities from the training corpus. Here the same idea applies: give the context word embeddings, and train the model so it can predict the target word correctly.

In the spoken example, the four context words "I am because I" were used to predict the target word "happy" — the full sentence was likely something like "I am happy because I …", with the blank sitting between "am" and "because". Before training, some predictions will be wrong. The model checks the probability of every possible target word given these context words, and the word with the maximum probability is predicted as the target.

The training data is self-supervised, exactly as in skip-gram: the corpus provides its own labels, because the word that actually appeared in the center is the correct answer. The one difference: here we predict the probability of the target word, not of the context words. You still need the target word's embedding to end up close to the embeddings of its context words. And the important point carries over: you are not interested in the final classification task — you are interested in the weight matrix that the training produces, because that weight matrix is the word embeddings. The "fake task" of filling in blanks is only the excuse; the learned weights are the treasure.

4.3.2 How CBOW Predicts

Given the embeddings of the context words (computed from the features), CBOW combines them and computes the probability of every possible target word in the input vocabulary. Each unique word in the vocabulary gets its own probability based on those context words. The word with the highest probability wins and is predicted as the target:

Read this as: (the predicted word) is the word that makes the conditional probability — "probability of word given the context words" — as large as possible. Computing this maximum needs a probability for every word in the vocabulary, and that is exactly the softmax function, covered in the next section.

4.3.3 The Forward Pass Under the Hood

How does "combine the context embeddings" actually work? The bag-of-words recipe is deliberately simple, and tracing it once makes the whole model concrete.

The three-step pipeline.

  1. Look up. Every context word in the window is replaced by its embedding (a vector of, say, 300 numbers). This is a table lookup, not a computation.
  2. Average. Add the context vectors together and divide by the number of context words. The result is one vector — the centroid of the context. Because addition does not care about order, the word order inside the window is thrown away: that is precisely the "bag" in the name.
  3. Score and normalize. Compare against every word's target vector with a dot product, giving a raw score per word in the vocabulary. Then apply softmax to turn the scores into a probability distribution over all words. The highest probability wins.

The two-vector trick from skip-gram reappears here: each word has an input vector (used when the word is part of the context) and an output vector (used when the word is a candidate target). The input vectors are the ones typically kept as the final word embeddings.

Worked example: one forward pass with real numbers. Corpus sentence: "the cat sat on mat", vocabulary of 5 words with indices (the=0, cat=1, sat=2, on=3, mat=4), embedding dimension 3, window of 2. Training sample: context words = {cat, on}, true target = sat.

Step 1 — look up the context vectors. Say the input matrix holds:

Step 2 — average into the centroid :

Step 3 — score every word with its output vector. With the output matrix of the worked spreadsheets, the dot products come out as:

Step 4 — softmax. Exponentiate each score: , , , , . Sum . Divide each by the sum:

The highest probability is for sat — the model predicts the correct target word, though only with 27% confidence (random guessing among 5 words would give 20%). Training exists to push that 0.270 toward 1.

Sense check. The five probabilities sum to 1.000 (up to rounding), as every softmax output must. And the predicted word is the one the corpus says actually sat in the center — the self-supervised label.

4.3.4 CBOW versus Skip-gram

CBOW is faster and simpler, because it only predicts the target word probability — it does not have to score context and out-of-context words the way skip-gram does. The trade-offs go both ways.

Dimension CBOW Skip-gram
Task Predict target from context words Predict context words from target
Cost per step One averaged context, one softmax One prediction per context word, with negative samples
Data appetite Wants a large training corpus Learns well from smaller data
Rare words Weaker — rare words get averaged into the centroid Stronger — every occurrence is its own training signal
Frequent words Predicts frequent words well Handles frequent words less efficiently
Production Simpler, slightly faster SGNS is the more popular choice overall

When to pick which: if you have a large corpus and care about speed and frequent words, CBOW is the cheaper tool; if your corpus is small or your task cares about rare words, skip-gram earns its extra cost. In production, SGNS is the more popular choice, and skip-gram is more powerful and useful for many real-world applications.

4.3.5 Student Questions

Q: When we do the word prediction probability, is it done for all the words in the vocabulary? Would that not be computationally expensive with millions of words?

A: Yes, it is done for all the words, because we need a word embedding for the entire vocabulary of the corpus — that is true for every word-embedding algorithm. Both approaches involve some computation, but it is minor compared to LLM computations. Here you are just counting things; probability is just counting, and it is easy even on CPUs. The difference is that skip-gram must compute for context words and non-context words, while CBOW only predicts the target word, which is why CBOW is a little faster.

One more important point: all of these word embeddings are built during training time, so they happen offline. None of this happens at inference time or runtime, so there is no latency cost from these heavy computations — the embeddings are pre-trained models. Training and inference have different requirements. A recent article about Google's TPU (competing with NVIDIA) described exactly this: Google separated the processing units for inference from the units for training, because training builds the offline static embeddings for the whole training corpus, while at test time you process real-world user input — you need a little more RAM during inference time and ROM during training time.

This training-versus-inference split is why pre-trained embeddings can be heavy to build but cheap to serve: pay the computation once, at training time, and then treat the vectors as a read-only table that any small service can query.

4.3.6 Assumptions, Scope, and Pitfalls

Assumption. CBOW assumes the bag-of-words shortcut is safe: word order inside the window carries little information. That holds surprisingly well for short windows but throws away syntax beyond the window.

Scope. The model is only as good as its window and its corpus. Rare words suffer, because averaging dilutes their signal, and any word outside the training vocabulary simply has no vector at all.

Pitfalls.

  • Expecting CBOW to respect word order — it cannot, by construction; the centroid is order-blind.
  • Forgetting that the weights, not the blank-filling accuracy, are the product; the classification task is disposable.
  • Using CBOW on tiny corpora, where skip-gram's per-word signal would serve better.

4.3.7 Recap, Exam Note, and Real-World Connection

Recap. CBOW predicts a target word from the average of its context-word embeddings and a softmax over the vocabulary — a self-supervised fill-in-the-blanks game whose real prize is the weight matrix, the word embeddings themselves.

Exam note: no full numerical problem for CBOW. Expect a simple addition or a conceptual question, for example the difference between the algorithms or when to use which one.

Bridge. CBOW's output layer needs one probability per vocabulary word that sums to 1 — which raises the question a student asked next: what exactly is the difference between sigmoid and softmax?

Where CBOW lives in industry: the model (and its Word2Vec sibling) is the default "get embeddings fast" tool in search and retrieval pipelines. Because training and serving are split — heavy counting offline, cheap vector lookup online — CBOW embeddings end up in products that must answer in milliseconds on modest hardware, from document similarity in knowledge bases to feature vectors for recommendation models.

4.4 Softmax and Sigmoid: Purpose and Difference

4.4.1 The Exchange

A question about the difference between sigmoid and softmax led to a useful clarification, since softmax returns later with contextual word embeddings.

Q: What is the difference between sigmoid and softmax, and what is the use of each?

A: Sigmoid outputs a value from 0 to 1, so it gives a categorization for a single input — one number, one verdict, perfect for binary decisions like "real pair or fake pair" in SGNS. Softmax is used for multi-class problems: it is the exponential of one value divided by the sum of all the other exponential values. It takes a whole vector of scores and turns them into a set of probabilities that compete with each other.

That last word — compete — is the heart of the second question, which followed immediately.

Q: What is the point of doing this? How do you get the "highest" probability?

A: Because you divide by the sum of all the probabilities. If one option has value 0.1 and another has 0.2, you divide each by the sum of all of them. After substituting into the formula you get probabilities for all the options, and they all add up to 1 — that is the whole idea. Suppose the output vocabulary has ten options, to . All ten probabilities will add to 100%: this one has 10%, this one has 12%, and so on. Whichever is highest among all of them is predicted as the target word.

The division by the sum is not decoration: it is what makes the ten numbers a genuine distribution — each value is a share of the total, so the shares sum to 100%, and "the biggest share" becomes a meaningful way to pick one winner.

4.4.2 The Formulas, Side by Side

Sigmoid — one input, one output. For a single real number (a score, a dot product):

The output is always between 0 and 1. Big positive pushes the output toward 1; big negative pushes it toward 0; gives exactly 0.5. Sigmoid answers: "how sure are you, on a scale from 0 to 1, that this one thing is true?" In SGNS it scores one word pair at a time.

Softmax — many inputs, one distribution. For a vector of scores , one score per class, the probability of class is:

The numerator exponentiates one score; the denominator sums the exponentiated scores of all classes (the index runs from 1 to ). Every lies between 0 and 1, and all of them sum to exactly 1. Softmax answers: "across these options, what share of confidence goes to each?" In CBOW, the options are the words of the vocabulary.

The relationship. Softmax is the multi-class generalization of sigmoid. With only classes, writing the score difference as , softmax reduces to — the sigmoid of the difference. That is why the lecture can use sigmoid for SGNS's binary game and softmax for CBOW's vocabulary-wide game; they are the same shape at different scales.

4.4.3 Worked Example with Numbers

Softmax over three classes. Suppose a tiny vocabulary gives raw scores . Exponentiate: , , . Sum: . Divide each by the sum:

The three probabilities add to 1.000 (up to rounding), and the third option wins with about 67%. Predicted class: .

Sigmoid on two scores. The same inputs through the binary lens: score the difference , then — class 3 beats class 2 with 73% confidence, the binary view of the same comparison.

Sense check. Probabilities are all in , the softmax outputs sum to 1, the highest score receives the highest probability, and the sigmoid result of 0.73 matches the "two-class softmax" reading of the same numbers.

4.4.4 Why CBOW Uses Softmax

CBOW uses softmax at the output side for predicting the target word. The number of output options equals the unique vocabulary size. The softmax turns the raw scores into a probability distribution over all possible target words, and the maximum is picked. For CBOW there is no exam math problem — the intuition is what matters: softmax gives you one probability per vocabulary word, all positive, all summing to one, so "the word with the highest probability" is a well-defined choice.

4.4.5 Assumptions and Pitfalls

Scope. Sigmoid judges one candidate against a fixed threshold-free scale; softmax judges many candidates against each other. If a new candidate is added, sigmoid scores for the old candidates do not change, but softmax scores do — the denominator grows, so every share shrinks a little. The two tools answer different questions; do not expect sigmoid outputs to sum to 1 across classes.

Pitfalls.

  • Using sigmoid for multi-class prediction: ten sigmoids can all output 0.9 at once, which is nonsense as a distribution.
  • Using softmax for a binary decision where you only need one scalar — it works but wastes computation on the second class.
  • Forgetting the denominator: softmax of is not normalized to themselves; it is normalized, which slightly re-weights the two.

4.4.6 Recap and Bridge

Recap. Sigmoid squashes one score into a probability in for binary decisions; softmax exponentiates a vector of scores and divides each by the total, producing competing probabilities that sum to 1 for multi-class decisions like choosing the target word in CBOW.

Bridge. Embeddings trained by these scores are vectors — and vectors support arithmetic. Next: what happens when you do math on words, like king minus man plus woman.

Real-world placement: this same softmax is the final layer of virtually every modern language model — GPT, Whisper, and friends all emit a softmax distribution over their vocabularies and sample or argmax from it to choose the next token. The lecture's "ten options adding to 100%" is, scaled to 50,000 tokens, the exact mechanism that generates every word you have ever seen an LLM produce.

4.5 Word Vector Arithmetic, Analogies, and t-SNE Visualization

4.5.1 Visualizing the Vector Space

A t-SNE plot is a standard way to look at the whole vector space. It is a nice interface, similar in spirit to matplotlib, showing the words with color coding so you can see which words are similar to each other. These plots are commonly used because they help immediately. GloVe ships with exactly such a visualization.

What does such a plot look like? Imagine a 2D scatter plot where each dot is a word. The horizontal and vertical axes have no simple names — t-SNE squeezes a 300-dimensional space down to two dimensions while trying to keep nearby neighbors together, so the axes mean "position in the squeezed map", not a real feature. You see clusters: months of the year in one corner, countries in another, verbs of motion bunched nearby. Color coding separates word classes so the clusters jump out at a glance. The landmark to notice is not any single dot but the gaps between clusters — words with related meanings fall into the same cloud, and unrelated words are separated by empty space. The takeaway: if similar words look close on the plot, the embeddings are healthy; a plot with no visible clusters signals a poorly trained or badly chosen space.

4.5.2 Math on Words

The beauty of vector word embeddings is that you can perform math operations on words just like you do on numbers. This vector translation of words lets you combine and subtract meanings. If you want the word embedding of queen, you can take the vector embedding of king, subtract the embedding of man, and add the embedding of woman:

The arithmetic with tiny numbers. Suppose a toy 2-dimensional space holds , , and . Then

If the trained space stores , the nearest vocabulary vector to is queen — the analogy is solved by plain addition and subtraction. Sense check: the subtraction removed the "male" direction and the addition brought in the "female" direction , which is exactly the change that turns king into queen; the result does not need to match exactly, only to land closer to queen than to any other word.

The same trick infers relations: given the relation between grape and wine, you can infer the analogous relation between apple and tree, because the word embeddings lie close to each other. This is why vector representation of words is extremely useful in many real-world applications.

4.5.3 Why the Arithmetic Works

Meanings live in directions, not just positions. The vector space does not only store which words are similar — it stores how they differ. Because "king" and "queen" appear in nearly identical sentences except for gender words nearby, the difference points along a consistent "royalty-gender" direction, which also nearly matches . Training has aligned these difference vectors, so algebra along them works:

starts from "king", removes the male direction, adds the female direction, and lands near "queen". The same mechanism gives the relational inference in the lecture: grape is to wine as apple is to tree. If the vector (the "made from" direction) is parallel to , then knowing three of the four words lets you find the fourth by simple addition and subtraction.

Scope: the arithmetic is approximate and directional. The result is not exactly the vector of "queen" — it is the nearest vector in the trained space, so the real procedure is: compute the target vector, then find the vocabulary word whose embedding is closest (highest cosine similarity). The trick works only for relations that show up consistently in the corpus — famous pairs like country–capital and singular–plural align well; obscure or corpus-dependent relations do not.

Pitfalls.

  • Expecting exact equality: the formula gives , not , and the correct answer is whatever the nearest-neighbor search returns.
  • Forgetting the subtraction order: lands nowhere sensible; directions have signs.
  • Reading too much into a t-SNE plot: t-SNE preserves neighborhoods, not distances, so two far-apart dots may simply be mid-sized gaps squeezed out of view; clusters are meaningful, distances across the whole plot are not.

4.5.4 Real-World Use

Analogy arithmetic is a standard quality check for word-embedding models, and the t-SNE visualization is how these vector spaces are explored interactively. When a team publishes a new embedding model, its score on analogy test sets (thousands of "king : queen :: man : ?" style questions, answered by nearest-neighbor search) is one of the first numbers reported — it proves the space has learnable structure, not just memorized clusters. In production, the same arithmetic powers lightweight semantic tools: rewriting a search query by moving it along a known direction ("cheap" minus "expensive" applied to a product vector) without retraining anything.

4.6 GloVe: Global Vectors for Word Representation

4.6.1 Global Vectors

GloVe is not a complicated concept. Its full form is global vectors for word representation. Recall that we have seen two methods of word embedding: the frequency-based approach using TF-IDF (basically calculating the frequency of different things), and the prediction-based approach with denser word vector representations. GloVe combines both — it combines counting with prediction, which is probability.

The hook: two families, one blind spot each. Count-based methods (TF-IDF) see the whole corpus but produce sparse vectors that handle analogies poorly. Prediction-based methods (skip-gram, CBOW) build lovely dense vectors but only look through a tiny window and never see the corpus as a whole. GloVe's bet: first count everything, then train vectors to match those counts — the best of both worlds in one model.

Skip-gram and CBOW only look at the plus/minus 2 context window for each word; they never look at the entire corpus. GloVe counts the co-occurrence of the entire vocabulary across the whole corpus, then uses unsupervised learning. The algorithm was developed at Stanford, and it captures both global and local statistics from the corpus. To start, you build a co-occurrence matrix for all the words in the vocabulary.

4.6.2 The Co-occurrence Matrix

For a toy corpus — say three sentences, standing in for the millions and trillions of sentences of a real corpus — first pick out the unique words. Then build a matrix that captures the co-occurrence of every unique word with every other unique word, within a context window of plus/minus 2 words. In the real world these counts can reach or more; with three sentences they stay small. This is just counting, and machines are very good at number crunching, so no fancy calculation is needed.

This reuses the co-occurrence concept from the earlier discussion: in that example, pie and cherry appeared together 42 times within a window of plus/minus 4 words in the training corpus. GloVe uses the same counting concept. High co-occurrence means the words are semantically related to each other; low co-occurrence means they are not. That is how context is captured in GloVe.

The matrix in one concrete picture. Imagine a square grid whose rows and columns are both the vocabulary. The entry counts how many times word appeared inside word 's window, across the whole corpus. For a mini-corpus like "I like cats. I like dogs. I love dogs." with a window of 1, the matrix has rows and columns {I, like, love, cats, dogs} and entries such as (like appears next to I twice) and . A row of this matrix is the word's signature of company — the full, corpus-wide list of who it hangs around with, which no local window scan ever sees at once. That is the "global" in Global Vectors.

4.6.3 Conditional Probabilities and Ratios

The next step is conditional probabilities. For a word and a conditioning word :

where is the number of times and co-occur within the window, and is the total count of in the training corpus. For example, the probability of "solid" given "ice" is the count of solid and ice occurring together — 180 in the worked example — divided by the number of times ice occurs in the training corpus, because ice can occur with words other than solid. The more this probability grows, the more related the two words are.

Sometimes you want to distinguish which of two words is more related to a third word: is "solid" more related to "ice" or to "steam"? Take the ratio:

The worked numbers: divided by , which gives about 8.9. Since the ratio is much larger than 1, solid is more related to ice than to steam. The same table shows water: , and fashion: 0.96. Both are close to 1, but water scores higher than fashion, so water is more related to ice than fashion is.

The ratio computation, step by step.

(Dividing the rounded table values gives about 8.6; the standard table quotes 8.9 from the unrounded counts — both readings are far above 1.) For the other probes the same division gives for water and for fashion. Sense check: solid's ratio above 1 means solid sides with ice; water's ratio near 1 means water sits with both ice and steam and cannot tell them apart; fashion's near-1 ratio means it belongs to neither. These ratios show exactly which words should lie in the same semantic space and which should lie away from each other. Larger ratios mean more related.

In this way GloVe captures both things: the global counts using all the words in the corpus, and the local context for each word. That is why this approach is said to capture both global and local statistics. Yet it uses only counting — there is no training as such, unlike CBOW and SGNS. There is no question of partial derivatives; nothing like that is done to compute the vectors. The counting part is the global statistics, computed across the entire training corpus. When you calculate probabilities and ratios, that part is local only.

4.6.4 Why Ratios Beat Raw Probabilities

Raw probabilities are noisy; ratios isolate the signal. Look at the four probe words against ice and steam:

Probe word Ratio
solid 8.9
gas 0.49
water about about 1.36
fashion about about 0.96

Both ice and steam co-occur a lot with "water", so the raw probabilities for water are large in both columns — but that tells you nothing about how ice differs from steam. The ratio filters out that shared background: solid's ratio of 8.9 says "specifically ice", gas's ratio of 0.49 says "specifically steam", and the near-1 ratios of water and fashion say "either both or neither — no distinguishing signal". The ratio is the local, contrastive statistic; the counts behind it are the global statistics. That division of labor is the whole GloVe idea. (Note: dividing the rounded values and gives about 8.6; the standard table quotes 8.9 from the unrounded counts, so both readings point the same way: strongly ice-related.)

4.6.5 Student Questions

Several questions came up around the counting window and the ratio table; the four distinct confusions are kept below.

Q: Here we are checking whether solid comes with ice in the context region, like plus/minus two. Right?

A: Yes. First we come up with the co-occurrence, where we count the plus/minus 2 words and how many times they come together. Next we find the probabilities. First we count how many times they occur together — co-occurrence frequency across the entire training corpus. After that we try to predict the probability of the word solid given the word ice. So it uses both co-occurrence frequency of the words and the probability. The counts all come from the training data: once the co-occurrence is there, the conditional probabilities follow, and then we calculate the ratios of the probabilities to get the words that are similar to each other and closer to each other.

The next confusion was about where the headline number came from.

Q: How did we arrive at this value, the 8.9?

A: This ratio is pre-calculated: divided by . The value comes from dividing this with this, and the probabilities are pre-calculated from the training corpus. No training step produces the ratio — it is arithmetic on counted data.

The most discussed row of the table was gas, and it led to a correction worth remembering.

Q: How is gas related to steam but not ice? I am a little confused there.

A: In this ratio the numerator has ice and the denominator has steam: . If we had taken the reverse, we would get a bigger value. The probability of gas given ice is much less than the probability of gas given steam. So if you invert the ratio — — you get a value larger than 1, which means gas is more related to steam than ice. The direction of the ratio decides the verdict; a ratio below 1 with ice on top is the same fact as a ratio above 1 with steam on top.

The remaining questions were about reading the near-1 rows and the table's scope.

Q: Between water and fashion, both are very close to 1. Water has 1.36 and fashion has 0.96. And can we say that whenever the division value is less than 1, the denominator word is the more related one?

A: Yes, water is also related to ice and steam — a ratio near 1 means the probe word does not distinguish the two. It should not be close to 1; it should be bigger than fashion's value. If you are taking a larger corpus, the ratio being larger shows that the words are more related. Among these four words, solid is most related to ice, gas is least related to ice, and fashion is also not related to ice. As for the "less than 1" rule: generally, no — we don't do that. We take numerator divided by denominator for all the words and compute the probabilities. If this value is larger — greater than 1 — we say they are related. If it is smaller, we say they are not related. It depends on the counts in your training corpus; for some words there may be very few counts, so the raw probabilities may not be a good enough indicator. That is why we take the ratios.

One more structural question closed the topic: why only ice and steam on the left side?

Q: GloVe stores the global relations as well as the local ones. How are both combined to form a single representation?

A: The final value you take as the vector word embedding for each word is the probability values you get; that word embedding carries the combination of both meanings. The mathematical detail of how the vectors are combined will be shown with an example in a later recap — there are no math problems on this for the final exam, which is why it was skipped today. A word document with a full CBOW example will also be shared.

A note on scope for that last answer: ice and steam are only a running example with a smaller number of words. You repeat the same counting and ratio procedure for all your words in the training corpus — every pair of words gets its own ratio table, which is exactly why the co-occurrence matrix has to be computed once, globally, before any vectors exist.

4.6.6 Recap, Exam Note, and Real-World Connection

Recap. GloVe counts co-occurrences over the whole corpus (global statistics), converts them to conditional probabilities, and reads ratios of probabilities (local statistics) to decide which words belong together — then trains vectors to reproduce those ratios, marrying frequency-based counting with prediction-based embeddings.

Exam note: no math problems on GloVe for the final exam — the mathematical derivation of how the vectors are produced is not required. The intuition (counts, probabilities, ratios, global versus local) is what matters.

Bridge. GloVe closes the static-embedding family. The lecture now pivots from representing words to scoring whole sentences: language modeling, which builds on the very conditional probabilities we just computed.

In the real world, GloVe's pre-trained vectors (trained on billions of tokens by the Stanford team) were for years the default word embeddings shipped in search, chatbots, and classifiers — and they still turn up where a fast, dependency-free, static embedding is the right size of tool. The ratio insight itself outlived the model: modern contextual models still learn by contrasting what appears together against what does not, the same ice-versus-steam logic at transformer scale.

4.7 Language Modeling: What It Is and Where It Is Used

4.7.1 The Definition

The hook: you already use one every day. Start typing a text message and your phone suggests the next word — "See you" offers "tomorrow", "soon", "later". Behind that tiny suggestion bar is the exact question this section is about: which words are most likely to come next, and how likely is a whole sentence to appear in natural text?

Language modeling is a core concept of NLP, and it came up many, many years ago — the statistical approach is today's topic, and the next session introduces neural language modeling, large language models, small language models, and prompt engineering.

What is language modeling? A first guess is "making a model understand a language", but it is more than understanding. These are generative models: given an input prompt from the user, the machine generates new tokens — answering a conversational question, making a PPT, writing code. Generation tasks are the concept of generative models, and that is the concept of language modeling.

The basic idea behind all language models — nano, edge, mini, small, large, open source or paid — is predicting a set of words given a set of previous words. It all boils down to probability, even in transformers. Given a set of words, you predict a set of new words: a next word, a sentence, a group of sentences, an article, a document, a PPT, or code. The statistical approach means finding the probability of the next set of words or tokens given a set of words or tokens — the probability of a sequence of words.

So a language model has two jobs that share one engine: score a whole word sequence (how natural does "high winds tonight" sound?) and rank the possible next words (what usually follows "See you"?). Both jobs read from the same probabilities, and the rest of this session builds those probabilities by counting text.

4.7.2 Predict or Generate?

Q: Is it prediction, kind of prediction for next word?

A: Predict is not the best name. What does ChatGPT do? It generates. These are all generative models — large language models, Gen AI with LLMs — generating new tokens, images, videos, new content for you. Given a particular set of input, the machine is able to accordingly generate the output. So "generate" is the better word than "predict" or "inference" here.

The terminology matters because the job is production, not guessing. Prediction suggests picking the one true next word; generation means creating new content one token at a time. Every modern chat assistant is exactly this loop repeated: score the next token, pick one, append it, score again. When the lecture says "generative", it points at that loop.

4.7.3 Applications

The applications number in the thousands. Most real-world applications are language-dependent, and wherever there is language there is an NLP application — that is why LLMs like ChatGPT became such a breakthrough.

  • Autocomplete of queries: the phone-keyboard example at scale — search engines and editors rank the continuations of what you typed.
  • Spell check and grammar check: compare the probability of one sequence of words against another, and suggest the one with the higher count in the training data. "About fifteen minuets" loses to "about fifteen minutes" because the second sequence is far more common.
  • Machine translation: you need to correctly translate the words. A wrong word choice changes the meaning — in the Hindi example given, translating a phrase for a strong wind must not substitute the wrong adjective (the recording has "tej hawa" — standard Hindi for "strong wind" is tez hawa — versus "jada hawa", possibly zyada hawa; the point stands either way: the adjective carries the meaning).
  • Speech recognition: statistical language modeling is widely used in audio analysis and automatic speech recognition systems like Whisper. If one transcription has more counts in the training corpus, it is the more likely correct speech-to-text. "I saw a van" beats the identically-sounding "eyes awe of an" because only one of them reads like English.
  • Next-token prediction, used for example by Google's systems, and answer generation from a web corpus for bots.

Everywhere, everything is dependent on the training data — whether it is a large language model, an agentic AI system, or statistical language modeling, it boils down to data. How good is your data? From that data you generate or predict new text.

Q: So this knowledge of the n-gram models concept taught today — can I use it to answer questions from a web corpus if I have a bot or something like that? Is this a use case?

A: Yes, you can use it. It is used — it was used in Google's systems, which also predict the next token. It was used here also predicting the next words and so on.

4.7.4 What a Language Model Is Not

Scope. A language model measures fluency, not truth. "The moon is made of green cheese" is false but perfectly fluent, so a language model scores it high. Every application above so pairs the language model with something that proposes sensible candidates — a translation system, an acoustic model, a knowledge base — and the language model only picks the most natural-sounding option among them.

Pitfalls.

  • Calling it "prediction" when the model is generating fresh text (the terminology correction from 4.7.2).
  • Expecting a language model alone to answer factual questions correctly — fluency is not factuality.
  • Forgetting that the counts come from your training data; a model trained on news text scores news-like sentences, not speech-like ones.

4.7.5 Recap, Exam Note, and Real-World Connection

Recap. A language model scores word sequences: it gives a probability to a whole sentence and to each candidate next word, built by counting in a training corpus — and generation is that scoring loop repeated token by token.

Exam note: the evaluation measures for language modeling (perplexity and friends) apply to transformers as well as statistical models and will be covered in the next session.

Bridge. To compute those probabilities we need the machinery of conditional probability — starting with what "given" means and how to chain it across a whole sentence.

Real-world placement: the perplexity tool, used widely in research papers, is built around the standard evaluation measure for these models, covered in the next session. When a new model is announced, its perplexity on a standard test set is one of the first numbers reported — it is this section's sentence probability, turned into one headline number. Autocomplete, spell check, machine translation, speech recognition, and chat assistants all rest on the same probability engine; the statistical version built today is the small, cheap, fully understandable ancestor of every one of them.

4.8 Conditional Probability, Independence, and the Chain Rule

4.8.1 Independence versus Dependence

Language modeling is built on plain probability theory, starting with conditional probability. Conditional probability is used when the outcome depends on whatever is available to you: what is the probability of something given something?

The everyday picture. Two situations from the lecture. A symptom and a disease: if you have a certain symptom, there is a likelihood of getting a certain disease — the events are linked. Or carrying an umbrella and it raining: what is the probability of you carrying an umbrella and it raining? People tend to carry umbrellas when it rains, so the events move together. Both pairs are dependent: knowing one happened changes your belief about the other. Conditional probability is the tool that captures exactly this kind of link.

If you want the probability of two events happening together, there are two cases. With an independence assumption, the two events do not depend on each other, and the joint probability of events and is simply the multiplication of both individual probabilities:

These individual probabilities are also called marginal probabilities. But when we condition, that means depends on , so you cannot simply multiply the individual probabilities to get the joint. You condition on the other event occurring:

That is: the probability of given that has already occurred. Equivalently, rearranging the same equation gives the definition of the conditional probability itself:

All three formulas say the same thing in different orders: the joint probability of two events is the probability of the first times the probability of the second given the first, and conditioning just re-weights the joint by the probability of what you already know.

4.8.2 The Chain Rule for Word Sequences

Now extend this to the language modeling problem: predicting a sequence of words. For a four-word phrase "chain rule in general", because the words of normal English depend on each other, the probability is:

We capture the context here. In language, all the words of a sentence relate to each other — you don't randomly pick words and form a sentence; that would be a garbage sentence. English works from left to right, so we calculate the probabilities from left to right, and we get a chain of probabilities. In general:

Reading the chain. is the probability that the whole sequence of words appears. It factors into pieces: the first word's probability alone, then every later word's probability given all the words before it. Each step conditions on a longer history, so the last factor needs the entire previous sentence. The chain rule is exact — nothing is approximated — but the last factors are unusable in practice: the exact history "its water is so" almost never repeats in any corpus. For hundreds or thousands of words, this chain becomes very complicated, which is why a simplifying assumption (the Markov assumption) comes next.

4.8.3 Worked Example: "its water is so transparent"

The lecture's running phrase (the recording garbles one word — "so" is heard as "soap", but the intended phrase is the one below) shows both how the chain rule works and why it is hard.

Chain rule on a five-word phrase. We want as a product of next-word probabilities. Five words give five factors:

Each factor is a ratio of counts from the corpus:

The catch. Individual words will definitely be present in the training corpus, and "its water" will be present. But for three words in sequence, all three must occur together one after another in the training corpus. As you go to a higher number of words it gets trickier: you need the entire phrase to occur. It is highly likely that this count will be 0, because the entire phrase may not exist in the corpus. In a real-world situation, whatever output the user gives may not be present in the training corpus — the individual words will be there, but not the continuous sequence. Once you get a 0, the entire probability of the phrase becomes 0, and you cannot tell whether the phrase should be given as output.

Sense check. The product form is exact: if every factor were known, the product would be the true phrase probability (a tiny positive number). The failure is not the math — it is the data: long exact histories are too rare to count.

This is the challenge that motivates the Markov assumption: computing these factors is not easy from the training corpus — computationally it is a real burden, because you need the counts — and the counts you need most (long histories) are the ones most likely to be zero.

4.8.4 Student Question

Q: Can you give an example of how we are building the model, like how you are explaining the chain rule?

A: Take the question "what is NLP?". The system will generate an answer, for example "NLP is natural language processing — a computational technique for making machines understand language" and so on. There is a sequence of words that needs to be predicted. When the machine comes up with a sequence, you need to check which sequence is correct. Using the chain rule of probabilities, first check the probability of the first word in the training corpus, then the probability of the second word given the first, then the third given the first two, one word after the other.

4.8.5 Pitfalls and Recap

Pitfalls.

  • Reversing the condition. is not : "dog bites man" and "man bites dog" use the same words but are very different sentences. The order of words matters in every chain-rule factor.
  • Multiplying marginals for dependent events. assumes independence; for words in a sentence (or umbrellas in rain), it gives wrong answers.
  • Expecting the exact chain to be computable. The rightmost factors need histories that may never occur; the chain rule is exact in theory and uncomputable in practice — which is exactly why the next section truncates it.

Recap. Conditional probability re-weights the joint ; the chain rule factors a whole sentence into one conditional per word, each given its full history — exact, but the long-history factors hit zero counts in any real corpus.

Bridge. The fix is to shorten the history: keep only the last few words. That shortcut is the Markov assumption and the n-gram models built on it.

Real-world placement: the chain rule is the generation engine of modern LLMs. When a chatbot writes a sentence, it computes , picks one token, appends it, and repeats — the product of all those steps is exactly the probability of the text it wrote. Today's models handle the long history with attention instead of exact counting, but the left-to-right chain of "given" factors is the same structure built in this section.

4.9 The Markov Assumption and n-gram Language Models

4.9.1 The Markov Assumption

Hidden Markov models came up in the deep learning course (a prerequisite call worth remembering). The idea: instead of remembering the complete set of previous words, remember a restricted set of previous words.

The everyday picture: merging onto a busy road. You mostly watch the car right next to you, not every car a mile back — the nearby car carries almost all the information you need right now. The Markov assumption does the same for words: the last one or two words carry most of the signal, so the distant history is dropped on purpose.

In the Markov assumption, the current word is not dependent on the complete set of previous words, but on some set of previous words. Instead of looking at the whole history, you look at the previous one word, previous two words, or previous three words. In symbols, the exact chain-rule factor,

is replaced by a short window of the last words:

The symbol means "is about equal to": it is an approximation, not the truth. Some real sentences do depend on far-back words, and the model accepts a small error in exchange for counts that actually exist. Instead of all previous words, you approximate with the previous words. This is a simplifying assumption that makes computation easier and better.

The value of depends on your training data. Usually is taken as two or three previous words, because those combinations are highly likely to occur in the training corpus. Combinations of five or six words are much less likely to be present, so we don't go that far.

4.9.2 Unigram, Bigram, Trigram

These are called n-gram language models: an n-gram is a sequence of tokens or words on which the current word depends. The number counts the words in the window including the word being predicted, so each model keeps previous words.

  • Unigram: . The current word does not depend on any previous word; its probability depends only on itself:

In practice unigram is of hardly any use, because a real sentence has dependencies between words — it is mentioned for completeness.

  • Bigram: . The current word depends on one previous word, since two words appear in the probability function:

  • Trigram: . The current word depends on the two immediately previous words:

The same pattern extends to 4-grams, 5-grams, and so on. Sometimes English sentences have longer dependencies, where the last word depends on the first or second word after five or six words. The n-gram model cannot capture those because the combination will not be in the training data — the attention mechanism, covered with neural language modeling, handles longer context.

Trigram preview with the toy corpus. In the three-sentence corpus counted in the next section, the trigram probability of "Sam" given the previous two words "I am" is

"I am Sam" occurs once, "I am" occurs once, so the probability equals one over one. Sense check: a trigram needs the exact pair of previous words — the denominator is the count of that pair, not of the single word "I". One full counting pass over that same toy corpus appears in 4.10.

4.9.3 Start and End Symbols

Extra start and end symbols are generally used in NLP applications to indicate the start and the end of the sentence. Some algorithms use tags like opening and closing <s> and </s>, others use a star symbol, and current transformer architectures use CLS for the start of a sentence and SEP to separate sentences. These tokens are automatically introduced when you do language modeling. The reason: for the first word of a sentence, the bigram needs a previous word, and without a start tag you would not know which word is first. A trigram needs two start symbols before the first word.

4.9.4 Student Questions

Q: Why do we look for the probability of I given start? Why not just predict the next word?

A: Because we want to know whether I occurs at the beginning of the sentence. Order is important. "Am I Sam" has no meaning; we want to ensure I comes at the beginning, so we check whether it has a start symbol before it. The start symbol lets the model learn which words actually begin sentences.

A second question was about the other boundary: when generation should end.

Q: How does the model understand when it should stop generating?

A: By default there is a token limit, generally in ChatGPT. You can mention "give me the answer in five words" and the algorithm will restrict the output. Otherwise there are default token limits — with the open-source free tiers you get a message that you have exhausted your tokens. These limits govern how many tokens the system generates.

The most important question of the set was about how much context a trigram really uses.

Q: In the trigram case, do we look at exactly the previous two words?

A: Yes, you look at the previous two words and see how many times those two words occur together. For example, how many times "I am Sam" occurs, divided by how many times "I am" occurs. And the order must be remembered — order is extremely important in language modeling, because otherwise the sentence is garbage. "Ham and eggs green like not I do" is gibberish; the same words in order make a proper sentence. The defining factor is : if , the word is conditioned on the one previous word; if , on the previous two; if , on the previous three, and so on.

Zero counts came up twice more, about denominators and about production.

Q: What if the denominator becomes zero — what if there is no occurrence of the previous word?

A: Then you don't count that bigram; you count bigrams and trigrams only for words that occur. The zero-value problem is handled with the same smoothing concepts from naive Bayes — Laplace smoothing — coming up shortly. Because of the zero probabilities in the corpus, later we combine bigram, trigram, and 4-gram probabilities using linear interpolation. For now, look at one at a time — bigram, trigram, or unigram. Unigram is normally not considered; either bigram or trigram.

A bridge question connected today's strings to the earlier vectors.

Q: Can we link this to the word-to-vector discussion, converting words to vectors and finding relations among words?

A: Don't do that yet. That is neural language modeling, where words are converted to vectors and relations among the words are found. Here the words are just strings of letters, not vector embeddings. The same concept will be applied with vectors in the neural language model next session — for now, treat words as strings.

Q: Up to 4-grams — are 4-grams used in production?

A: Yes, it depends on the training corpus. 4-grams give more context than trigrams, but generally we restrict to trigrams because most 4-grams and 5-grams may not be present in the training corpus, and then we have the zero-count challenge again. That is why bigrams and trigrams are the norm, though people do go for 4-grams as well.

4.9.5 Scope, Pitfalls, and Recap

Scope. The Markov assumption is an approximation: it works well for the kind of text where nearby words dominate (most of it), and it fails where the decisive word sits far back — "The computer which I had just put into the machine room on the fifth floor is crashing" needs a window of ten words to pick "is" over "are". No small n-gram can see that far; neural models with attention exist to fix exactly this.

Pitfalls.

  • Treating the shortcut as the truth — longer real dependencies silently get the wrong probability.
  • Forgetting word order in the counts: and are different numbers.
  • Going too high in : the longer the phrase, the rarer it is, so most 4-gram and 5-gram counts are zero.

Recap. The Markov assumption truncates history to the last words; an n-gram model keeps the last words (unigram keeps none, bigram one, trigram two), and start/end symbols make sentence boundaries countable.

Exam note: word order in n-gram calculations is extremely important — an exam-ready point repeated many times.

Bridge. With the model defined, the only job left is to estimate its probabilities by counting — the MLE formula and the three-sentence toy corpus come next.

Real-world placement: classic n-gram models are pure Markov models — fixed short windows — and they remain the go-to for fast, cheap text scoring on limited hardware: keyboard suggestions, SMS autocorrect, and domain-specific command systems. Modern neural models broke the -word limit with attention, which is why the lecture repeatedly points forward: the Markov assumption is the simple baseline that later models were built to beat.

4.10 Bigram Probabilities: MLE Estimation and the Toy Corpus

4.10.1 The MLE Formula

The maximum likelihood estimate (MLE) for a bigram comes straight from the training corpus. Count how many times comes after , and divide by the count of (because that word can occur with other words too):

Read it as "count and divide". The numerator is how many times the pair appears in that exact order; the denominator is how many times the first word appears at all. The name "maximum likelihood" means this fraction makes the training text as likely as possible — for our purposes, "count the pair, count the first word, divide". Lots of notations are used for the same thing, but the count is all you need.

One rule before any calculation: when you do bigram, trigram, or any n-gram calculations, the order of the words is critical. The probability of I given am is different from the probability of am given I — the pair "am I" is counted separately from the pair "I am".

4.10.2 The Three-Sentence Corpus

The toy corpus for practice has three sentences with start and end symbols:

  1. <s> I am Sam </s>
  2. <s> Sam I am </s>
  3. <s> I do not like green eggs and ham </s>

(The third sentence is reconstructed from the spoken counts in the lecture; its words — do, not, like, green, eggs, and, ham — are exactly the ones that appear in the discussion, each occurring once.)

The counts. From this corpus the counts follow: the start symbol <s> occurs 3 times (three sentences), I occurs 3 times, Sam occurs 2 times, am occurs 2 times, and each other word once. Now compute each bigram probability:

  • : I comes after the start symbol twice, and the start symbol occurs 3 times.
  • : only sentence 2 starts with Sam.
  • : I occurs 3 times, and "I am" occurs twice (sentences 1 and 2).
  • : "do" follows I once, in sentence 3.
  • : am occurs twice, and am comes before Sam once (sentence 1).
  • : Sam occurs twice, and the closing tag comes after Sam once (sentence 1 ends with Sam).
  • : am occurs twice, and sentence 2 ends with am.

Sense check. All the probabilities that follow a given word add to 1: after I comes am (2/3) and do (1/3), and ; after the start symbol come I (2/3) and Sam (1/3). Every row of a bigram table must sum to 1.

Trigram from the same corpus: , since "I am Sam" occurs once and "I am" occurs once. For the second sentence, — the trigram depends on which word you are trying to predict.

4.10.3 Student Questions

Q: The end tag — I see the start symbol is present in three sentences and Sam is only present in two, so isn't the end tag given Sam going to be 1 divided by 3?

A: Order is important, and this example is chosen on purpose. Here the previous word is Sam, not the start symbol: Sam is the and the closing tag is . Sam occurs twice in the corpus, and the closing tag comes after Sam once. So it is 1/2.

A closely related question was about the denominator in the other direction.

Q: In the third sentence there is no Sam and no am, but why is the denominator for Sam given am 2 and not 3?

A: The denominator is 2 because we count the occurrences of am, which is . Am occurs twice, and am comes before Sam once, so it is 1/2. If am had occurred four times in the corpus, the denominator would be 4, and the same numerator-over-denominator rule applies. The same logic answers "why is the denominator for do given I equal to 3?" — you count how many times I occurs: one, two, three — that is , so it is 3.

The last confusion was about what kind of probability this is.

Q: One point on the probability definition: it usually measures whether a word has occurred or not, but here we check whether it occurred after this word.

A: Right — we are looking at conditional probabilities. If you just count , you see whether it has occurred or not — that is unigram, and the probability of the start symbol would just be 3 out of the total words. Here we check the word given that this word is the previous word, so this probability is different from the unigram one.

4.10.4 Pitfalls, Exam Note, and Recap

Pitfalls.

  • Dividing by the wrong count: the denominator is the count of the previous word, not the total number of words and not the sentence count.
  • Swapping the pair's order: in this corpus, while — same words, different numbers.
  • Confusing conditional probabilities with unigram probabilities: conditioning changes the denominator, so the two are genuinely different quantities.

Recap. The bigram MLE is count of the pair over count of the first word: , verified by hand on the three-sentence corpus where every row of probabilities sums to 1.

Exam note: when a table of counts is given in the exam, it will be specified which is the next word and which is the earlier word (row versus column).

Bridge. Three sentences are easy to count. The next section scales the same counting to a real 9,222-sentence corpus, multiplies bigrams into sentence probabilities, and meets the zero-count problem head-on.

Real-world placement: this hand count is exactly what a training pipeline does on billions of words — build a giant table of which word follows which, then normalize each row into probabilities. The table is the model. Everything downstream, from a speech recognizer choosing between transcriptions to a keyboard suggesting the next word, is a lookup in that table followed by multiplication.

4.11 Sentence Probability, Logs, and the Zero-Count Problem

4.11.1 A Bigger Corpus

Scale up to a larger toy corpus: 9,222 sentences from a restaurant-information system. The bigram table gives counts of the next word given the previous word — next word on the rows, previous word on the columns. There is some noise in real training data: grammatically incorrect sentences produce odd counts, like I coming after I five times. Want coming after I occurs 827 times. The preposition "to" coming after I occurs 0 times (generally a preposition does not come after I). Eat coming after I occurs 9 times. There are many 0 values in this table.

To turn raw counts into probabilities, use the unigram counts — the number of times each word occurs in these 9,222 sentences. The count of I is 2,533. The probability calculation uses the same formula as before: the joint occurrence divided by the unique occurrence. For example:

Do this for every word. Some entries are 0 in the numerator, so their probability is 0. The method does not change with size — it is still count and divide — the numbers are just messier now.

4.11.2 Multiplying Bigram Probabilities

To score a whole phrase, multiply the individual bigram probabilities under the Markov assumption. For "I want to eat Chinese food", some of the needed bigrams are zero in the corpus, so the entire sentence probability becomes 0. For a phrase like "I want English food" the pieces exist, so the sentence probability is easy to compute:

Sentence probability for "I want English food" with start and end symbols. Write the chain of bigrams, substitute the table values, and multiply step by step:

Final answer: . Sense check: tiny and positive — every full sentence is rare, but this one is possible, so it sits above zero.

The contrast. "I want to eat Chinese food" needs , and the pair "to food" never appears — that single zero makes the whole sentence probability 0, even though the sentence is perfectly good English. For the sentences where the probabilities come out zero, we get a problem: a whole sequence is rejected because one bigram is missing. That zero problem is solved with smoothing, next section.

4.11.3 Logs Avoid Underflow

One more practical issue before smoothing. Instead of multiplying the raw probabilities, which can get a diminishing value — probabilities like , or for longer sequences — we squash the values by taking the log. This avoids underflow: we take the log of all the probabilities, and instead of multiplication we just add the log probabilities. Addition is always less expensive computationally than multiplication for the machine, which is another reason this is better. Everywhere, including transformers, log is taken to reduce the computations:

Why logs work. The log of a product is the sum of the logs: . Probabilities are between 0 and 1, so their logs are negative numbers of ordinary size — is about , a comfortable number for any computer, where the product itself is a sliver that gets rounded to 0. Since log is monotonic (bigger probability means bigger log), comparing or ranking sentences in log space gives the same order as the raw probabilities. Two wins for one transform: no underflow, and cheaper arithmetic.

4.11.4 Ready-Made n-gram Corpora

You don't need to compute these counts yourself. A lot of free n-gram datasets are available — for example the Google web corpus, a large repository with counts of all possible combinations of words, ready-made for applications. You can see the counts of 4-grams occurring together, like every continuation of "serve as the" with its own tally. For domain-specific work (medical or finance), the open-source generic English datasets (Wikipedia and others) may not fit, but otherwise they are freely downloadable and easy to use. Even web-scale counts run out — most possible long phrases were still never written — so zeros never fully disappear; scale reduces the problem but does not remove it.

4.11.5 Student Questions

Q: Sentence completion — do we use n-grams or bigrams there as well?

A: Yes, this works for any number of words. To predict the next word, compute the probability of "me" given the earlier words, then "about" given those, and so on. To generate the full sentence, the model is actually computing one by one — predicting the next token, next token, next token.

A follow-up asked about predicting two words at once.

Q: Can we have the probability of two words at once, like "me about" given the earlier words?

A: You would need "me about" in your training data — you would treat them as a single word and check the occurrences. You can do that, but you should have that count. Generally one word at a time is done, because you have that corpus. Two words at a time boils down to the same problem — the phrase must occur in the corpus — which is exactly why we make the bigram assumption: to make counting and data availability easier.

4.11.6 Pitfalls and Recap

Pitfalls.

  • Hard zeros. A zero is not "very unlikely"; it is "cannot happen", and in a product one zero destroys the whole sentence score. Smoothing exists to convert zeros into small positives.
  • Underflow blindness. Multiplying 30 probabilities of 0.2 each gives about — many programs round that to exactly 0, silently erasing the sentence. Use logs.
  • Log sign confusion. Logs of probabilities are negative; "higher log-probability" means closer to zero (less negative), not a bigger probability gap in the wrong direction.

Recap. Sentence probability is the product of bigram factors; real corpora contain zero counts that make the product zero, and logs turn the fragile product into a strong sum — the standard trick used everywhere, transformers included.

Bridge. Logs fix the arithmetic but not the zeros. The next section attacks the zeros directly with Laplace smoothing, the first of three repair tools.

Real-world placement: log-space scoring is the everyday language of model training — the cross-entropy loss used by modern neural networks is an average of negative log-probabilities. The restaurant-corpus counting here and a GPT's training objective are the same family of computation, separated by sixty years and six orders of magnitude.

4.12 Laplace (Add-One) Smoothing

4.12.1 The Add-One Formula

The zero problem: I have the words "offer" and "loan" individually in my training data, but not in that sequence, so the bigram probability is 0, and any sentence containing it scores 0. To avoid the 0 probability, Laplace smoothing adjusts the MLE counts: add 1 in the numerator and add the vocabulary size in the denominator:

where is the number of unique words in the training vocabulary.

The everyday picture: a teacher's free mark. A teacher gives every student one free mark before grading. A student who scored zero now has one mark, not zero; the top students barely notice the change. The "add one" is that free mark — every pair is imagined to have been seen one extra time, so no pair can have count zero.

Why divide by , instead of just adding 1 in the numerator? Two reasons. First, a probability should be between 0 and 1, and dividing keeps the smoothed values in that range. Second, balance: when you add 1 in the numerator you affect the counts, and to balance that and generalize it so the counts are not too large, we divide by the entire vocabulary size. The count becomes close to 0, but it is not exactly 0 — and dividing by the vocabulary avoids giving too much significance to the zero-count words. If you divided by 1, you would manipulate the data far more.

There is a deeper reason the denominator grows by exactly : we added 1 to each of the possible next words, so the row total grows by , and adding the same below keeps each row of probabilities summing to 1. Note the numerator update applies to every count, not just the zeros: 827 becomes 828, 5 becomes 6 — all the counts are updated by 1 in the numerator, and the vocabulary is added in the denominator.

4.12.2 Worked Numbers

For the running example (the restaurant corpus has vocabulary size unique words — the number needed to reproduce the lecture's rounded values):

The smoothed table, row by row. Using :

  • : raw falls to .
  • : raw count 0 lifts off the floor: .
  • : raw becomes .

All the blue values that were 0 before are now slightly non-zero but close to 0. That is the advantage Laplace smoothing gives: no pair can ever kill a sentence with a hard zero again.

Sense check. Each smoothed row still sums to 1 (the numerator additions and the in the denominator balance exactly), every probability sits in , and the previously impossible "to after I" now carries a tiny but real mass.

4.12.3 The Blunt-Instrument Problem

There is a problem with Laplace smoothing. The counts have been manipulated, and the change is large. If you take the smoothed probability and try to recover the counts — multiplying the smoothed probability by the denominator count — the "counts" you get back are substantially changed. The original count was 827, and the adjusted count comes out as about 527:

Laplace smoothing is a blunt instrument. The pair "I want" fell from a real count of 827 to an effective count of about 527 — roughly 300 real sightings were handed over to unseen pairs. With a vocabulary of tens of thousands, the in the denominator swamps the real counts even harder. So: useful if you have a small number of zeros in your input dataset, and it is definitely used widely in text classification — but normally you should avoid blind add-one smoothing in a real-world scenario. That is why other techniques exist: backoff and interpolation.

Just by doing Laplace smoothing, you are manipulating the data quite a lot, and you don't want to do that. The lesson is to match the strength of the fix to the size of the problem: over-smoothing hurts, just like too much regularization in a neural network underfits.

4.12.4 Student Questions

Q: In that table these are probabilities, so the counts should not change, right? Where did this 527 number come from?

A: The original counts themselves are not updated — you only update the probabilities. But when you compute the new probabilities from the original ones (the original was 0.33, the new probability is about 0.21), in terms of probability you cannot see the difference, so we show it in terms of counts. Take the updated probability formula — adding 1 in the numerator and the vocabulary in the denominator. The actual probability formula is the MLE one. If you want to get the counts back, multiply the smoothed probability by the count. For want given I: 527 divided by the count of I, 2533, gives the 0.21 value. The point of showing 527 is that the data has been manipulated to a large extent, which is not a good idea in a real-world scenario.

Q: In Laplace smoothing we took in the denominator. Could we have used 1 in the denominator?

A: No — that would further manipulate the data more. Because is large in number, we at least get probabilities that are close to zero rather than far away from zero. Dividing by the vocabulary makes more sense: a large number in the denominator and a small number in the numerator means the effect is lesser — you are not tampering too much.

4.12.5 Scope and Recap

Scope. Add-one is the right tool where zeros are rare: text classification (naive Bayes) uses it as a standard, clean default. It is the wrong tool for n-gram language models, where the vocabulary is huge and zeros are everywhere, because the term moves too much probability away from common pairs. "Add-one is bad" is true for n-grams and false for classification — the right smoothing depends on how many zeros you face.

Recap. Laplace smoothing adds 1 to every pair count and to every denominator: . It kills every zero, but at the price of heavy distortion — the reconstituted count for "I want" drops from 827 to about 527.

Bridge. The gentler fixes drop the "add to everything" idea: backoff steps down to shorter contexts only when needed, and interpolation blends all orders with weights — the topic of the next section.

Real-world placement: the same add-a-little-to-everything trick reappears across machine learning under other names — pseudo-counts in Bayesian models, label smoothing in neural networks, and the standard naive-Bayes text classifier's smoothing. Recognizing it in its n-gram form (and knowing when its distortion is acceptable) is the transferable skill here.

4.13 Interpolation and Backoff

4.13.1 Linear Interpolation

To avoid zero probabilities without the heavy manipulation of add-one smoothing, use interpolation or backoff — both are easy and similar to each other. In interpolation, we mix the probabilities of all three orders instead of focusing on only one. If the corpus has trigram counts, use those; if not, use the bigram counts; if not, use the unigram counts. The mixing weights are the lambdas:

The lambdas give importance to the trigram, the bigram, and the unigram respectively: multiplies the trigram term, the bigram, the unigram. They must add to one because this is like a probability:

Why blend all three every time? Even when the trigram count is 0, the bigram and unigram terms still contribute, so the blended estimate is never zero as long as the unigram is positive. The weights say how much to trust each order: more context deserves more trust. Example values from the lecture: , , — more importance to the trigram, which captures more context. Another spoken suggestion: about 0.9 and about 0.001, just to avoid zero probability. These lambdas are hyperparameters given by the user during language modeling. You can also learn these lambda values from held-out training data, just like cross-validation in machine learning, instead of setting values like 0.05 or 0.01 by hand.

4.13.2 Worked Example: A B C D

For a sentence A B C D computed with trigrams, the sentence probability is:

The first word needs two start symbols; the second word conditions on one start symbol and A; the third conditions on B and A; and so on. Normally you would calculate each trigram on its own. With interpolation, each of these individual probabilities also adds the bigram and unigram terms — the same three-formula combination for each one.

Interpolated trigram with numbers. Suppose for the word D after context B C the table gives: trigram count of "B C D" is 0, so ; bigram ; unigram . With weights , , :

Final answer: . Sense check: the trigram zero does not kill the estimate — the bigram supplies almost all of the mass, and the unigram chips in a tiny floor. Without interpolation the factor would be 0, and the whole sentence A B C D would score 0.

Training for interpolation needs samples for everything: bigram, unigram, and trigram all get counted, so if any one is zero you still have the other two to help you.

4.13.3 Stupid Backoff

Backoff is exactly similar, except that instead of taking all three, we take one at a time. If we have the trigram count, we go ahead with that. If we do not have the trigram count, we reduce the weightage by 0.4 — giving 100% weightage to the trigram when available, then 0.4 times weightage for the bigram. If nothing works, we further reduce to the unigram, and the unigram count is divided by (the total token count), so the unigram gets very little weightage:

with the final fallback , where is the total number of tokens in the training corpus.

Reading the recursion. Start at the top: if the trigram was seen, use its plain relative frequency. If not, drop one word of context, move to the bigram, and multiply by the fixed penalty 0.4. If the bigram is also unseen, drop again to the unigram and pay the 0.4 penalty a second time — the unigram score is the word's count divided by , the total token count, so frequent words get a little and rare words almost nothing. Each backing-off step discounts the score, so longer, more reliable evidence always outscores a fallback. The idea is backing off: start with the highest grams; if the count is less than or equal to 0, go to the bigram count; if that is also zero, go to the lower grams. That is why it is called stupid backoff — it is a very simple technique, deliberately so.

One honest label: is a score, not a true probability — it does not sum to 1, so it is good for ranking candidates, not for plugging into probability-based measures.

4.13.4 Comparison: Interpolation versus Backoff

Dimension Interpolation Backoff
How it combines Blends trigram + bigram + unigram every time, with weights Uses one order at a time; steps down only when the longer count is missing
Zero handling Never zero if the unigram is positive Never zero; final fallback is
Free parameters The lambdas (which can be learned on held-out data) The fixed 0.4 discount (no tuning)
Output A true probability (weights sum to 1) A score, not a true probability

When to pick which: use interpolation when you want a proper probability and can afford tuning the lambdas; use backoff when you only need to rank candidates and want a zero-parameter method — interpolation usually works better, and backoff is the simpler tool.

4.13.5 Student Questions

Q: In the case of backoff, are the lambdas dynamic or static?

A: In backoff there is no lambda at all — you are just backing off from one value to another. For the same example, first compute the trigram; if there is a count for it, substitute that in the formula. If there is no count, back off to given , and calculate that one. If that is also not greater than 0, go to the next one. There is no lambda here at all — the 0.4 is just a standard multiplying factor that reduces the weightage to the lower grams.

A follow-up asked whether the zero checks happen at runtime.

Q: Would that be at runtime — checking whether there is a count or not?

A: No, not at runtime. These counts are available at training time — all these tables are computed offline for the training data. These models are pre-computed for the web-scale data, and at runtime you just check in the model if the counts are zero and move to the next one.

The last two questions were about training data and the weights.

Q: When we train for interpolation, do we create samples for everything — bigram, unigram, and trigram?

A: Yes, we count all three — trigram probabilities, bigram, and unigram — and then do the training. If any one is zero, the other ones still help you.

Q: Which lambda has more weight?

A: Lambda one, the trigram, because it captures more context. More value for more context, and less value for the unigram. The unigram lambda usually stays at something like 0.001, just to avoid zero probability, the trigram might be about 0.9, and the remaining goes to the bigram. The three lambdas should add to one.

4.13.6 Recap, Exam Note, and Real-World Connection

Recap. Interpolation always blends all three orders with weights , so no factor is ever zero; backoff uses one order at a time and steps down with a fixed 0.4 discount to the unigram — a simple, parameter-free ranking score.

Exam note: there might be a simple problem on interpolation, but there will be no math problems on learning the lambda parameters.

Bridge. With smoothing complete, the statistical language-modeling toolkit is done: chain rule, Markov assumption, counting, zeros, and now the repairs. The next session swaps the count tables for neural networks — same objective, vector representations.

Real-world placement: stupid backoff earned its fame at Google scale — with a billion words of training data, a fast parameter-free ranking method beats a careful method that is too slow to use. The engineering lesson generalizes: a rough tool that scales can win over a precise tool that does not, which is why production systems at web scale still use variants of this "stupid" idea today.

Exam Guidance Summary

What to expect per topic.

  • SGNS: expect a numerical similar to the worked spreadsheet example — sigmoid values, errors, gradient updates, and updated embeddings with learning rate 0.05.
  • CBOW: no full numerical; a simple addition or a conceptual question, such as the difference between CBOW and skip-gram and when to use which.
  • GloVe: no math problems on the final exam for the GloVe vector computation.
  • Interpolation: a simple problem is possible; there are no problems on learning the lambda parameters.

Cross-cutting exam rules.

  • Evaluation measures (perplexity and the comparison of models) will be covered in the next session, together with applications and the code; the perplexity tool used for research papers builds on this measure.
  • When a bigram/trigram count table appears in an exam question, the question will specify which is the next word and which is the earlier word (row versus column).
  • Word order in n-gram calculations is extremely important — an exam-ready point repeated many times.
  • 4-grams and 5-grams are possible in production and depend on the training corpus, but bigram and trigram are the norm because higher orders are usually missing from the corpus.

Recall from earlier sessions.

  • TF-IDF formula variants: some books put the plus one inside the log and some put it outside. Jurafsky's latest version has with the plus one outside; Manning's has inside. It doesn't matter much — it just avoids zero. Log base 10 is more used because at web scale the vocabulary is very large; in a toy corpus the calculations are tiny either way. If a formula appears in the exam, it will be specified in the question, or you can write down which formula you are using. The version that divides by the document length is the advanced BM25, not plain TF — plain TF does not need it.

Study advice.

  • Revision is important — the material is new, and a recap will cover all the topics again; n-gram models are deliberately kept simpler so that neural language modeling is easier to absorb next session; previous-semester papers will be shared for practice.

Key Industry Applications

Static word embeddings in production.

  • Static word embeddings (SGNS, CBOW, GloVe) are low-resource, run on local CPUs, and are used in many production environments; the intuition for contextual embeddings came from them.
  • gensim implements all the static word-embedding algorithms, in the style of scikit-learn or TensorFlow; pre-trained embedding models can be downloaded like GPT or LLaMA checkpoints.
  • GloVe ships with a t-SNE-based interactive visualization of the vector space, with color-coded clusters of similar words.
  • Word-vector arithmetic (king − man + woman ≈ queen) and analogy inference (apple : tree :: grape : wine) are standard tools in embedding quality checks.

Statistical language modeling in products.

  • Language modeling powers autocomplete, spell check, grammar check, machine translation, and speech recognition systems like Whisper; statistical language models are widely used in audio analysis.
  • Ready-made web-scale n-gram corpora (for example from Google) provide counts and probabilities for generic English; domain-specific corpora (medical, finance) need their own data.
  • n-gram models remain a good return-on-investment choice for domain-specific, small-vocabulary products on limited hardware — no high-end servers needed.

Ideas that carried into transformers.

  • Transformers use start (CLS) and separator (SEP) tokens, and everywhere — including transformers — log probabilities are used to avoid underflow and to make computation cheaper.
  • Google's TPU work separates inference hardware from training hardware, reflecting the offline training versus runtime inference split of these models — the same split that makes pre-trained embeddings cheap to serve.

NLP Lecture 4 Notes · CBOW, GloVe, and Statistical Language Modeling

Natural Language Processing· postgraduate· 2026-08-13

Sections Breakdown

1Skip-gram with Negative Sampling: Recap of the Update Procedure

Recap of the skip-gram with negative sampling update cycle: sigmoid prediction, error terms, gradient updates, and the context window choice.

2Training Data Quality and Bias in Word Embeddings

How training data quality shapes word embeddings, why word meanings drift with the corpus, and how bias enters at the embedding layer.

3Continuous Bag of Words (CBOW)

The continuous bag of words model: predicting the target word from averaged context vectors with softmax, and how it compares with skip-gram.

4Softmax and Sigmoid: Purpose and Difference

The purpose and difference between sigmoid and softmax, with a side-by-side worked numerical example.

5Word Vector Arithmetic, Analogies, and t-SNE Visualization

Word vector arithmetic and analogies such as king minus man plus woman, with t-SNE visualization of the vector space.

6GloVe: Global Vectors for Word Representation

GloVe: global co-occurrence statistics, conditional probability ratios, and why ratios beat raw probabilities.

7Language Modeling: What It Is and Where It Is Used

What language modeling is, prediction versus generation, and where language models are used.

8Conditional Probability, Independence, and the Chain Rule

Conditional probability, independence, and the chain rule for word sequences.

9The Markov Assumption and n-gram Language Models

The Markov assumption and unigram, bigram, and trigram language models with start and end symbols.

10Bigram Probabilities: MLE Estimation and the Toy Corpus

Maximum likelihood estimation of bigram probabilities on a toy corpus.

11Sentence Probability, Logs, and the Zero-Count Problem

Sentence probability via products of bigram factors, log-space computation, and the zero-count problem.

12Laplace (Add-One) Smoothing

Laplace add-one smoothing: the formula, worked numbers, and its blunt-instrument effect.

13Interpolation and Backoff

Linear interpolation and stupid backoff for handling unseen n-grams.

14Exam Guidance Summary

What to expect per topic on the exam, plus cross-cutting exam rules.

15Key Industry Applications

Industry applications of static embeddings and statistical language modeling, and ideas that carried into transformers.

Postgraduate students in Natural Language Processing

Exam Revision Notes

Below is the distilled, exam-ready core. Every entry comes from the full explanation above. Use this section for rapid review; return to the main notes when a point needs more context.

Skip-gram with Negative Sampling: Recap of the Update Procedure

Must-know: SGNS update cycle: sigmoid of dot product gives prediction, error is actual minus predicted, and each vector updates by adding learning-rate (0.05) times the sum of error-weighted neighbor vectors — positives attract, negatives repel.

⚠️ Top pitfall: Mixing the error convention with the wrong update sign flips the geometry — positives get pushed away instead of pulled in.

Self-check: If a negative sample scores 0.52, what is its error, and in which direction does the target vector move?

Connects to: 4.3 Continuous Bag of Words (CBOW), 4.2 Training Data Quality and Bias in Word Embeddings

Training Data Quality and Bias in Word Embeddings

Must-know: Garbage in, garbage out: embeddings are the input layer of the whole pipeline, so bias and noise in the training corpus propagate to every downstream model.

⚠️ Top pitfall: Treating embeddings as neutral measurements instead of statistics of a specific, dated, possibly biased corpus.

Self-check: Why does a word's embedding change when the training corpus changes, even though the word itself is the same?

Connects to: 4.1 Skip-gram with Negative Sampling: Recap of the Update Procedure, 4.3 Continuous Bag of Words (CBOW)

Continuous Bag of Words (CBOW)

Must-know: CBOW predicts the target word from the averaged context vectors and a softmax over the vocabulary; the embeddings are the weight matrix, not the classification output.

⚠️ Top pitfall: Forgetting that the bag-of-words averaging throws away word order by construction.

Self-check: Which algorithm would you pick for a small corpus with rare words — CBOW or skip-gram — and why?

Connects to: 4.1 Skip-gram with Negative Sampling: Recap of the Update Procedure, 4.4 Softmax and Sigmoid: Purpose and Difference

Softmax and Sigmoid: Purpose and Difference

Must-know: Sigmoid gives a single value in 0..1 for one input; softmax is exponential of each value divided by the sum of all exponentials, giving probabilities that add to 1 for multi-class prediction.

⚠️ Top pitfall: Using sigmoid for multi-class problems — ten sigmoids can each output 0.9, which is not a valid distribution.

Self-check: What happens to the softmax probabilities of existing classes when a new class is added?

Connects to: 4.3 Continuous Bag of Words (CBOW), 4.6 GloVe: Global Vectors for Word Representation

Word Vector Arithmetic, Analogies, and t-SNE Visualization

Must-know: v(king) - v(man) + v(woman) is about v(queen): differences of embeddings encode relations, and analogy inference finds the nearest neighbor of the resulting vector.

⚠️ Top pitfall: Expecting exact equality — the arithmetic gives an approximate vector and the answer comes from a nearest-neighbor search.

Self-check: Using grape:vine and apple:tree, write the vector expression that predicts the missing word in 'grape is to wine as apple is to ?'.

Connects to: 4.6 GloVe: Global Vectors for Word Representation, 4.1 Skip-gram with Negative Sampling: Recap of the Update Procedure

GloVe: Global Vectors for Word Representation

Must-know: GloVe ratio: P(solid|ice)/P(solid|steam) = 1.9e-4/2.2e-5 about 8.9; ratios much larger than 1 mean the probe word belongs to the numerator word, near 1 means no distinction; counting is global, ratios are local. No exam math on GloVe.

⚠️ Top pitfall: Reading a ratio below 1 as 'unrelated' without noticing which word is the numerator — gas|ice over gas|steam below 1 means gas belongs to steam.

Self-check: P(water|ice)/P(water|steam) = 1.36 and P(fashion|ice)/P(fashion|steam) = 0.96. Which probe word distinguishes ice from steam better?

Connects to: 4.5 Word Vector Arithmetic, Analogies, and t-SNE Visualization, 4.2 Training Data Quality and Bias in Word Embeddings, 4.7 Language Modeling: What It Is and Where It Is Used

Language Modeling: What It Is and Where It Is Used

Must-know: A language model computes the probability of a sequence of words and of each next word given the previous words; these are generative models, so 'generate' is the right word, not 'predict' or 'inference'.

⚠️ Top pitfall: Treating a language model as a fact-checker — it measures fluency (how natural the text sounds), not truth.

Self-check: Name three applications where a language model picks the most natural candidate, and say what it needs to be paired with.

Connects to: 4.8 Conditional Probability, Independence, and the Chain Rule, 4.6 GloVe: Global Vectors for Word Representation

Conditional Probability, Independence, and the Chain Rule

Must-know: Chain rule: P(w1..wn) = P(w1)·P(w2|w1)·P(w3|w1,w2)···P(wn|w1..w(n-1)); each factor is a ratio of counts, and long histories that never co-occur make whole-phrase probabilities zero.

⚠️ Top pitfall: Reversing the condition: P(B|A) is not P(A|B); word order matters in every factor.

Self-check: Why does the phrase 'its water is so transparent' often score zero even when every individual word appears in the corpus?

Connects to: 4.9 The Markov Assumption and n-gram Language Models, 4.7 Language Modeling: What It Is and Where It Is Used

The Markov Assumption and n-gram Language Models

Must-know: Unigram P(w_i); bigram P(w_i|w_(i-1)); trigram P(w_i|w_(i-2),w_(i-1)); word order is critical in every n-gram count, and higher orders usually have zero counts in the corpus.

⚠️ Top pitfall: Treating the Markov approximation as exact — long-distance dependencies (verb agreement many words back) cannot be captured by any small n-gram.

Self-check: A trigram needs how many start symbols before the first word of a sentence, and why?

Connects to: 4.8 Conditional Probability, Independence, and the Chain Rule, 4.10 Bigram Probabilities: MLE Estimation and the Toy Corpus

Bigram Probabilities: MLE Estimation and the Toy Corpus

Must-know: MLE bigram: count of the ordered pair divided by count of the previous word; e.g. P(am|I) = 2/3 and P(</s>|Sam) = 1/2 in the toy corpus; each row of a bigram table sums to 1.

⚠️ Top pitfall: Using the wrong denominator — it must be the count of the previous word w_(i-1), not the total words or the sentence count.

Self-check: In the three-sentence corpus, why is P(</s> | Sam) = 1/2 and not 1/3?

Connects to: 4.9 The Markov Assumption and n-gram Language Models, 4.11 Sentence Probability, Logs, and the Zero-Count Problem

Sentence Probability, Logs, and the Zero-Count Problem

Must-know: P(want|I) = 827/2533 about 0.33; sentence probability multiplies bigram factors; one zero bigram makes the whole product zero; log probabilities are added, not multiplied, to avoid underflow.

⚠️ Top pitfall: Forgetting that log-probabilities are negative — 'higher' means closer to zero, not a bigger magnitude.

Self-check: Why does 'I want to eat Chinese food' score zero in the restaurant corpus while 'I want English food' scores about 0.000031?

Connects to: 4.10 Bigram Probabilities: MLE Estimation and the Toy Corpus, 4.12 Laplace (Add-One) Smoothing

Laplace (Add-One) Smoothing

Must-know: Laplace: P(w_i|w_(i-1)) = (C(w_(i-1),w_i)+1)/(C(w_(i-1))+V); with V=1446, P(want|I) = 828/3979 about 0.21, and the reconstituted count 0.208 x 2533 about 527 shows how blunt add-one is.

⚠️ Top pitfall: Using add-one blindly for n-gram language models — the large +V steals too much probability from common pairs (827 to 527).

Self-check: Why is V added to the denominator, and what would happen if you added 1 there instead?

Connects to: 4.11 Sentence Probability, Logs, and the Zero-Count Problem, 4.13 Interpolation and Backoff

Interpolation and Backoff

Must-know: Interpolation: P-hat = lambda_1·trigram + lambda_2·bigram + lambda_3·unigram with weights summing to 1, lambda_1 largest (most context); backoff has no lambdas — it steps down with a fixed 0.4 factor to unigram count/N.

⚠️ Top pitfall: Treating a stupid-backoff score S as a true probability — it does not sum to 1 and can only be used for ranking.

Self-check: With lambda = (0.6, 0.3, 0.1), trigram 0, bigram 0.3, unigram 0.01, what is the interpolated probability?

Connects to: 4.12 Laplace (Add-One) Smoothing, 4.11 Sentence Probability, Logs, and the Zero-Count Problem

Exam Guidance Summary

Must-know: SGNS numerical expected; CBOW and GloVe are conceptual-only; simple interpolation problems possible; exam count tables specify next word versus earlier word; word order is critical.

⚠️ Top pitfall: Mixing up which word is the next word and which is the earlier word when reading an exam count table.

Self-check: Which topics carry numerical exam questions, and which are conceptual-only?

Connects to: 4.1 Skip-gram with Negative Sampling: Recap of the Update Procedure, 4.3 Continuous Bag of Words (CBOW), 4.6 GloVe: Global Vectors for Word Representation, 4.13 Interpolation and Backoff

Key Industry Applications

Must-know: Static embeddings remain production tools because they are cheap to train and serve; the offline-training versus runtime-inference split (as in Google's TPU separation) is why pre-trained embeddings are heavy to build but cheap to use.

⚠️ Top pitfall: Using generic English n-gram corpora for domain-specific products — medical and finance applications need their own training data.

Self-check: Which standard visualization ships with GloVe, and what does it show?

Connects to: 4.1 Skip-gram with Negative Sampling: Recap of the Update Procedure, 4.5 Word Vector Arithmetic, Analogies, and t-SNE Visualization, 4.7 Language Modeling: What It Is and Where It Is Used, 4.11 Sentence Probability, Logs, and the Zero-Count Problem

Was this lecture useful?

Loading comments…
🤖

BitsNotes AI Assistant

Subject Notes Assistant

Configure AI Chat

Choose how to access the chatbot
Have your own API key?

Switch to "Bring Your Own Key" tab above for unlimited access with any OpenAI-compatible provider.

🔑 Enter API key above to fetch live models from provider, or enter model name manually.
OpenAI-Compatible API Support

Choose any provider preset (Gemini, DeepSeek, Kimi, GLM, MiniMax, Qwen, OpenAI, Groq, Ollama, etc.) or enter a custom endpoint URL.

Security & Privacy First

Your API key is sent directly from your browser to your specified provider. BitsNotes servers never store or see your key.