Statistical ML
With no labels at all, what hidden structure can a model find in data?
Part 6's pages come back uncoloured, and a two-component mixture fitted without labels recovers the two authors on 97% of them. The part builds models with parts that are never observed. Principal components are derived two ways, as the closest line and as the direction of greatest spread, then turned into a probability model; independent components unmix two microphones at a cocktail party. Mixtures are fitted by EM, whose lower bound is derived from Jensen's inequality and drawn under the real likelihood, and the same engine fits topic models, hidden Markov models (Baum-Welch) and IBM's Model 1 for translation. The part then counts as well as counting can: Kneser-Ney smoothing from Good-Turing, and an infinity-gram on a suffix array of all thirty novels, which adds a row to the scoreboard at 2.027 bits per character. It turns to graphs, d-separation and belief propagation, and to what a graph says about causes: Simpson's paradox and the back-door adjustment. It ends with the Bayesian toolkit: Gaussian processes, the evidence as Occam's razor, Bayesian optimization, and variational inference with the reparameterization trick.
What you need. Calculus, matrix algebra and probability with Gaussians (Parts 3 and 5); Part 6's pages.
- Mathematics and history
- PCA, EM, HMMs, graphical models, causality, Gaussian processes, variational inference, topic models, statistical MT, Kneser–Ney
- Models, data
- the scoreboard's KN and ∞-gram rows
What you will be able to do
Undergraduate
- Explain what a principal component is and compute the share of the spread it keeps.
- Run the E step and the M step of a two-bell mixture by hand, and say what each one does.
- Explain Simpson's paradox with a confounder, and why seeing is not doing.
Master's
- Derive PCA from a Lagrange multiplier and EM's lower bound from Jensen's inequality, and prove that EM never lowers the likelihood.
- Implement the forward and Viterbi recursions of a hidden Markov model and state their cost.
- Derive a Gaussian process's posterior mean and variance by conditioning a joint Gaussian.
Research
- Derive the ELBO identity, run coordinate-ascent variational inference on a conjugate model, and explain why the mean-field answer is too narrow.
- Split the log evidence of a Gaussian process into data fit and complexity penalty, and explain how it selects a model without held-out data.
Engineering
- Build an n-gram model with Kneser-Ney smoothing and report its bits per character on held-out text.
- Tune a hyperparameter by Bayesian optimization with expected improvement, and compare the evaluations spent with a grid.
Contents
Each chapter has a home level. Choose a track to see what to read and watch: Undergraduate 19 min · Master's 47 min · Research 55 min · Engineering 27 min.
- 0Structure nobody labelledUndergraduate3 min
- 1Principal components, two waysUndergraduate4 min
- 2PCA as a probability modelMaster's2 min
- 3The cocktail partyMaster's2 min
- 4Mixtures and EMUndergraduate4 min
- 5Topic modelsMaster's3 min
- 6Hidden Markov modelsUndergraduate3 min
- 7Baum-Welch, and machines that listenMaster's3 min
- 8Translation by countingEngineering3 min
- 9Kneser-Ney, from Good-TuringMaster's4 min
- 10The infinity-gramEngineering3 min
- 11Models as picturesMaster's3 min
- 12From graphs to causesUndergraduate3 min
- 13Gaussian processesMaster's4 min
- 14Bayesian Occam's razorResearch3 min
- 15Bayesian optimizationEngineering2 min
- 16Variational inferenceResearch5 min
- Recap, problems, and where this comes backAll tracks3 min
Also on this page: Lecture · Key results · Try it · Lab · Problems · Notes and sources · 中文 · Build the film.
Lecture
The text of each chapter is the film's narration, as it is spoken, so you can read along or revise without the film. The pictures are in the film. A dashed box stands for a number the film computes when it is rendered (hover over it to see what is computed); the README's figures for each chapter, where it lists them, follow the chapter's text.
Structure nobody labelledUndergraduate3 min
Here are part six's six hundred and thirty-nine pages again, each a point in seventy dimensions, seen along the three directions in which they vary most. But this time, nobody tells us who wrote which. Can the data reveal its own hidden structure? A model that assumes there are two hidden sources, and fits them with no labels at all, finds two groups. And they're the two authors: 97 percent of the pages land with the right one.
How did we get here? In 1901 Karl Pearson asked for the line that passes closest to a cloud of points. In 1933 Harold Hotelling asked for the directions of greatest variance, and called them principal components. In the 1960s, engineers and code breakers learned to reason about states they could not see: Andrew Viterbi's decoder in 1967, Leonard Baum's training method in 1970. In 1977 Dempster, Laird and Rubin showed that one algorithm, EM, fits almost any model with missing pieces. Judea Pearl gave the field a language of graphs for reasoning under uncertainty. At IBM, Fred Jelinek's group turned speech recognition, and then translation, into statistics: count, smooth, and let the data decide. By the 1990s, the hand-written rules of part two's expert systems had given way to probabilities learned from data. Topic models in 2003 and the Gaussian process book of 2006 crowned a decade in which machine learning meant statistics. Deep learning absorbed it all, but didn't replace it. The ELBO trains today's generative models, mixtures route words to experts, the forward algorithm aligns speech, and n-grams over trillions of words check what language models have memorized.
This is part seven of AI, Built: models with hidden parts, directions, sources, states and functions that we never observe, only infer. In this part: hidden directions and sources, from principal components to the cocktail party; mixtures, and the EM algorithm that fits them, with k-means and topic models; hidden Markov models, and the statistical revolution they started in speech and translation; the best ways to count, ending with an infinity-gram over all thirty novels; graphical models, and what they can say about cause and effect; and the Bayesian toolkit: Gaussian processes, Occam's razor, Bayesian optimization, and variational inference. Every method is written out and run.
1Principal components, two waysUndergraduate4 min
Pearson and Hotelling asked two different questions. Here are the pages again, on just two of the seventy word rates, 'the' and 'not', each rescaled to a spread of one. Pearson wanted the line that passes closest to the points: the smallest average squared distance, these little red segments. Hotelling wanted the direction along which the points spread the most. Turn the line, and watch both. Each page's squared length splits, by Pythagoras, into the part along the line and the part across it. So the spread kept plus the distance lost is the same total, 2.00, at every angle. The line closest to the points is the line of greatest spread. Two questions, one answer.
Here's why, in a few lines. The spread of the data along a unit vector u is u transpose C u, where C is the covariance matrix. We want the largest, keeping u at length one, so bring in a Lagrange multiplier, lambda. Set the gradient to zero, and out comes an eigenvector equation: C u equals lambda u. Multiply by u transpose: the spread along an eigenvector is its eigenvalue. So the best direction is the eigenvector with the largest eigenvalue. And the distance lost is the total minus the spread kept, so minimizing one maximizes the other. With k directions, the error left is exactly the sum of the eigenvalues we leave out. On the pages, with five directions, that's 46.59 of the seventy units of variance, and the identity holds for every k.
Principal components find the directions in which data varies the most. Start with the covariance matrix: seventy by seventy, how each pair of word rates moves together. It's symmetric, so, from part three, its eigenvectors are perpendicular, and each eigenvalue says how much of the variation lies along its eigenvector. The first direction holds 12.6 percent of all the variation, the next 9.1, and then they fall away.
A common alternative avoids forming the covariance matrix: part three's singular value decomposition of the data itself. Z equals U, sigma, V transpose. The rows of V transpose are the principal directions, and each singular value, squared and divided by the number of pages, is an eigenvalue. On the pages the two agree to the last digits of floating point. Working on Z directly is also more accurate: squaring the data to make C squares its condition number.
What are these directions? Each one is a recipe for mixing the seventy word rates. The first weighs 'not', 'be', 'very' and 'she' against 'the', 'and' and 'out'. That's Austen against Dickens, found without ever being told who wrote what. The second weighs 'I', 'me', 'you', 'said' and 'my' against 'of' and 'their'. That's dialogue against narration: the other big difference between pages.
Seen along the first three directions, the authors already sit apart. A single cut along the first direction sorts percent of these same pages correctly. The directions were fitted without author labels; we used the labels to choose the sign and this cut. PCA is part three's eigenvectors, put to work: the cheapest way to see a cloud of high-dimensional data.
2PCA as a probability modelMaster's2 min
PCA finds directions, but it isn't a probability model: it can't say how likely a new page is. In the late nineteen nineties, Michael Tipping and Christopher Bishop, and independently Sam Roweis, gave it one. Imagine each page begins as a few hidden numbers, z, drawn from a standard bell curve. A matrix W maps them up into the seventy word rates, onto a flat sheet through the data. Then noise of the same size in every direction blurs the sheet. Add it up, and a page is Gaussian, with covariance W W transpose plus sigma squared times the identity: a few big directions, and a fog around them.
The best W and sigma, by maximum likelihood, come out in closed form. W's columns can point along the top k eigenvectors of chapter one, each stretched by the square root of its eigenvalue minus the noise variance. Rotating the hidden axes gives an equally good fit. And the noise is the average variance of all the directions left out. Shrink the noise to zero and you get plain PCA back. So PCA was always the limit of a probability model, and now it has a likelihood.
A likelihood lets us choose how many hidden directions to keep. Fit on part six's training pages, use the held-out pages for validation and model selection. On the training pages, adding directions cannot lower the maximum likelihood, though ties are possible.
Probabilistic PCA sits in a family. Charles Spearman's factor analysis, from 1904, is the same model with a separate noise level for every variable. Probabilistic PCA ties them into one, which is why the eigenvectors fall out. And replace W with a neural decoder and add a learned variational encoder, and you reach the variational autoencoder of part twenty: the same hidden z, the same picture, a curved sheet instead of a flat one.
3The cocktail partyMaster's2 min
In 1953 the psychologist Colin Cherry asked how we manage to follow one voice in a noisy room: the cocktail party problem. Here's a machine's version. Two people talk at once. Two microphones each hear a different blend of the two, louder for whoever is nearer. In symbols, x equals A times s: the sounds we record are a mixing matrix times the voices. But we know neither the matrix nor the voices. All we have is x.
Plot the two microphones against each other, moment by moment, and the mixing shows as a slanted, squashed shape. First, whiten: chapter one's principal components, rescaled to unit spread. The two outputs are now uncorrelated. But they're still mixed: turn this white cloud by any angle, and it stays uncorrelated, so correlation alone can never tell us which way is right. The central limit theorem motivates looking for non-Gaussian directions in mixtures of independent signals. Here the contrast is excess kurtosis: for a centered, unit-variance output, the fourth moment minus three. A Gaussian gives zero, though zero alone does not prove Gaussianity. So turn the direction until the output is as far from Gaussian as possible. Aapo Hyvärinen's FastICA does it with a fixed-point step; here we record fixed-point steps.
Turn the white cloud to that angle, and read off the two outputs. Independent component analysis grew from Jeanny Hérault and Christian Jutten's circuits in the 1980s, through Pierre Comon's definition in 1994 and Bell and Sejnowski's infomax. Run on patches of natural images, it finds edge detectors like those in the visual cortex. Today it cleans eye blinks out of brain recordings, and its idea, find the directions in which the data is sparse and independent, is the dictionary learning behind part thirty's sparse autoencoders.
4Mixtures and EMUndergraduate4 min
PCA finds directions. A mixture model goes further: it supposes that each point was made by one of several hidden sources, each a bell curve of its own, and tries to recover them. Here are the pages along the first two directions, with no colours: we don't know who wrote what. Start with two guessed bells, badly placed. The expectation-maximization algorithm, EM, alternates two steps. E: for each page, how likely is each bell to have made it? That gives every page a soft colour. M: refit each bell to the pages, weighted by those colours.
Then again: E, M, E, M. Here the exact posterior E step and the constrained M step cannot lower the same likelihood. Each covariance has a fixed eigenvalue floor, and the M step maximizes the bound within that constraint. By the last displayed round, the pages each bell claims match the true authors percent of the time. Nobody told it there were authors at all. EM applies to many hidden-variable models when its E and M steps can be computed; it's the next chapter's engine too.
When does EM avoid going downhill? Use the exact posterior in E, and do not lower the same bound in M. Write the log-likelihood as a sum over the hidden choice z: which bell made this point. Multiply and divide by any distribution q over z. The log of an average is at least the average of the logs: that's Jensen's inequality, because the log curves downward. So we get a lower bound, B, that we can compute. How far below? The gap is exactly a KL divergence, between q and the posterior over z. It vanishes when q is the posterior, and that is the E step: it makes the bound touch. The M step then maximizes the bound over the parameters. Chain the three facts: the new likelihood is above the bound, the bound went up, and it started touching. The likelihood can never fall under those conditions. This also covers a generalized EM step that increases the bound without maximizing it. That's the principle in Dempster, Laird and Rubin's 1977 paper.
Here's that bound for real, on the pages. Each panel follows a straight line through the parameters, from one round's bells to the next round's. The yellow curve is the log-likelihood. The green curve is the bound that round's E step built: always below, touching at the start. The M step jumps to the top of the green curve, and the yellow curve, above it, can only be higher there. The first step, from a poor start, is a leap; later displayed steps are small. Each maximizing update raises the same bound within the feasible set; these closed-form updates need no gradient learning rate.
Now make EM's choices hard. Instead of soft colours, each page joins whichever centre is nearest; then each centre moves to the mean of its pages. That's k-means, Stuart Lloyd's algorithm from Bell Labs in 1957. From the same poor start, we display recorded rounds, and the average squared distance never rises. This is the small-variance limit of a Gaussian-mixture EM model: take round, equal-weight bells and take their width toward zero: points with a unique nearest centre make hard choices, while exact distance ties can remain soft. At the smallest width shown, percent of pages have responsibility above ninety-nine percent.
5Topic modelsMaster's3 min
A mixture model gives each page one hidden source. But a book is about several things at once. In 2003 David Blei, Andrew Ng and Michael Jordan wrote down a model for that: latent Dirichlet allocation, the topic model. The story goes like this. There are K topics, each a distribution over words. Each section of text has its own mix of topics, drawn from a Dirichlet distribution, which prefers mixes of only a few. And each word is made in two steps: pick a topic from the section's mix, then a word from that topic. Only the words are observed. The topics, the mixes and every word's topic are hidden, and we infer them all.
We cut the thirty novels into sections of words, keep the commonest words that aren't names or little function words, and ask for twelve topics. The topics start as the words of a few random sections: noise. Blei's original method fits them by variational EM, which chapter sixteen will explain: an E step that guesses each section's mix, and an M step that rebuilds each topic from the words assigned to it. Watch six of the topics take shape, alongside the bound scored after each round.
Here are all twelve topics after forty rounds, each with its commonest words and the novel where it turns up most. Nobody named them, but you can read them. The topic most at home in War and Peace leads with 'army', the one in The Count of Monte Cristo with 'francs', and the one in War and Peace with 'count'. Others are harder to name. And here is one section of War and Peace, with each word coloured by its likeliest topic. Its mix is 51 percent one topic and 49 percent another. For a decade, topic models were how historians and social scientists read archives too large to read. Today embeddings do much of that work, but the idea, a document as a mix of hidden themes, is the same picture.
6Hidden Markov modelsUndergraduate3 min
Hidden states can also unfold in time. A hidden Markov model has a state we can't see, moving like part five's Markov chain, with transition probabilities A. At every step the state emits something we can see, a letter, from its own table of chances, B. Here is a two-state model of the letters in the books; we'll train it in the next chapter. Leonard Baum and his colleagues worked out the mathematics in the late 1960s, at the Institute for Defense Analyses. Three questions follow. How likely is a sentence? Which states produced it? And how do we learn A and B?
First: how likely is a sentence? Summing over every possible sequence of hidden states would take two to the power of its length. The forward algorithm does it in one sweep. Lay the states out as a lattice, one column per letter. Let alpha of a state be the probability of the letters so far, ending in that state. By the Markov property, each alpha is a sum over the state before: its alpha, times the chance of the move, times the chance of the new letter. Sweep left to right, and the last column adds up to the probability of the letters. For 'there' and a space, that's about in ten million, exactly the sum over all paths. For the whole -letter sentence, the sum has two to the terms; the sweep takes a few hundred multiplications. Part twenty-three's speech recognizers train with CTC, which runs a related forward sum over the allowed ways of lining up sound with text, including blank labels.
Second: which hidden states produced the letters? Change one thing: replace the sum with a maximum. Now each circle holds the probability of the single best path into it, and we keep a pointer to the state it came from: one bright arrow into each circle. At the end, take the better final state and follow the pointers back. That's the most likely path, found exactly, without trying all of them. Andrew Viterbi published it in 1967 for decoding error-correcting codes; it went into mobile phones and space probes, and it decoded speech for decades.
Here's Shannon's sentence from part one, with one most likely complete hidden-state sequence. These colours come from the whole path, using both letter emissions and state transitions, rather than choosing each state's label independently. Nobody told the model what a vowel is.
7Baum-Welch, and machines that listenMaster's3 min
Third: how does the model learn A and B from letters alone? It's chapter four's EM again, and for this model it's called Baum–Welch. Run the forward sweep, and a mirror image, the backward sweep: beta is the probability of the letters still to come, from each state. Alpha times beta, divided by the probability of the whole text, is the chance that the chain was in state i at time t. That's the E step's soft colouring, one per letter. The same trick gives the chance of each move, from i to j, at each moment. The M step just counts: expected moves from i to j, over expected visits to i; expected emissions of each letter, over expected visits. For transitions, leave out the final time, which has no outgoing move. Exact E and M steps cannot decrease the likelihood; at a fixed point it stays unchanged.
Give it two hidden states, 200,000 letters of the books, and random first guesses. Then run Baum–Welch, and watch what each state learns to emit.
The learned emission tables: From the first state, the chain switches to the second percent of the time; from the second back to the first, percent. These are two directional probabilities. Nobody supplied vowel labels. Cave and Neuwirth studied this two-state English-letter experiment in 1980.
This is how machines learned to listen. In the 1970s, James Baker's DRAGON system and Fred Jelinek's group at IBM treated speech recognition as a statistics problem. Cut the sound into frames, a hundred a second, each a vector of features. Model every sound of the language as a small hidden Markov model, three states from left to right, and chain them into words. Each state emits feature vectors from a mixture of Gaussians: chapter four's mixtures inside chapter six's chain, all trained by Baum–Welch on hours of recorded speech. A dictionary turns sounds into words, and a counting model of word sequences, chapter nine's subject, chooses between sentences that sound alike. Viterbi finds the best one. Data beat rules. The remark usually attributed to Jelinek, in its best-known form: every time I fire a linguist, the performance of the speech recognizer goes up. He remembered the wording differently, but the point stuck. This design ran speech recognition for three decades, until, around 2012, deep networks replaced the Gaussian mixtures, and later the whole pipeline. Part twenty-three picks up the story.
8Translation by countingEngineering3 min
In 1947 Warren Weaver, who had run wartime research for the United States, wrote that a Russian article might be English written in a strange code, waiting to be decoded. The first decades of machine translation used rules instead, and in 1966 a government report, ALPAC, judged them a failure. Twenty years later, Jelinek's speech group at IBM took Weaver literally. Pretend the French was English, sent through a noisy channel. To decode, find the English sentence that is likely in itself, by a language model, and likely to come out as this French, by a translation model. They learned the translation model, with EM, from more than a million pairs of sentences from the Canadian parliament's proceedings, published in both languages.
Here's IBM's Model 1, on a tiny parallel corpus of French and English sentences that we wrote. The model has one table: t of e given f, the chance that a French word turns into an English word. Here we condition on the English length, and learn the direct English-given-French table, reversing the earlier noisy-channel direction. Each English word chooses equally among the French positions and NULL; the normalization is one over the number of choices, for every English word. Comparing different output lengths also needs a length prior. The alignments are hidden. EM again. Start with every translation equally likely. In the E step, each English word spreads its credit over the French words in its sentence; in the M step, the table is rebuilt from that credit. Because 'chat' appears exactly where 'cat' does, the credit piles up, and 'le' is pushed toward 'the', which frees 'chat'. After thirty rounds, 'chat' becomes '' with probability , and the alignment of this sentence is sharp, though Model 1 can't tell the two 'le's apart: it has no idea of word order.
Now translate sentences it never saw, one word at a time, using the table. Some come out right. Others put the adjective after the noun, French style. How good is that? In 2002 Kishore Papineni and colleagues at IBM proposed a score anyone can compute: BLEU. Count what share of the output's single words, pairs, triples and runs of four appear in a human reference, average their logs, and penalize output that's too short. Real systems learned their own word order: IBM's later models, then phrase-based translation, which ran Google Translate from 2006 until neural networks replaced it in 2016. And the alignment table of Model 1 came back as attention, a learned soft alignment, in 2014.
9Kneser-Ney, from Good-TuringMaster's4 min
Counting fails on what it has never seen, and most things are never seen. The fix came from code breaking. At Bletchley Park, Alan Turing and his assistant Jack Good needed the chance of things they had never yet seen. Good published the method in 1953, crediting Turing. Let N r be the number of different things seen exactly r times. Something seen r times is really worth r star: r plus one, times N r plus one over N r. And the total chance of everything unseen is N one over N, the share of things seen exactly once. Let's test it on pairs of words in the novels: count them in one half, then check the counts in the other half.
Look at what a count loses between the two halves: r, minus what the same pairs average in the other half. So instead of a formula for every r, subtract one fixed discount, D, from every count you've seen, and share the savings among what you haven't. That's absolute discounting, and it's the first half of Kneser–Ney.
Back to part one's scoreboard. The best counting model on that scored passage used characters of context and reached bits per character on the passage. Longer contexts should help, but they're rare: most long contexts in the passage appeared only a handful of times in thirty novels, if at all. Part one's curve retains its original order-dependent scoring starts. Here every Kneser–Ney order scores the same passage characters, after the first characters.
Reinhard Kneser and Hermann Ney's smoothing, from 1995, has two ideas. First, absolute discounting: shave the fixed discount off every count you've seen, and use the savings to back off to a shorter context, one character fewer: blend the two. Second, judge the shorter contexts by their variety. In the novels, '' appears times, but its number of distinct predecessors is ; its most common predecessor is ''. '' is about as common, and follows different words. So the shorter contexts count how many different contexts something follows, not how often it appears.
With characters of context, selected by comparing orders on one common validation suffix, Kneser–Ney reaches bits per character on the passage after its first characters. This benchmark keeps that selected order's own scoring start, matching the following infinity-gram comparison. For two decades, from speech recognition to machine translation, a Kneser–Ney model was the language model in the noisy channel. Stanley Chen and Joshua Goodman's careful comparison in 1998 found a modified Kneser–Ney variant best among the methods they tested. But why stop at characters?
10The infinity-gramEngineering3 min
Our Kneser–Ney tables use up to characters of context. Longer tables become expensive. The novels hold different pairs of characters, and different strings of . But a count is just a search through the text, and searching can be fast. Take every suffix of the text: the text from each position to the end. Here's a tiny one. Sort them alphabetically. That's a suffix array, from Udi Manber and Gene Myers in 1990. Every occurrence of any string, of any length, is now one contiguous block of the list, found by binary search, and the block's size is the count. For the thirty novels that's suffixes, with decimal megabytes of positions. Our replay searches at most characters of context. In 2024 Jiacheng Liu and colleagues combined indexes covering five trillion tokens of public text, and called the resulting unbounded-context model an infinity-gram.
Now predict the passage. At each character, take the context before it and extend it to the left, one character at a time, up to characters, counting as we go. The first count here is . An extra character can keep the count unchanged or reduce it. At characters, The infinity-gram predicts from the longest context the novels contain: whatever followed it there. Over the Maltese Falcon passage, the longest match is usually about characters, and at most : the novels have never seen most of Hammett's sentences, but they've seen their pieces.
How good is it? On its own, the infinity-gram's single most likely next character is right percent of the time. But percent of the time it gives the true character no chance at all, because it never saw it after that context. One zero, and the bits are infinite. So it's mixed with Kneser–Ney, with a weight for each length band and for whether the index has one or several possible next characters. In Liu's paper, a decontaminated 360-billion-token Pile index assigned the true next token probability above one half on 47 percent of held-out Pile tokens: a lower bound on next-token accuracy, separate from the five-trillion-token combined index. Mixing such counts also helped neural models. These indexes can trace generated phrases back to matching training documents.
11Models as picturesMaster's3 min
Every model in this part can be drawn the same way: a circle for each quantity, shaded if we observe it, empty if it's hidden, and an arrow wherever one depends directly on another. The mixture: a hidden choice of source, then a page, repeated for every page. The hidden Markov model: a chain of hidden states, each emitting a letter. The picture is a formula. The probability of everything is a product, the big pi: multiply one probability per circle, each given only the circles that point into it, its parents. That's a Bayesian network, Judea Pearl's language for reasoning under uncertainty.
Part one's language models fit the same picture, with an arrow from every earlier letter to every later one. Nothing is hidden, but nothing is simplified either: each factor is a prediction from the whole past. Counting can't fill in factors like that. A network, from part nine on, can.
A graph also tells you, without any numbers, which things are independent. Information flows along paths, and there are only three kinds of junction. In a chain, cloudy leads to rain leads to wet grass. Once you know it rained, the clouds tell you nothing more about the grass: observing the middle blocks the path. In a fork, clouds cause both rain and, less often, the sprinkler. The two look related: the sprinkler is on percent of rainy days and percent of dry ones. Given the clouds, the link disappears. The collider is the strange one. Rain and the sprinkler are independent, but both wet the grass, and observing the wet grass connects them. Pearl and his students turned these three cases into a rule, d-separation, that reads the conditional independences implied by the picture.
Pictures also tell us how to compute. Redraw the model as a factor graph: circles for the variables, and a small square for each factor of the product, each a table of numbers. To find the probability of one variable, we'd have to sum over all the others, every combination. Judea Pearl's belief propagation, from 1982, sends messages instead. Each circle tells its neighbour what it believes, given everything on its own side. Leaves first, up to the root, then back down. Multiply the incoming messages by the local factor, then normalize, and you have its exact probability. On a tree it is exact: Add one factor that closes a loop, and the same messages, passed round and round, are only approximate, off by about here. Yet loopy belief propagation decodes the error-correcting codes in phones and satellite links, and its messages are the message passing of part twenty-five's graph neural networks.
12From graphs to causesUndergraduate3 min
A real study, from 1986: two ways of removing kidney stones, open surgery and a keyhole method. For small stones, open surgery succeeded more often. For large stones, open surgery succeeded more often too. But over all patients, the keyhole method wins. That's Simpson's paradox, and it isn't a trick of arithmetic. Doctors gave open surgery mostly to the hard cases, the large stones. The comparison over all patients mixes the treatment's effect with the difficulty of the cases. Which treatment would you choose? Data alone can't say. You need to know where the data came from.
Draw where the data came from. Stone size affected which treatment doctors chose, and it affected success. So there are two paths from treatment to success: the direct one, the effect we want, and a back door through stone size, which carries the confounding. Judea Pearl's question is not 'what's the success rate among patients who got open surgery', but 'what would it be if we gave everyone open surgery': y given do x. Doing means cutting the arrows into the treatment: it's set by hand, not by the stone. And if a variable, here stone size, blocks every back door in an adequate causal graph, with no omitted confounding, the observational adjustment can identify the effect. We also need consistency, so treatment denotes the same well-defined intervention, and overlap: both treatments must be possible in each relevant size stratum. Average over size, using the success rate within each size, weighted by how common each size is in everyone. The size-standardized kidney-stone rates favour : against percent. Reading these as causal requires those assumptions; the observational table alone cannot establish them. This is the back-door adjustment, with its identification assumptions.
To be sure, build a world where we know the truth. Half the patients are severe cases; doctors treat most of the severe ones; the treatment adds ten points to recovery, and severity takes thirty-five away. Correlation is not intervention. Pearl calls it a ladder: seeing, doing, and imagining what would have happened otherwise. Randomized trials climb to the second rung by force. And part thirty climbs it inside neural networks, setting an activation by hand and watching what changes.
13Gaussian processesMaster's4 min
Sometimes the hidden thing is a whole function. Here's how often each page of Great Expectations says 'her', from the start of the novel to the end. It rises and falls as the story moves between characters. A Gaussian process is a probability distribution over functions; our kernel makes them smooth. Gaussian means bell-shaped: at every page, the value is uncertain, most likely near the middle of a bell. The kernel, k, says how strongly two pages' values move together: strongly when the pages are close, hardly at all when they're far apart. We already fitted the mean, kernel and noise settings using all these pages. Here are five draws from that fitted empirical-Bayes prior, before conditioning on the individual values again. Their typical width of wiggle is the length scale. Now condition on the pages with those settings fixed. The draws move toward functions compatible with the noisy observations.
The white curve is the conditional mean. The band is plus or minus two conditional standard deviations of the latent function, given the fitted settings. It excludes observation noise and uncertainty in those settings. The length scale, about pages, was chosen by the all-page marginal likelihood among the settings tried. Now condition only on the first pages, still holding the all-page fitted mean, kernel and noise fixed. This is a subset-conditioning demonstration, not a held-out forecast: those later pages already helped choose the settings.
Why is conditioning so easy? First subtract the mean. Under a Gaussian process, the pages we've seen and the value at any new page are jointly Gaussian, with covariances given by the kernel. And a Gaussian, conditioned on some of its coordinates, is still Gaussian. Completing the square gives its mean and variance. The mean is a weighted sum of the observed values: nearby pages weigh the most in this example. With mean and kernel settings fixed, the conditional latent variance is the prior's, minus what conditioning explains. It depends on the page locations, not directly on their observed values. But our fitted settings depend on all the values; this plug-in variance omits their uncertainty. Rasmussen and Williams' book of 2006 builds the whole subject on these two lines.
Now reveal conditioning pages in a random order. At zero revealed pages, this is the fitted empirical-Bayes prior; its mean, kernel and noise already used all the pages. We hold those settings fixed throughout. The band is plus or minus two latent conditional standard deviations, not an observation prediction band or full Bayesian uncertainty. Each conditioning page reduces the uncertainty near it, and the band pinches there. With all pages, the average uncertainty has fallen from to . Between the pages, where the kernel says the rate could still wander, it stays open. Mining engineers did this first: Danie Krige estimated gold grades between boreholes in the 1950s, and Georges Matheron made it a theory, kriging. Machine learning took it up in the 1990s.
14Bayesian Occam's razorResearch3 min
Chapter thirteen chose its length scale by a quantity we haven't explained: the marginal likelihood, also called the evidence. It is the probability of the data under the model, averaged over every function the prior allows. For a Gaussian process the average can be done exactly: the data is Gaussian, with the kernel matrix plus noise as covariance. Take the log: two model-dependent terms and a normalization constant. One term measures the fit: how well the data agrees with the model's covariances. The other is a penalty for complexity: the log-determinant measures how many different datasets the model could have produced. A flexible model spreads its probability thin.
Here are the two terms for the rate of 'her' in Great Expectations, as the length scale varies, the noise and signal levels held where they were fitted. Short length scales make wiggly functions that can follow every page: the fit is good. Long ones are smooth and miss the pages. But wiggly functions could have made so many other datasets that they pay a large complexity penalty. Together with the constant, the total log evidence peaks in between, at about pages. No held-out data was needed: the evidence trades fit against complexity by itself. That's Bayesian Occam's razor.
David MacKay drew the reason in 1992. Spread out every dataset a model could produce, and plot how probable the model makes each one. Every curve has area one. A simple model predicts a few datasets strongly. A flexible one can produce almost anything, so it gives each only a little. For the data we actually saw, the model in between wins: flexible enough to explain it, not so flexible that it bets on everything.
One more test, where we know the answer: points from a cubic curve, plus noise. Fit polynomials of every degree, from a flat line up to degree twelve, by Bayesian linear regression. The lower chart uses a separate, unregularized least-squares fit. In that reference family, training error cannot increase as degree grows. Fit against complexity: the same trade-off, seen from the other side, is the subject of part eight.
15Bayesian optimizationEngineering2 min
Every model in this series has knobs. Here's one: Kneser–Ney's discount, D, a single value for every order. Each try means building a model and scoring it on held-out text: seconds here, but days for a large network. So we want the best D in as few tries as possible. Bayesian optimization puts a Gaussian process on the unknown score, and asks, at every candidate, how much better than the best so far we can expect it to be. For a Gaussian the answer has a formula, the expected improvement. One term rewards a low predicted score: exploit. The other rewards a wide band: explore. Jonas Mockus proposed the approach in the 1970s; Donald Jones and colleagues made expected improvement standard in 1998; and in 2012 Jasper Snoek and colleagues showed it tuning neural networks better than experts.
Here it runs. Two random tries to start. The grey band is the Gaussian process's belief about the score; the yellow curve below is expected improvement, rescaled to a peak of one at each step. Its peak is where to look next. Each new score lands, the band pinches there, and the next look moves. Mostly it heads for low scores, and now and then it checks a place where the band is still wide. Exploring and exploiting is part twenty-six's bandit problem in another form. DeepMind tuned AlphaGo's settings this way before its 2016 match.
16Variational inferenceResearch5 min
For most models with hidden parts, the exact answer, the posterior over the hidden variables, is a shape we can't compute. The posterior is what we believe about the hidden things after seeing the data: part five's updated belief. Part five sampled such shapes with Markov chains. Variational inference does something else: it picks the closest shape from a simple family, here a single Gaussian, and uses that instead. Here both shapes are approximated on a finite grid and normalized inside the displayed window. Closest in what sense? In part one's KL divergence, from q to p. Start from a poor guess, and slide the Gaussian downhill.
It settles on one bump and ignores the other. This direction of KL punishes q for putting probability where p has almost none, so q hides inside a single mode, a single peak of the distribution. Measure the other way round, from p to q, and the fitted Gaussian covers both bumps, spilling into the empty middle. Neither is wrong: they answer different questions. The identity behind it all: the log probability of the data equals a lower bound, the ELBO, plus that KL. The ELBO is a score we can compute that always sits below the true one. Push it up, and the KL has to shrink, dragging q toward p. Variational autoencoders, in part twenty, are trained exactly this way.
Where does that identity come from? Three lines. The log probability of the data doesn't depend on z, so averaging it over q changes nothing. By Bayes' rule, p of x is the joint over the posterior. Multiply and divide by q, and split the log in two. The first part is the ELBO, the evidence lower bound; the second is the KL divergence from q to the true posterior. It's chapter four's EM bound again. EM can make the KL zero, because there the posterior is computable. With a restricted family, variational inference may leave a positive gap, even at the best q it can represent.
Now a model where we can check everything. Take of Austen's pages and their rate of 'the'. Model it as a bell curve of unknown mean and unknown precision, with the usual conjugate prior, so the exact posterior is known: here are its contours. Variational inference pretends we couldn't compute it, and looks for q of mu times q of tau: two independent factors, the mean-field family. Coordinate ascent updates one factor at a time: the best log q of one variable is the expected log joint, averaged over the other. Start q far too narrow. Each sweep raises the ELBO. These early updates are a preview, not a convergence test. Now jump to saved sweep for the check. The exact log probability of the data is ; the ELBO plus the KL, integrated numerically, agree to the third decimal place.
CAVI needs expectations in closed form. For a neural network there aren't any, so we follow the gradient of the ELBO with samples instead. The old way, the score function, multiplies f by the gradient of log q. It's unbiased, but noisy. In 2013 Diederik Kingma and Max Welling, and independently, a few months later, Danilo Rezende and colleagues, wrote the sample as the mean plus noise, so the gradient can flow through the sample itself: the reparameterization trick. The edge bins include estimates beyond the displayed range. Same expectation, same answer on average; but here its spread is against , a variance times smaller.
One more step. Our CAVI example fit one shared posterior to the whole set of pages. For local latent variables, such as chapter five's document mixtures, inference instead fits a separate q for each example. Instead, train one network, an encoder, to output q's parameters for any input: amortized inference. Sample z with the reparameterization trick, decode it back, and train both networks on the ELBO. That's the variational autoencoder, and part twenty builds one. The same bound trains diffusion models in part twenty-one.
Recap, problems, and where this comes backAll tracks3 min
Let's take stock. Principal components are the covariance's eigenvectors: the line of greatest spread, and the line closest to the data, at once; add noise, and they become a probability model. Independent components unmixed two synthetic signals. With an exact posterior E step and an M step that never lowers the same bound, EM cannot lower the likelihood. For an equal-weight spherical Gaussian mixture, k-means is the small-variance limit, and a topic model is a mixture of mixtures. Hidden Markov models inferred states from unlabelled letters, and EM's alignments started statistical translation. Good–Turing and Kneser–Ney counted what hadn't been seen, and a suffix-array model counted contexts up to its stated cap. Graphs gave us independence, message passing, and, with do, cause and effect. Gaussian processes put probabilities on whole functions, chose their own length scale by Occam's razor, and chose where to look next. And variational inference turned an impossible posterior into an optimization.
Hidden parts come back everywhere. Model 1's alignments return as attention, a soft alignment learned inside the network, in part thirteen. State-space models, in part fifteen, carry a hidden state through time, and mixtures of experts, in part sixteen, are mixtures with a learned way of choosing. The forward algorithm trains speech recognizers in part twenty-three. Under suitable independent random initialization and scaling, the infinite-width prior of a fully connected network is a Gaussian process, in part twelve. The ELBO and the reparameterization trick train autoencoders and diffusion models. Setting a network's activations by hand is the do operator, in part thirty. And Kneser–Ney is the row the first neural language model has to beat, in part nine.
Here are six problems, from Pearson's line to Pearl's do operator. Pause here and work through them; full solutions are in this part's notes.
Next time: the deepest question in machine learning. A model fits its training data; why should it work on anything else? Bias and variance, the bounds of Vapnik and Chervonenkis, networks that memorize random labels, and the curve that goes down, up, and then down again.
Bishop's Pattern Recognition and Machine Learning covers most of this part; Rasmussen and Williams the Gaussian processes, and Pearl's Causality the causes. Thanks for watching, and see you in part eight.
Where it goes next. Model 1's alignments return as attention in Part 13, hidden state through time as the state-space models of Part 15, and mixtures as the mixtures of experts of Part 16. The forward algorithm trains speech recognizers as CTC in Part 23, Gaussian processes are the infinite-width networks of Part 12, the ELBO and the reparameterization trick train the autoencoders and diffusion models of Parts 20 and 21, the do operator is causal tracing in Part 30, and Kneser-Ney is the row the neural language model of Part 9 has to beat.
Key results
The part's results in one place, for revision.
Try it
Lab 7 · EM never goes downhill: the bound under the likelihood
Fit a mixture of two Gaussians to unlabelled points by EM, and check the chapter's proof in numbers: the bound touches the log-likelihood where the E step was taken, lies below it everywhere else, and the gap is a KL divergence.
python -m videos.ai.labs 7
needs numpy, scipy, matplotlib · download lab07.py ·
source on GitHublog-likelihood per point: start, round 1, round 40 -1.9269 -1.9086 -1.7778
smallest change in one round 1.17e-03 (never negative)
bound minus likelihood where the E step was taken 1.1e-13 (they touch)
largest (bound - likelihood) along any step 1.1e-13 (the bound stays below)
gap at the new parameters minus KL(q || posterior) 2.0e-13
fitted means and sds -1.61, 1.35; 0.68, 0.88 (truth -1.6, 1.4; 0.7, 1.0)
points given to their true source 96.0%, with no labels
Each E step builds a curve that touches the log-likelihood from below; the M step climbs to that curve's top, so the likelihood above it can only have risen.
The code (105 lines; it asserts its own result)
"""Lab 7: run EM on a two-bell mixture and draw the lower bound each E step builds under the log-likelihood."""
import numpy as np
from videos.coursekit import labs
TITLE = "EM never goes downhill: the bound under the likelihood"
GOAL = ("Fit a mixture of two Gaussians to unlabelled points by EM, and check the chapter's proof in numbers: the "
"bound touches the log-likelihood where the E step was taken, lies below it everywhere else, and the gap is a KL divergence.")
TASKS = [
"Move the two sources closer (means -0.6 and 0.6). How many rounds does EM need now, and how well does it recover the labels?",
"Make the E step hard: give each point wholly to its likelier bell (k-means with variances). Does the log-likelihood still never fall?",
"Start both bells at the same mean. Explain from the M step's formulas why EM cannot leave that start.",
]
def log_joint(x, theta):
"""log p(x_i, z = k; theta) for both bells: an (n, 2) array. theta = (pi_1, mu_1, mu_2, sd_1, sd_2)."""
pi, mu, sd = np.array([theta[0], 1 - theta[0]]), np.array(theta[1:3]), np.array(theta[3:5])
return np.log(pi) - 0.5 * np.log(2 * np.pi * sd ** 2) - 0.5 * ((x[:, None] - mu) / sd) ** 2
def log_lik(x, theta):
return np.logaddexp(*log_joint(x, theta).T).sum()
def e_step(x, theta):
lj = log_joint(x, theta)
return np.exp(lj - np.logaddexp(*lj.T)[:, None])
def m_step(x, q):
nk = q.sum(0)
mu = (q * x[:, None]).sum(0) / nk
sd = np.sqrt((q * (x[:, None] - mu) ** 2).sum(0) / nk)
return np.array([nk[0] / len(x), mu[0], mu[1], sd[0], sd[1]])
def bound(x, q, theta):
"""Jensen's lower bound B(q, theta) = sum_i sum_k q_ik log(p(x_i, k; theta) / q_ik)."""
return (q * (log_joint(x, theta) - np.log(np.maximum(q, 1e-300)))).sum()
def run(seed=0):
rng = np.random.default_rng(seed)
n = 400
z = rng.random(n) < 0.4
x = np.where(z, rng.normal(-1.6, 0.7, n), rng.normal(1.4, 1.0, n))
theta = np.array([0.5, -0.3, 0.4, 1.5, 1.5]) # a poor start: two wide bells side by side
thetas, lls, worst_touch, worst_above, worst_kl = [theta], [log_lik(x, theta)], 0.0, -np.inf, 0.0
curves = []
for k in range(40):
q = e_step(x, theta)
new = m_step(x, q)
ts = np.linspace(0, 1.25, 51)
line = [theta + t * (new - theta) for t in ts]
ll_line = np.array([log_lik(x, th) for th in line])
b_line = np.array([bound(x, q, th) for th in line])
worst_touch = max(worst_touch, abs(ll_line[0] - b_line[0])) # the bound touches at the E step's parameters
worst_above = max(worst_above, (b_line - ll_line).max()) # ... and is never above the likelihood
post = e_step(x, new) # the gap at the new parameters is KL(q || posterior there)
kl = (q * (np.log(np.maximum(q, 1e-300)) - np.log(np.maximum(post, 1e-300)))).sum()
worst_kl = max(worst_kl, abs((log_lik(x, new) - bound(x, q, new)) - kl))
if k in (0, 1, 4):
curves.append((k, ts, ll_line, b_line))
theta = new
thetas.append(theta)
lls.append(log_lik(x, theta))
lls = np.array(lls)
agree = np.mean((e_step(x, theta)[:, 0] > 0.5) == z)
agree = max(agree, 1 - agree)
lab = labs.Lab()
lab.row("log-likelihood per point: start, round 1, round 40", f"{lls[0] / n:.4f} {lls[1] / n:.4f} {lls[-1] / n:.4f}")
lab.row("smallest change in one round", f"{np.diff(lls).min():.2e} (never negative)")
lab.row("bound minus likelihood where the E step was taken", f"{worst_touch:.1e} (they touch)")
lab.row("largest (bound - likelihood) along any step", f"{worst_above:.1e} (the bound stays below)")
lab.row("gap at the new parameters minus KL(q || posterior)", f"{worst_kl:.1e}")
lab.row("fitted means and sds", f"{theta[1]:.2f}, {theta[2]:.2f}; {theta[3]:.2f}, {theta[4]:.2f} (truth -1.6, 1.4; 0.7, 1.0)")
lab.row("points given to their true source", f"{agree:.1%}, with no labels")
lab.note = ("Each E step builds a curve that touches the log-likelihood from below; the M step climbs to that "
"curve's top, so the likelihood above it can only have risen.")
assert np.all(np.diff(lls) > -1e-9), "the log-likelihood never falls"
assert worst_touch < 1e-8 and worst_above < 1e-8, "a lower bound, tight at the current parameters"
assert worst_kl < 1e-7, "the gap is the KL divergence from q to the posterior"
assert agree > 0.9 and abs(theta[1] + 1.6) < 0.3 and abs(theta[2] - 1.4) < 0.3, "the sources are recovered"
fig, ax = labs.figure(2, size=(11, 4.2))
grid = np.linspace(x.min() - 0.5, x.max() + 0.5, 300)
ax[0].hist(x, bins=40, density=True, color=labs.GREY, alpha=0.45, label="400 unlabelled points")
for th, color, name in ((thetas[0], labs.RED, "the start"), (thetas[-1], labs.GOLD, "after 40 rounds")):
ax[0].plot(grid, np.exp(log_joint(grid, th)).sum(1), color=color, label=name)
ax[0].set(title="The mixture before and after EM", xlabel="x", ylabel="density")
ax[0].legend()
for (k, ts, ll_line, b_line), color in zip(curves, (labs.BLUE, labs.PURPLE, labs.TEAL)):
rise = ll_line[40] - ll_line[0] # ts[40] = 1: each round is drawn in units of its own gain
ax[1].plot(ts, (ll_line - ll_line[0]) / rise, color=color, label=f"round {k + 1}: log-likelihood")
ax[1].plot(ts, (b_line - ll_line[0]) / rise, color=color, ls="--", label=f"round {k + 1}: the E step's bound")
ax[1].axvline(1, color=labs.MUTED, lw=0.8, ls=":")
ax[1].set(title="Along each step: the bound touches at 0, peaks at 1", xlabel="from this round's parameters (0) to the next round's (1)",
ylabel="rise, as a share of the round's gain", ylim=(-0.75, 1.3))
ax[1].legend(ncol=1, loc="lower right")
lab.fig = fig
return lab
Now change it
- Move the two sources closer (means -0.6 and 0.6). How many rounds does EM need now, and how well does it recover the labels?
- Make the E step hard: give each point wholly to its likelier bell (k-means with variances). Does the log-likelihood still never fall?
- Start both bells at the same mean. Explain from the M step's formulas why EM cannot leave that start.
Problems, with solutions
Try each problem before opening its solution.
1. Pearson's line is Hotelling's. For centred data with covariance C and a unit vector u, show that the mean squared distance to the line through u is tr(C) − uᵀCu, and deduce that the two lines coincide.
Solution
The projection of x on the line is (uᵀx)u, and x − (uᵀx)u is perpendicular to u, so by Pythagoras ‖x − (uᵀx)u‖² = ‖x‖² − (uᵀx)². Averaging, E‖x‖² = tr(C) and E(uᵀx)² = uᵀCu. The distance is a constant minus the spread, so minimizing one maximizes the other: both are the top eigenvector of C.
2. Probabilistic PCA. Show that x = Wz + μ + ε, with z ~ N(0, I_k) and ε ~ N(0, σ²I) independent, has covariance WWᵀ + σ²I, and check that W = U_k(Λ_k − σ²I)^{1/2} makes it agree with the data's covariance on the top k directions.
Solution
Cov(Wz) = W Cov(z) Wᵀ = WWᵀ, Cov(ε) = σ²I, and independent covariances add. With W = U_k(Λ_k − σ²I)^{1/2}, WWᵀ = U_k(Λ_k − σ²I)U_kᵀ, so for an eigenvector u_i with i ≤ k, (WWᵀ + σ²I)u_i = (λ_i − σ²)u_i + σ²u_i = λ_i u_i, the data's own variance; in the other directions the model gives σ², the average of the discarded eigenvalues.
3. EM never goes downhill. Using log p(x; θ) = B(q, θ) + KL(q ‖ p(z | x; θ)), prove that one round of EM never lowers the likelihood.
Solution
The E step sets q = p(z | x; θ_old), so the KL is 0 and B(q, θ_old) = log p(x; θ_old). The M step picks θ_new to maximize B(q, ·), so B(q, θ_new) ≥ B(q, θ_old). And since KL ≥ 0 (Gibbs), log p(x; θ_new) ≥ B(q, θ_new). Chaining: log p(x; θ_new) ≥ B(q, θ_new) ≥ B(q, θ_old) = log p(x; θ_old).
4. The forward algorithm. Derive α_t(j) = Σ_i α_{t−1}(i) A_ij B_j(x_t) and count its operations.
Solution
α_t(j) = p(x_1..x_t, z_t = j) = Σ_i p(x_1..x_{t−1}, z_{t−1} = i) p(z_t = j | z_{t−1} = i) p(x_t | z_t = j), where the conditional independences of the chain (the next state depends only on the current one; each letter only on its state) remove x_1..x_{t−1} from the last two factors. Each of the T steps computes S values, each a sum of S products: O(T S²), against S^T paths for the brute-force sum.
5. Good–Turing's singleton mass transfer. Assume N_1 > 0. Good–Turing gives each item seen once the count 1* = 2N_2/N_1. What total probability does it give all of them, and where did the rest of their mass go?
Solution
N_1 items × (2N_2/N_1) / N = 2N_2/N, exactly the share of tokens that items seen twice had. In general the class seen r times receives the mass the class seen r + 1 times had, (r + 1)N_{r+1}/N; the class seen once gives its mass N_1/N to the unseen items, which is Good–Turing's estimate p(unseen) = N_1/N. Here N counts observations: for word pairs it is the number of bigram trials, not the number of words. The class-transfer identity does not ensure that the unsmoothed estimator normalizes when frequency classes are missing. With one type seen once and another seen three times, N=4 but N_2=N_4=0: both raw adjusted seen counts are zero, and estimated unseen mass is only 1/4. Practical models smooth the counts of counts and normalize; do not infer a complete probability distribution from the raw row formula alone.
6. The back-door formula. For Z → X, Z → Y, X → Y, derive P(y | do(x)) = Σ_z P(y | x, z) P(z).
Solution
Assume the stated causal graph is adequate, with no omitted confounding, consistent well-defined interventions and overlap in treatment assignment. The joint factorizes as P(z) P(x | z) P(y | x, z). Intervening on X removes the factor for X (it no longer listens to Z) and fixes X = x: P_do(x)(z, y) = P(z) P(y | x, z). Summing out z gives the formula. It differs from P(y | x) = Σ_z P(y | x, z) P(z | x), which weighs the strata by how often each z occurs among those who received x.
Notes and sources
Sources
Books: C. M. Bishop, Pattern Recognition and Machine Learning (2006); D. MacKay, Information Theory, Inference, and Learning Algorithms (2003); C. E. Rasmussen & C. K. I. Williams, Gaussian Processes for Machine Learning (2006); D. Koller & N. Friedman, Probabilistic Graphical Models (2009); D. Jurafsky & J. H. Martin, Speech and Language Processing, 3rd ed. draft; J. Pearl, Causality (2000); J. Pearl & D. Mackenzie, The Book of Why (2018).
Papers: Pearson (1901); Spearman (1904); Hotelling (1933); Krige (1951); Cherry (1953); Good (1953); Baum & Petrie (1966); Viterbi (1967); MacQueen (1967); Baum, Petrie, Soules & Weiss (1970); Baker (1975); Mockus (1975); Jelinek (1976); Dempster, Laird & Rubin (1977); Cave & Neuwirth (1980); Pearl (1982, 1988, 1995); Lloyd (1982, written 1957); Hérault & Jutten (1986); Charig et al. (1986); Rabiner (1989); Brown et al. (1990, 1993); Manber & Myers (1990); Church & Gale (1991); MacKay (1992); Comon (1994); Julious & Mullee (1994); Ney, Essen & Kneser (1994); Kneser & Ney (1995); Bell & Sejnowski (1995, 1997); Jones, Schonlau & Welch (1998); Chen & Goodman (1998); McEliece, MacKay & Cheng (1998); Roweis (1998); Tipping & Bishop (1999); Hyvärinen (1999); Jordan, Ghahramani, Jaakkola & Saul (1999); Hofmann (1999); Papineni, Roukos, Ward & Zhu (2002); Blei, Ng & Jordan (2003); Snoek, Larochelle & Adams (2012); Hinton et al. (2012); Kingma & Welling (2013); Rezende, Mohamed & Wierstra (2014); Chen et al., Bayesian Optimization in AlphaGo (2018); Liu, Min, Zettlemoyer, Choi & Hajishirzi, Infini-gram (2024).
About this partfrom its README
Part 7 of a thirty-one-part series on how modern AI works and how it came to be (see the series plan
and the syllabus): models with hidden parts, which we never observe and only infer, and the
statistical era of AI, from Pearson's line of closest fit (1901) through EM (1977), IBM's statistical speech
recognition and translation, Pearl's graphs and causes, topic models (2003) and Gaussian processes (2006), to an
infinity-gram over the thirty novels (after 2024's infini-gram). It reuses Part 6's 639 pages (Austen and Dickens,
70 word rates each) and Part 1's books, and every method is written out in numpy in compute.py; every model that
is trained has its training replayed on screen.
Chapter notes
- Structure nobody labelled. The pages along their three main directions, uncoloured; a two-component mixture fitted without labels recovers the authors (97% agreement). How we got here: Pearson (1901), Hotelling (1933), Viterbi (1967), Baum (1970), Dempster–Laird–Rubin (1977), Pearl (1988), IBM's translation (1990–93), LDA (2003), Rasmussen–Williams (2006). The objectives.
- 1. Principal components, two ways. Pearson's line closest to the points and Hotelling's direction of greatest spread, on two standardized word rates: a line turned through every angle, the spread kept plus the squared distance lost always 2.00 (Pythagoras). The derivation: Lagrange, Cu = λu, spread = λ, error with k directions = the eigenvalues left out (46.59 of 70 at k = 5, checked for every k). The 70 × 70 covariance and its spectrum (12.6%, 9.1%, ...); the SVD of the data matrix (σ²/n = λ to rounding); what directions 1 and 2 weigh; one cut along direction 1 sorts 88% of pages.
- 2. PCA as a probability model. Probabilistic PCA (Tipping & Bishop 1999; Roweis 1998): x = Wz + μ + ε, samples from the fitted model, the closed-form maximum-likelihood W and σ², PCA as σ → 0. Held-out log-likelihood on Part 6's 191 test pages against the number of hidden directions: training always rises, held-out peaks at k = 17 (−92.8 nats per page, against −93.1 for a full covariance). Factor analysis (Spearman 1904) → pPCA → the VAE.
- 3. The cocktail party. Cherry (1953); two signals mixed into two microphones, x = As; whitening leaves the rotation undetermined; the central limit theorem and kurtosis (sources −1.51 and −1.10, whitened mixes −0.80 and −0.56); kurtosis against angle, FastICA's fixed point (Hyvärinen 1999) landing in 5 steps; recovered sources correlate 0.9992 and 0.9999 with the truth, whitening alone 0.76–0.77. Hérault & Jutten, Comon (1994), Bell & Sejnowski (1995, 1997), EEG artefact removal, dictionary learning.
- 4. Mixtures and EM. A mixture of Gaussians fitted by EM on the pages' first two principal components: soft colours, the ellipses breathing, the log-likelihood that never falls, 97% agreement (Dempster, Laird & Rubin 1977). The derivation: Jensen's lower bound B(q, θ), the gap is KL(q ‖ p(z | x)), monotonicity proved. The bound drawn for real: along the line from round k's parameters to round k + 1's, the likelihood and the bound the E step built (touching at round k, peaking at round k + 1), for rounds 0, 1 and 4. k-means as hard EM (Lloyd 1957/1982, MacQueen 1967): 10 rounds, the objective falling, 95% agreement; responsibilities hardening as the bells shrink.
- 5. Topic models. Latent Dirichlet allocation (Blei, Ng & Jordan 2003; after Hofmann 1999): the plate diagram and generative story; the thirty novels cut into 2,248 sections of 2,000 words, 3,000 content words, 12 topics fitted by variational EM (40 rounds, the bound rising every round); six topics taking shape; the final topics with the novel each is commonest in (the whaling of Moby Dick, the armies of War and Peace, ...); one section coloured word by word, with its mixture.
- 6. Hidden Markov models. The chain and its emissions; a two-state model of the letters; the forward algorithm derived and run on "there␣" (3.2 × 10⁻⁷, equal to the sum over all 64 paths); the cost T·S² against S^T; CTC (Part 23) runs the same recursion. Viterbi (1967): the lattice with real back-pointers, the path lighting up; Shannon's sentence decoded.
- 7. Baum–Welch, and machines that listen. Forward–backward as EM's E step (γ, ξ) and the counting M step; the training replayed on 200,000 letters: one state takes the space and the vowels, the other every consonant, alternating 72% of the time (Cave & Neuwirth 1980); bits per letter 4.89 → 3.96. Speech recognition with HMM–GMMs (Baker's DRAGON 1975; Jelinek 1976): frames, three-state phone models, Gaussian-mixture emissions, a pronunciation dictionary and an n-gram model; the remark attributed to Jelinek; deep networks replace the mixtures (Hinton et al. 2012).
- 8. Translation by counting. Weaver's letter (1947) and memorandum (1949); ALPAC (1966); IBM's noisy channel (Brown et al. 1990, 1993) on the Canadian Hansards. IBM Model 1 trained by EM on a 20-pair French–English corpus we wrote: an alignment matrix sharpening round by round, the likelihood rising; 'chat' → 'cat' with probability 1.00. BLEU (Papineni et al. 2002), defined and computed on 6 held-out sentences: 0.76 word by word, 1.00 with one reordering rule; IBM Models 2–5, phrase-based translation, attention as learned soft alignment.
- 9. Kneser–Ney, from Good–Turing. Good (1953, after Turing): r* = (r + 1) N_{r+1} / N_r and p(unseen) = N_1/N, tested on the novels' word pairs against the other half (Church & Gale 1991): seen once, 0.32 predicted, 0.32 measured. The loss r − r_held is nearly constant (0.80–0.95 from r = 2): absolute discounting (Ney, Essen & Kneser 1994). Kneser–Ney (1995): discounting and continuation counts, with the novels' own example ('cristo': 1,049 times, always after 'monte'; 'nor': 1,315 times after 921 different words). Character n-grams to 7 characters of context: 2.04 bits per character on the passage (Part 1: 2.32); Chen & Goodman (1998).
- 10. The infinity-gram. Distinct strings in the novels by length (167 … 4.5 million); the suffix array (Manber & Myers 1990) built by prefix doubling over all 23.7 million characters, a small one sorted on screen; a context grown leftward with its count falling from 4.2 million to 1 at 26 characters; longest matches over the passage (median 10, at most 37). The ∞-gram alone: 56% next-character accuracy, but probability 0 for the truth 32% of the time; mixed with Kneser–Ney by weights per match length (chosen on held-out novel text), 2.027 bits per character against 2.040: the scoreboard's new row. Liu et al. (2024): 5 trillion tokens, 47% next-token accuracy.
- 11. Models as pictures. Graphical models (Pearl 1988): circles, shading, arrows, the factorized joint; the mixture and the HMM; a language model as a fully connected picture. d-separation: chain, fork and collider, checked by simulation (the sprinkler on 16% of rainy days and 38% of dry ones, 10.0% against 9.9% given clouds; rain 20%, 45% given wet grass, 20% given wet grass and the sprinkler: explaining away). Factor graphs and belief propagation (Pearl 1982): messages leaves → root → leaves on a 7-variable tree, exact against all 128 states; one loop makes it approximate (off by 0.0007); turbo and LDPC decoding, graph neural networks.
- 12. From graphs to causes. Simpson's paradox in the kidney-stone study (Charig et al. 1986; Julious & Mullee 1994); the confounder, the back door, P(y | do(x)) and graph surgery; the back-door adjustment derived (open surgery 83% against 78%). A simulated world where the truth is known (+0.10): the naive comparison −0.11, the adjustment +0.099, a randomized experiment +0.101. Pearl's ladder of causation; interventions on networks (Part 30).
- 13. Gaussian processes. The rate of "her" across Great Expectations: prior and posterior samples, the kernel, the mean and its band; the length scale (2 pages) by marginal likelihood; the band opening beyond the first 20 pages. Mean, kernel and noise are fitted using all pages: the initial distribution is an empirical-Bayes fitted prior, and the first-20-page display conditions on a subset with those settings fixed. It is not a held-out forecast. The band is latent-function mean ±2 conditional standard deviations, excluding observation noise and uncertainty in the fitted settings. Plot coordinates retain their values within an inclusive viewport. The posterior from Gaussian conditioning (Schur complement), step by step. The band shrinking as pages land in random order (average σ 6.34 → 2.60 over 186 pages). Krige (1951), Matheron, Rasmussen & Williams (2006).
- 14. Bayesian Occam's razor. The evidence p(y | θ) = ∫ p(y | f) p(f | θ) df, its log split into data fit and complexity penalty; both terms against the length scale, the sum peaking at 2.1 pages. MacKay's picture (1992, schematic). Polynomials of degree 0–12 on 30 noisy points from a cubic: training error always falls, the evidence peaks at degree 3.
- 15. Bayesian optimization. Kneser–Ney's discount D (one for every order, 5 characters of context) tuned on 200,000 held-out characters; expected improvement derived; the GP band and EI replayed evaluation by evaluation (the GP's length scale chosen by marginal likelihood each step): D = 0.84 (1.8438 bits) after 8 evaluations, as good as a 31-point grid; the discounts estimated from counts of counts give 1.8470. Mockus (1975), Jones, Schonlau & Welch (1998), Snoek, Larochelle & Adams (2012); AlphaGo's tuning.
- 16. Variational inference. KL(q ‖ p) on Part 5's two bumps settles in one bump, KL(p ‖ q) covers both; the ELBO identity derived (EM's bound again). CAVI on a Normal–Gamma model of 25 Austen pages' rate of "the": the exact posterior's contours, q(μ)q(τ) converging in 2 sweeps, log p(x) = −95.334 = ELBO + KL = −95.352 + 0.018 (KL integrated on a grid; difference 3 × 10⁻⁷); mean field too narrow (1.51 against 1.57). The reparameterization trick (Kingma & Welling 2013; Rezende, Mohamed & Wierstra 2014): one-sample gradient estimates, variance 12× smaller than the score function's; amortized inference and the VAE (Part 20).
- Recap in twelve pictures, where it comes back, the problem set, Part 8's teaser, references.
Every number in the list above is computed by compute.py and printed on screen from the cache; a rerun on another
machine can move the last digits, and the narration, written over the data, follows in both languages.
The syllabus's plan for this partfrom SYLLABUS.md, the plan of record
- PCA two ways (max variance, min reconstruction) and via SVD; probabilistic PCA.
- ICA (the cocktail party).
- Mixtures and EM: the Jensen bound, monotonicity proved; k-means as hard EM.
- HMMs: forward, Viterbi lattice, Baum–Welch (CTC in Part 23 reuses the forward algorithm).
- Graphical models: d-separation, factor graphs, belief propagation.
- Gaussian processes: posterior from Gaussian conditioning, marginal-likelihood hyperparameters.
- Variational inference: the ELBO identity, mean-field CAVI, reparameterization, amortization (VAEs come back).
- Bayesian Occam's razor.
- Kneser–Ney from Good–Turing and absolute discounting.
- ∞-gram (infini-gram, suffix arrays) on the thirty novels: a new scoreboard row.
- Topic models: latent Dirichlet allocation (2003).
- The statistical revolution in language: IBM translation models trained by EM (1990s), BLEU; speech recognition with HMM–GMMs.
- From graphs to causes: Pearl's do-calculus, the back-door criterion, why correlation is not intervention.
- Bayesian optimization (a GP choosing where to look next).
Visuals: EM ellipses breathing; Viterbi paths lighting up; a GP band shrinking as points land.
中文讲义
本讲的中文部分(与英文版对应)。
习题与解答
1. 皮尔逊的直线就是霍特林的直线。 对协方差为 C 的中心化数据和单位向量 u,证明到过 u 的直线的平均平方距离是 tr(C) − uᵀCu,并由此推出两条直线重合。
解答
x 在直线上的投影是 (uᵀx)u,而 x − (uᵀx)u 与 u 垂直,所以由勾股定理 ‖x − (uᵀx)u‖² = ‖x‖² − (uᵀx)²。取平均, E‖x‖² = tr(C),E(uᵀx)² = uᵀCu。距离等于一个常数减去分散程度,所以让一个最小就是让另一个最大:两者都是 C 的最大特征向量。
2. 概率PCA。 证明当 z ~ N(0, I_k) 与 ε ~ N(0, σ²I) 独立时,x = Wz + μ + ε 的协方差是 WWᵀ + σ²I,并验证 W = U_k(Λ_k − σ²I)^{1/2} 使它在前 k 个方向上与数据的协方差一致。
解答
Cov(Wz) = W Cov(z) Wᵀ = WWᵀ,Cov(ε) = σ²I,独立随机量的协方差相加。取 W = U_k(Λ_k − σ²I)^{1/2}, 则 WWᵀ = U_k(Λ_k − σ²I)U_kᵀ,所以对 i ≤ k 的特征向量 u_i,(WWᵀ + σ²I)u_i = (λ_i − σ²)u_i + σ²u_i = λ_i u_i,正是数据自己的 方差;在其余方向上,模型给出 σ²,也就是被舍掉的特征值的平均。
3. EM 永不走下坡。 利用 log p(x; θ) = B(q, θ) + KL(q ‖ p(z | x; θ)),证明 EM 的一轮不会降低似然。
解答
E 步令 q = p(z | x; θ_old),于是 KL = 0,B(q, θ_old) = log p(x; θ_old)。M 步选 θ_new 使 B(q, ·) 最大,所以 B(q, θ_new) ≥ B(q, θ_old)。又因为 KL ≥ 0(吉布斯不等式),log p(x; θ_new) ≥ B(q, θ_new)。串起来: log p(x; θ_new) ≥ B(q, θ_new) ≥ B(q, θ_old) = log p(x; θ_old)。
4. 前向算法。 推导 α_t(j) = Σ_i α_{t−1}(i) A_ij B_j(x_t),并数一数它的运算量。
解答
α_t(j) = p(x_1..x_t, z_t = j) = Σ_i p(x_1..x_{t−1}, z_{t−1} = i) p(z_t = j | z_{t−1} = i) p(x_t | z_t = j),这里用了链的 条件独立性(下一个状态只依赖当前状态,每个字母只依赖它的状态),把后两个因子里的 x_1..x_{t−1} 去掉。T 步中每一步算 S 个值,每个值是 S 个乘积之和:O(T S²),而暴力求和要遍历 S^T 条路径。
5. Good–Turing 的单例质量转移。 假设 N_1 > 0。Good–Turing 给每个只见过一次的东西的计数是 1* = 2N_2/N_1。它们合起来得到多少概率? 其余的概率质量去了哪里?
解答
N_1 个东西 × (2N_2/N_1) / N = 2N_2/N,恰好是见过两次的那一类原来占的比例。一般地,见过 r 次的那一类,得到 见过 r + 1 次那一类原有的质量 (r + 1)N_{r+1}/N;见过一次的那一类,把自己的质量 N_1/N 让给了没见过的东西,这正是 Good–Turing 的估计 p(没见过) = N_1/N。 这里 N 是观测次数:对词对来说,是二元词对的试验数,不是词数。上面的类别质量转移并不保证原始估计在计数类别缺失时归一化。 例如一种类型见过1次,另一种见过3次,N=4,但 N_2=N_4=0,两种已见类型的原始调整计数都是0,未见质量估计却只有1/4。 实际模型需要平滑计数的计数并归一化,不能只凭原始逐行公式就宣称得到了完整概率分布。
6. 后门公式。 对 Z → X、Z → Y、X → Y,推导 P(y | do(x)) = Σ_z P(y | x, z) P(z)。
解答
假设这个因果图足以描述问题,没有遗漏混杂,干预有一致且明确的含义,而且各层里都有机会接受两种治疗。 联合分布分解为 P(z) P(x | z) P(y | x, z)。对 X 进行干预,就删掉 X 的因子(它不再听 Z 的),并固定 X = x: P_do(x)(z, y) = P(z) P(y | x, z)。对 z 求和即得公式。它不同于 P(y | x) = Σ_z P(y | x, z) P(z | x),后者按每个 z 在接受了 x 的人中出现的频率来给各层加权。
术语
| English | 中文 |
|---|---|
| principal component analysis (PCA) | 主成分分析(PCA) |
| line of closest fit | 最佳拟合直线(最近直线) |
| covariance matrix, eigenvector, eigenvalue | 协方差矩阵,特征向量,特征值 |
| Lagrange multiplier | 拉格朗日乘子 |
| reconstruction error | 重构误差 |
| singular value decomposition (SVD) | 奇异值分解(SVD) |
| probabilistic PCA | 概率PCA |
| factor analysis | 因子分析 |
| latent variable, hidden variable | 潜变量,隐变量 |
| held-out data | 留出数据 |
| independent component analysis (ICA) | 独立成分分析(ICA) |
| cocktail party problem | 鸡尾酒会问题 |
| mixing matrix, whitening | 混合矩阵,白化 |
| kurtosis | 峰度 |
| central limit theorem | 中心极限定理 |
| FastICA, fixed point | FastICA,不动点 |
| mixture of Gaussians | 高斯混合模型 |
| expectation-maximization (EM), E step, M step | 期望最大化(EM),E步,M步 |
| responsibility (posterior) | 责任(后验概率) |
| Jensen's inequality, lower bound | 詹森不等式,下界 |
| k-means, hard assignment | k均值,硬分配 |
| topic model, latent Dirichlet allocation (LDA) | 主题模型,潜在狄利克雷分配(LDA) |
| Dirichlet distribution | 狄利克雷分布 |
| variational EM | 变分EM |
| hidden Markov model (HMM) | 隐马尔可夫模型(HMM) |
| transition probability, emission probability | 转移概率,发射概率 |
| forward algorithm, backward algorithm, forward–backward | 前向算法,后向算法,前向–后向算法 |
| lattice (trellis) | 网格 |
| Viterbi algorithm, back-pointer | 维特比算法,回溯指针 |
| Baum–Welch algorithm | 鲍姆–韦尔奇算法 |
| HMM–GMM speech recognizer | HMM–GMM语音识别器 |
| noisy channel | 有噪信道 |
| parallel corpus, alignment | 平行语料,对齐 |
| IBM Model 1, translation table | IBM模型1,翻译概率表 |
| BLEU, n-gram precision, brevity penalty | BLEU,n元精确率,长度惩罚 |
| phrase-based translation | 基于短语的翻译 |
| Good–Turing estimation, counts of counts | Good–Turing估计,计数的计数 |
| absolute discounting | 绝对折扣 |
| Kneser–Ney smoothing, continuation count | Kneser–Ney平滑,接续计数 |
| suffix array, prefix doubling, binary search | 后缀数组,前缀倍增,二分查找 |
| infini-gram (∞-gram), longest match | 无穷元模型(∞-gram),最长匹配 |
| graphical model, Bayesian network, plate | 图模型,贝叶斯网络,板 |
| d-separation; chain, fork, collider | d分离;链,叉,对撞点 |
| explaining away | 解释消除 |
| factor graph, belief propagation, message passing | 因子图,信念传播,消息传递 |
| loopy belief propagation | 有环信念传播 |
| Simpson's paradox, confounder | 辛普森悖论,混杂因子 |
| intervention, do-operator, do-calculus | 干预,do算子,do演算 |
| back-door criterion, back-door adjustment | 后门准则,后门调整 |
| ladder of causation | 因果之梯 |
| randomized experiment | 随机试验 |
| Gaussian process, kernel, length scale | 高斯过程,核函数,长度尺度 |
| Gaussian conditioning, Schur complement | 高斯条件分布,舒尔补 |
| kriging | 克里金法 |
| marginal likelihood (evidence) | 边缘似然(证据) |
| data fit, complexity penalty | 数据拟合,复杂度惩罚 |
| Bayesian Occam's razor | 贝叶斯奥卡姆剃刀 |
| Bayesian linear regression | 贝叶斯线性回归 |
| Bayesian optimization, expected improvement | 贝叶斯优化,期望改进 |
| exploration, exploitation | 探索,利用 |
| variational inference, ELBO | 变分推断,证据下界(ELBO) |
| mean field, coordinate ascent (CAVI) | 平均场,坐标上升(CAVI) |
| conjugate prior, Normal–Gamma | 共轭先验,正态–伽马分布 |
| score-function estimator, reparameterization trick | 得分函数估计量,重参数化技巧 |
| amortized inference, encoder, decoder | 摊销推断,编码器,解码器 |
Build the film
python -m videos.ai.ai7.compute # the part's numbers, into .cache/ai7
python tools/build.py ai7 # render and assemble the film
EXPLAINER_TTS=silent python tools/qa_scene.py ai7 Hook # one chapter, silent, with a contact sheet
Scenes: videos/ai/ai7. Setup: see the course page. Source of these notes: the README and the scenes' narration.
Build it
From the repo root:
python tools/make.py ai7 # everything: compute, then English and Chinese builds
python -m videos.ai.ai7.compute # just the numbers (.cache/ai7), about 15 CPU-minutes on one core
python -m videos.ai.ai7.compute infini lda # specific items; --force to recompute
python -m videos.ai.ai7.compute --check # read-only cache status; missing/stale results fail
python tools/build.py ai7 # English
python tools/build.py ai7 --lang zh # Chinese
The computation requires Part 1's existing thirty novels, text and score artifacts (.cache/ai1) and current
Part 6 pages (.cache/ai6). The make command explicitly prepares the inputs needed by the requested items;
requesting only kn does not build the unrelated page experiments or model-backed scoreboard. Direct loaders
never download missing upstream data, and cached-only mode rejects missing, legacy or stale results before
generation. Recomputed results preserve replaced bytes; Bayesopt resumes only pieces with matching observed
source, runtime and consumed-input identities. Every random choice is seeded. The suffix array (infini.py) sorts 23.7 million suffixes by
prefix doubling in numpy (about a minute, under 1.5 GB of memory) and is not cached; the Bayesian optimization saves
each evaluation as it goes (CACHE.partial), so an interrupted run resumes. No multiprocessing, no torch.
Other parts read load("kn") and load("gp") (Parts 9, 10, 13, 31) and the functions kn_model, ngram_tables and
kn_probs (Part 9): they are unchanged. The scoreboard with Part 7's two rows is load("scoreboard").