Six neurons share one hidden driver, and one of them is loud and noisy. Factor analysis still finds the driver’s loadings where PCA chases the noise.
Learn how a population of neurons can be explained by a few hidden factors plus private noise, how to fit that model, and how it connects to PCA.
Drag the noise on neuron 1 upward. Watch the warm PCA bars swing toward the loud neuron while the teal factor analysis bars stay near the purple truth. Then we build, piece by piece, the model, its fit, and its closed-form cousin.
You need a rough idea of a Gaussian (a bell curve of values with a centre and a spread) and what a firing rate is (spikes per second). We build the rest from zero.
Based on Lecture 19 of Princeton NEU 560: Statistical Modeling and Analysis of Neural Data (Spring 2024), taught by Jonathan Pillow; the slides and notes are on the course site. Every idea is re-taught here in our own words and devices.
Simulated, not recorded: 400 trials, six neurons, one hidden driver with true loadings 0.9, 0.6, 1.0, 0.5, 0.8, 0.7. Neurons 2 to 6 have noise variance 0.3; you set neuron 1. Bars show each loading vector scaled to length 1. Match is the cosine similarity with the true loadings (1.0 means the same direction). Factor analysis is fitted by 80 steps of EM (Chapter 6).
Chapter 0
See why a population of neurons moves together, and why one shared signal plus private noise is the right story
Picture a mouse running along a track while a thin probe records six neurons in its hippocampus. You plot each neuron’s firing rate over time. All six wander up and down, and they wander together. When the mouse reaches the middle of the track, most neurons fire more. When it turns back, most fire less.
No single neuron explains the pattern. Each one is noisy, and each one has its own habits. Yet something shared moves them all. Here the shared thing is easy to name: the animal’s position on the track. In many recordings you cannot name it. It could be attention, arousal or a memory replaying.
This lecture gives that story a name and a recipe. A latent variable is a quantity we never measure but believe exists, like the mouse’s position when the camera is off. A factor is a latent variable that several neurons share. Factor analysis (FA) is a model that explains a whole population with a few factors plus private noise for each neuron.
Lecture 15 introduced hidden-variable models in general (the lesson on that lecture covers them). Before this lecture the course covered the tools for fitting them: EM, mixtures of Gaussians, Monte Carlo and importance sampling. Lecture 19 applies those tools to the simplest, friendliest latent variable model there is.
It is the friendliest because everything is Gaussian. A Gaussian is the bell curve: a centre (the mean) and a spread (the variance). Gaussians stay Gaussian when you add them, scale them or condition on one of them. So every integral in this lecture has an exact answer, and every answer is a short formula.
The lecture has two halves. Part I is factor analysis: the model, what it predicts, why its answer is ambiguous, how to read the hidden factor out of the data, and how to fit it with EM. Part II is probabilistic PCA (PPCA): factor analysis with one extra rule, which makes the model fit in one step and ties it to the PCA you already know. The last slides set up the next lecture, the variational autoencoder.
Suppose all six neurons were only the shared signal. Then every neuron would be a copy of the position, scaled. Real neurons are not copies. Each one has its own randomness: its own noisy spiking, its own small inputs. So each neuron is the shared signal, scaled, plus private noise.
The balance between the two matters. If the shared part is large, the neurons look alike and a pair of them has a high correlation (a number from −1 to 1 that says how closely two signals rise and fall together). If the private part is large, the neurons look independent. Drag the slider below and watch both the traces and the correlation grid change.
The purple trace is the hidden signal. Each blue trace is one neuron: some of the signal plus its own noise. The grid on the right shows how strongly each pair of neurons moves together. Drag the share of each neuron that comes from the signal.
Simulated: 240 time bins, six neurons, every neuron scaled to variance 1. Each neuron is the square root of the shared share times the hidden signal, plus the square root of the rest times its own noise. The first 80 bins are drawn; the correlations use all 240.
At 0% the grid is dark except the diagonal: the neurons ignore each other. At 100% every cell is bright: the six neurons are copies. In between lies every real population. The average correlation tracks the shared share, because the shared signal is the only thing two neurons have in common.
That gives us a tool. If we can measure how much two neurons move together, we learn how much of each one is shared. Factor analysis does this for all neurons at once, and it also recovers the shared signal itself, trial by trial.
The slides open with five review problems, a quick check on those earlier tools. They ask for the ELBO (the lower bound that EM raises) in its E-step and M-step forms, the marginal p(x) and the recognition distribution P(z = 2 | x) of a three-component mixture of Gaussians (EM for Gaussian mixtures), a Monte Carlo recipe for a KL divergence (Monte Carlo), and a way to estimate an expectation under Bernoulli(p) from a fair coin by importance sampling (importance sampling). Nothing else in this lesson needs them, but the recognition distribution and the E-step return in Chapters 5 and 6 in a new, Gaussian form.
This lesson follows the lecture slide by slide, in order. Each chapter adds one idea, and one device lets you play with it.
Chapter 1
Generate fake neural data from the factor analysis model and name every shape in the recipe
You are recording six neurons while a mouse repeats a task 400 times. Each repeat is a trial. On every trial the mouse is in a slightly different internal state: a little more alert, a little less. You never measure that state. You only see six firing rates per trial.
Suppose you wanted to invent data that looks like this, using a computer. What would you do? You would first invent the hidden state for the trial. Then you would decide how strongly each neuron follows it. Last, you would add a little randomness to each neuron. That three-step recipe is factor analysis.
For every trial, draw a short list of numbers called the factors, written z. Here the list has one number, the hidden state. The lecture draws each factor from a standard Gaussian: mean 0, variance 1, independent of the others. Write it z ~ N(0, I), where I is the identity matrix, the way to say “variance 1 each, no links between them.”
The list is low-dimensional: m numbers, with m much smaller than the number of neurons d. The slide marks one more fact. This step has no parameters. A mixture of Gaussians needs mixing probabilities for its hidden variable. Factor analysis fixes the hidden variable’s distribution and puts all learning elsewhere.
Next, multiply the factors by a matrix A, the factor loadings. A has one row per neuron and one column per factor, so it is d × m: tall and skinny, as the slide says. Entry Ajk answers one question: how strongly does neuron j follow factor k? A big positive entry means the neuron fires more when the factor is high. A negative entry means it fires less.
With one factor, A is a single column of six numbers. That column is a pattern across the population: which neurons move together, and which move against each other.
Last, add noise ε to every neuron, drawn from N(0, Ψ). Ψ (psi) is a diagonal matrix: it has numbers on the diagonal and zeros elsewhere. The diagonal entries are the noise variances, which the slide also calls uniquenesses, because each belongs to one neuron alone. Zeros off the diagonal mean the noise of one neuron says nothing about the noise of another.
The whole model has two sets of unknowns: A and the diagonal of Ψ. Together they are the parameters θ = {A, Ψ}. With d = 6 neurons and m = 1 factor, that is 6 loadings plus 6 noise variances: 12 numbers.
The same recipe in one line says: given the factors, the data is Gaussian with mean Az and covariance Ψ. Write it x | z ~ N(Az, Ψ). Read the bar as “given.” Once you know z, each neuron’s remaining randomness is its own.
Try it. Press Draw a trial and watch the three steps for one trial. Then raise the noise and watch the data bars stop following the purple pattern.
Top: the factor z for this trial. Rows: six neurons. Purple is the loading times z, yellow is the neuron’s private noise, blue is what you would record, the sum of the two. Press Draw a trial, then change the noise.
Simulated. The loadings are the lesson’s running example (0.9, 0.6, 1.0, 0.5, 0.8, 0.7). All six neurons get the same noise variance here so you can see the effect of the knob alone. Rates are in arbitrary units around a mean of zero, as the model assumes.
Follow one trial through the shapes. z has shape (m) = (1). A has shape (d, m) = (6, 1). The product Az has shape (6). The noise ε has shape (6). The sum x has shape (6).
Now stack N = 400 trials as columns. Z has shape (m, N) = (1, 400), and the data matrix is X = A Z + noise, with shape (6, 400). That is exactly what your recording is. Fitting the model means going backwards: given X, find A, Ψ and, if you like, Z.
pythonimport numpy as np
rng = np.random.default_rng(0)
d, m, N = 6, 1, 400
A = np.array([[0.9, 0.6, 1.0, 0.5, 0.8, 0.7]]).T # loadings, shape (d, m)
psi = np.full(d, 0.3) # noise variances, shape (d,)
Z = rng.standard_normal((m, N)) # factors, shape (m, N)
E = rng.standard_normal((d, N)) * np.sqrt(psi)[:, None]
X = A @ Z + E # data, shape (d, N)
Two honest limits. First, the data is assumed to have mean zero, so subtract each neuron’s average rate before fitting. Second, the model is Gaussian, but spike counts are whole numbers and not bell-shaped. A common fix is to take the square root of each count, which makes the spread more even, then treat the result as Gaussian. A better fix is a model with Poisson spiking, as in generalized linear models. This lecture keeps the Gaussian version because everything stays exact.
The failure to watch for is a shared noise source that is not a brain state. Symptom: a factor loads with the same sign on every neuron, even when the animal does nothing. Measurement: its trial values rise and fall with a recording artefact, such as head movement. Fix: remove the artefact, for example by subtracting a common reference, and refit.
Chapter 2
Integrate out the hidden driver and see the shape of the cloud of trials that the model predicts
Run the recipe 400 times and plot the results. Each trial is one dot with a coordinate per neuron. What shape does the cloud of dots have? That is the question this chapter answers, and the answer is the model’s fingerprint on your data.
The factors z are hidden, so we cannot plot them. We care about the marginal distribution: the distribution of x alone, after we ignore (integrate out) the hidden z. The lecture also calls it the induced data distribution, because the hidden variable induces it.
A sum of Gaussians is Gaussian. Since x = Az + ε adds a scaled Gaussian to a Gaussian, x is Gaussian. So we only need its mean and its covariance. The covariance is a table: entry (j, k) says how much neurons j and k move together, and the diagonal holds each neuron’s own variance.
Mean. The mean of z is 0 and the mean of ε is 0. So the mean of x is A × 0 + 0 = 0.
Covariance. Multiply x by its own transpose and average. Four terms appear. Two are cross terms between z and ε. They vanish because z and ε are independent with mean zero. What remains is A E[zzT] AT + E[εεT]. Now E[zzT] = I, because z has variance 1 and no links. And E[εεT] = Ψ. So the covariance is AAT + Ψ.
Read the formula as a sentence about your data. All the links between neurons live in the low-rank part. All the leftover variance sits on the diagonal. That is the model’s whole claim.
A full covariance for d neurons has d(d + 1)/2 free numbers. For d = 6 that is 21. For 100 neurons it is 5,050, and you would need thousands of trials to estimate them well. Factor analysis with m factors has only d × m + d numbers. For 100 neurons and 5 factors that is 600. The model is a structured guess that needs far less data.
The slides build one small example, step by step, and so do we. Take two neurons and one factor. The loadings are A = (1, 2), so neuron 2 follows the factor twice as strongly as neuron 1. The noise variances are Ψ = diag(100, 1). Neuron 1 is very noisy: its noise has a standard deviation of 10. Neuron 2 is quiet.
First, AAT is the 2 × 2 table [[1, 2], [2, 4]]. Add Ψ, which puts 100 and 1 on the diagonal. The marginal covariance is [[101, 2], [2, 5]]. The big 101 is almost all noise. Neuron 2 has variance 5, of which 4 is shared.
Step through the device. Each press of a button moves the same 250 dots one stage further.
Each dot is one trial. Choose a stage and watch the dots move. Horizontal is neuron 1, vertical is neuron 2, both drawn at the same scale.
Simulated: 250 trials from A = (1, 2) and Ψ = diag(100, 1), the lecture’s example. The ellipse is the contour two standard deviations from the centre of the marginal. Purple is the loading direction A. Warm is the top principal component of the marginal covariance.
Look at the last stage. The ellipse is long and nearly flat. It lies along the x1 axis, the noisy neuron. Yet the hidden factor pushes along a steep line that the cloud barely shows. The top principal component, the direction of greatest variance, is warm and points along the noise. The loading direction A is purple and points up steeply.
Compute it. The covariance [[101, 2], [2, 5]] has eigenvalues about 101.04 and 4.96. The top eigenvector points 1.2 degrees above the x1 axis. The direction of A is atan(2 / 1) = 63.4 degrees. The two are 62 degrees apart. This gap is the lecture’s motivation for factor analysis, and Chapter 3 takes it up.
One more caution. With only two neurons and one factor, the data cannot tell A and Ψ apart. The covariance has 3 numbers and the model has 4 unknowns. The picture shows the true model that made the data. To recover A and Ψ from data you need enough neurons. Chapter 4 counts exactly how many.
The failure to watch for is too few factors. Symptom: after fitting, neurons that share a hidden cause still move together in the leftover. Measurement: subtract AAT + Ψ from the sample covariance and look for off-diagonal entries that are not near zero. Fix: add a factor, then test whether it helps on held-out trials.
Chapter 3
Answer the lecture’s discussion question by changing a unit and watching which method notices
The lecture pauses on the worked example with a question to the room: is PCA or FA a better data analysis technique for this case? The slide relabels the picture. The hidden variable is now animal position, and the two axes are the responses of neuron 1 and neuron 2. Two neurons, one position, and one of the neurons is very noisy.
Pause here and guess before reading on. The answer comes from asking what each method believes about variance.
Principal component analysis (PCA) finds the direction in which the data varies most. You may know it from Lecture 3 or the PCA lesson. It treats all variance as signal. It has no place to put noise. If one neuron is wildly noisy, its big variance looks like a big signal, and the top component turns toward it.
That is what the last chapter’s picture showed. The covariance [[101, 2], [2, 5]] has its top principal component almost along neuron 1. Yet the animal’s position acts along (1, 2), mostly through neuron 2. PCA answers a different question from the one we asked. We asked for the shared direction. It returned the loudest direction.
Factor analysis gives every neuron its own noise variance. It can say: “Neuron 1 has a variance of 101, but 100 of it is private noise.” Because the noise has a home in the model, the shared direction is what is left over. The model asks how much of each neuron’s variance is shared, not how large it is.
So for this example the answer is factor analysis. The neurons clearly differ in noise, and the question is about the hidden position, not about the variance itself.
Here is a sharper way to see the difference. Suppose you measured neuron 1 in spikes per second and then in spikes per 10 ms. The numbers shrink by a factor of 100. Nothing about the neuron changed. A good method should give the same answer after you translate the units back.
Factor analysis passes. Rescaling neuron 1 by s rescales its loading by s and its noise standard deviation by s. The result is another model of the same kind, so the fitted structure maps back exactly. PCA fails. Rescaling changes which neuron has the most variance, so it changes which direction wins.
Try it. Slide the unit of neuron 1 from 0.05 times to 10 times its original size. The dial shows angles measured from the neuron 1 axis, after translating back to the original units.
The purple arrow is the loading direction of the hidden position. The warm arrow is the top principal component, translated back to the original units. Drag the unit and watch the warm arrow swing.
The example is the lecture’s: A = (1, 2), Ψ = diag(100, 1). The covariance after rescaling neuron 1 by s is [[101 s², 2 s], [2 s, 5]]. The purple direction is the true loading direction, which an exact factor analysis fit returns whatever the unit; two neurons alone cannot fit it from data (Chapter 4). Angles are in degrees from the neuron 1 axis.
At the original unit (×1) the warm arrow lies 1.2 degrees above the axis and the purple arrow 63.4. The gap is 62.2 degrees. Shrink neuron 1 to ×0.3 and PCA is still 61 degrees off. At ×0.2 it jumps to 28.9 degrees, a gap of 34.5. At ×0.1 the warm arrow lands on the purple one, a gap of zero, and then it moves away again. PCA found the right line once, by luck, because the units happened to balance the noise against the signal.
The purple arrow never moves. That is the whole point. The hidden position acts in one way on the neurons, and the model’s answer does not depend on the ruler you used to measure them.
PCA is not wrong. It answers the question “where is the variance?” exactly. If you want a compact picture of a dataset, that is often enough. The trouble starts when you read the top component as the shared signal.
If every neuron has the same noise variance, PCA and factor analysis agree on the direction. Equal noise adds the same amount to every diagonal entry, which changes no eigenvector. Part II of the lecture builds on exactly that fact: a model with one shared noise variance that fits in closed form.
The failure to watch for is reading PCA weights as shared structure. Symptom: the top component loads mostly on the neuron with the highest variance. Measurement: plot each neuron’s variance next to its weight in the component. If they track, you are seeing loudness. Fix: use factor analysis, or at least scale every neuron to variance 1 first, remembering that this equalises total variance and not noise.
Chapter 4
Rotate the factors, keep every prediction, and learn which parts of the answer are real
Two labs fit factor analysis to the same recording. Lab A reports that factor 1 mostly drives neurons 1 to 3. Lab B reports that factor 1 drives neurons 3 to 5. Both fits predict the data equally well. Did one lab make a mistake? Not necessarily. The slide’s one-line warning explains why: the model is identifiable only up to a rotation.
A model is identifiable if different parameter values always make different predictions. If two different settings make exactly the same predictions, no amount of data can choose between them. The slide shows that factor analysis has this problem, and it shows why in four short lines.
Take any orthogonal matrix U. That is a matrix whose columns have length 1 and are at right angles, so that UUT = I. A rotation is an orthogonal matrix. So is a reflection, which flips an axis.
Build a new loading matrix Ā = AU. Now compute what it predicts. The shared part of the covariance is ĀĀT = (AU)(AU)T = A U UT AT. Since UUT = I, this equals AAT. So both A and AU give the same marginal distribution, N(0, AAT + Ψ). The slide states it exactly so.
The slide gives a second view. If z is drawn from N(0, I), then Uz is also drawn from N(0, I) for any orthogonal U. A standard Gaussian cloud is round, so turning it changes nothing. So x = Az = (AU)(UTz): the same data arises from rotated loadings and rotated factors.
The device uses two factors and six neurons, so each neuron has a pair of loadings: a point in the plane of the factors. Turn the factors. The points move. The table of AAT on the right does not.
Each dot is one neuron’s pair of loadings on factor 1 (horizontal) and factor 2 (vertical). The grid shows AAT: how strongly each pair of neurons shares the factors. Drag the angle, or flip a factor.
Toy loadings for six neurons and two factors (invented for this device). The change in AAT is computed live as the largest difference between any entry of the rotated product and the original; it is zero up to rounding error in the computer.
Look at neuron 3, which starts at (0.80, 0.60). Turn the factors by 70 degrees and its loadings become about (0.84, −0.55). Every neuron’s numbers change. Yet the largest change in any of the 36 entries of AAT is 0.000000. The data cannot tell the two descriptions apart.
Three things survive any rotation, so you can trust them: the product AAT, the noise variances Ψ, and the plane that the columns of A span. The individual axes inside that plane are a choice. With one factor, the only orthogonal matrices are +1 and −1, so the only ambiguity is the sign.
In practice analysts pick a convenient rotation after the fit. A popular one, varimax, turns the axes so that each factor loads strongly on a few neurons and weakly on the rest. That makes factors easier to describe. It does not make them more true.
Count equations against unknowns. The sample covariance of d neurons gives d(d + 1)/2 numbers. The model has d × m + d unknowns, minus m(m − 1)/2 that rotation removes. For one factor, d = 2 gives 3 equations for 4 unknowns: not enough, as Chapter 2 warned. d = 3 gives 6 for 6: just enough. For two factors you need d = 5, which gives 15 equations for 14 unknowns. This counting is a necessary condition, not a guarantee.
The failure to watch for is over-reading factor axes. Symptom: two analyses of the same data, or two random starts of EM, disagree about what factor 1 is. Measurement: compare AAT from the two fits. If it matches, the fits agree and only the axes differ. Fix: compare the subspaces, not the axes, or fix a rotation rule (such as varimax) before you compare.
Chapter 5
Turn the model around with Bayes’ rule and compute what the neurons say about the hidden driver
So far we ran the model forwards: pick a hidden state, get neural data. Now run it backwards. You recorded one trial, the two numbers x = (x1, x2). Where was the animal? The slide asks it as a bare question, p(z | x) = ?, and answers it in two lines.
The answer is called the recognition distribution: the distribution of the hidden factors given the data you saw. The word “recognition” is used because it recognises, from the neurons, what the hidden state was. You met the same object for mixtures of Gaussians, P(z = 2 | x). Here z is continuous, so the answer is a bell curve instead of a list of probabilities.
Bayes’ rule turns a forward model into a backward one. It says p(z | x) is proportional to p(x | z) p(z): the likelihood (how well z explains x) times the prior (how likely z was before we looked). Both are Gaussians that we know: N(x | Az, Ψ) and N(z | 0, I).
Write each Gaussian as exp of a quadratic. A Gaussian N(y | m, V) is proportional to exp(−½ (y − m)T V−1 (y − m)). So the product is exp of the sum of two quadratics in z. A sum of quadratics is one quadratic. And exp of a quadratic in z is a Gaussian in z. So the answer is Gaussian, and only its mean and covariance are left to find.
The trick is called completing the square: rewrite a quadratic so that it looks like (z − m)T V−1 (z − m). Then you can read the mean m and the covariance V straight off. The slide does it in six lines. Here they are, in words and symbols.
Line 1. Expand the likelihood and the prior inside the exponent: −½ (Az − x)T Ψ−1 (Az − x) − ½ zTz.
Line 2. Drop everything that does not contain z, because it only rescales the answer. What is left is −½ zT (ATΨ−1A + I) z + zT ATΨ−1 x.
Line 3. Name the bracket. Write Λ−1 = ATΨ−1A + I. The exponent is now −½ zT Λ−1 z + zT ATΨ−1 x.
Line 4. Compare with −½ (z − m)T Λ−1 (z − m), which expands to −½ zTΛ−1z + zT Λ−1 m + const. The cross terms match when Λ−1 m = ATΨ−1 x. So m = Λ AT Ψ−1 x.
The mean has a clear meaning. ATΨ−1x projects the data onto the loadings, but each neuron is divided by its noise variance first. The slide says it plainly: when inferring the latent from x, the components of x are downweighted in proportion to the amount of independent noise they contain. A noisy neuron gets a small vote. A quiet neuron gets a large one.
The covariance has a clear meaning too. Precision is the inverse of variance: high precision means high certainty. Independent sources of information add their precisions. The prior supplies 1. The neurons supply ATΨ−1A. More neurons, or quieter ones, mean a narrower posterior.
Use the lecture’s example again: A = (1, 2), Ψ = diag(100, 1). First, ATΨ−1A = 12/100 + 22/1 = 0.01 + 4 = 4.01. So Λ−1 = 5.01 and Λ = 0.1996. The posterior standard deviation is 0.447, less than half the prior’s 1.
Now the weights. Neuron 1 gets Λ × 1 / 100 = 0.0020. Neuron 2 gets Λ × 2 / 1 = 0.3992. Neuron 2 is quiet, so it has about 200 times more say. Take a trial with x = (5, 3). The mean is 0.0020 × 5 + 0.3992 × 3 = 0.010 + 1.198 = 1.208. Play with the numbers yourself.
The grey dashed curve is the prior for z. The teal curve is what the two neurons say about z. Below, the bars show how much each neuron contributes to the posterior mean. Drag the two responses, or make neuron 2 noisier.
The lecture’s example: A = (1, 2), noise variance 100 on neuron 1; you set the response of each neuron and the noise variance of neuron 2. The posterior comes from the formulas above, computed live. Both curves are drawn over z from −4 to 4.
Slide neuron 2’s noise from 1 up to 100, so that it is as noisy as neuron 1. The posterior widens. At 100 the mean for x = (5, 3) shrinks from 1.21 to 0.11 and the standard deviation climbs to 0.98, almost the prior’s 1. The neurons have little left to say, so you fall back on the prior.
For d neurons and m factors: Λ has shape (m, m). The weight matrix ΛATΨ−1 has shape (m, d), and it does not depend on x. Because Ψ is diagonal, Ψ−1 is just a divide by each variance. So decoding one trial is one small matrix-vector product: a linear decoder, in the sense of the linear decoders lesson, whose weights come from a model of the noise. The latent variable models lesson of the BCI series uses this idea on real recordings.
The failure to watch for is a decoded factor that looks too small. Symptom: when you compare the posterior means to the true factors in simulation, the slope is below 1. Measurement: regress the mean on the true value. For m = 1 the slope is ATΨ−1A / (ATΨ−1A + 1), which is 4.01/5.01 = 0.80 here. This is correct shrinkage toward the prior, not a bug. Fix, if you need the full size: add neurons or lower the noise.
Chapter 6
Alternate between guessing each trial’s driver and refitting the loadings until the likelihood stops rising
You have the data matrix X. You do not have A, and you do not have Ψ. This looks like a chicken and egg problem. If you knew A and Ψ, Chapter 5 would tell you the factors for every trial. If you knew the factors, you could fit A by regression and read off the leftover noise. You know neither.
EM breaks the circle by taking turns. Guess A and Ψ. Use the guess to infer the factors. Use the inferred factors to improve A and Ψ. Repeat. This is the EM algorithm from earlier in the course, now with every step in closed form. The lecture names the two halves of each turn the E-step and the M-step.
We want the parameters θ = {A, Ψ} that make the observed data most likely. The likelihood of one trial is an integral over the hidden factors: p(x | θ) = ∫ p(x | z, θ) p(z) dz. For Gaussians this integral is easy, and Chapter 2 solved it. But the lecture’s point is the method, because it carries over to models where the integral is hard.
EM raises a lower bound on the log-likelihood. The bound is the ELBO (evidence lower bound), which the slides also call the negative free energy F. It depends on the parameters θ and on a distribution q(zi) for each trial’s factors. The E-step improves F by choosing q. The M-step improves F by choosing θ. The likelihood never goes down.
Set each q(zi) equal to the recognition distribution under the current parameters: q(zi) = p(zi | xi) = N(μi, Λ). Chapter 5 gave the answer: Λ = (ATΨ−1A + I)−1 and μi = ΛATΨ−1xi. The slide adds a note: only the mean varies across datapoints. Every trial has the same Λ. The data enters only through μi.
Now freeze q and improve θ. Plug q into F. The only part that depends on θ is the expected log-probability of the data given the factors, Eq[log N(xi | Azi, Ψ)]. The slides expand it with Gaussian identities:
Take the derivative with respect to A, set it to zero, and solve. Then do the same for Ψ. The slide ends with two formulas:
 = (∑i xi μiT) (∑i μi μiT + NΛ)−1
Ψ̂ = diag( (1/N) ∑i xi xiT − (1/N) ∑i xi μiT ÂT )
Read the first as a regression. Regress each neuron’s data on the inferred factors. The usual least squares answer would be the cross-product of x and μ times the inverse of the factors’ own cross-product. The extra NΛ accounts for the fact that μi is only a best guess of zi. Without it, A would come out too large. Read the second as a leftover: each neuron’s total variance minus the part that A explains. Only the diagonal is kept, because Ψ is diagonal.
The shapes: μi has shape (m). Σ xiμiT has shape (d, m). Σ μiμiT + NΛ has shape (m, m). Â has shape (d, m). A useful trick: every sum over trials can be written with the data covariance S = (1/N) Σ xixiT, because μi is linear in xi. So you compute S once, and each EM turn costs a few small matrix products, whatever N is. The device below runs exactly this version, with one factor.
The data here is the hero’s: six neurons, one factor, and neuron 1 with noise variance 8. The start is deliberately wrong: loadings that point in nearly the wrong direction and a noise variance of 1 for every neuron. Press Step and watch both panels.
Left: the loadings of each neuron (length 1): true, EM so far, and PCA for contrast. Right: the log-likelihood per trial after each EM turn, with the best PPCA can do and the truth as dashed lines. Press Step, or Run to play.
Simulated: 400 trials, true loadings 0.9, 0.6, 1.0, 0.5, 0.8, 0.7, noise variance 8 on neuron 1 and 0.3 on the others. EM starts from loadings (−0.4, 0.3, −0.2, 0.5, 0.1, −0.3) and noise variance 1. The log-likelihood is the average over trials of the Gaussian log-density of the fitted covariance.
At turn 0 the loadings match the truth at only 0.17 and the log-likelihood is −11.99 per trial. After 1 turn it is −9.03. After 5 turns the match is 0.996 and the likelihood is −7.79. After 20 turns it reaches −7.748 and stops moving. The fitted noise variance for neuron 1 is 8.38, near its true 8. The dashed PPCA line sits at −8.99: forcing equal noise costs about 1.2 nats per trial here. (A nat is the unit of log-likelihood with natural logs.) The fit even beats the true parameters, at −7.758, because it adapts to the particular 400 trials you drew.
Compare the bars. The teal EM bars settle onto the purple truth. The warm PCA bars do not: PCA matches the truth at 0.66 on this data. EM knows neuron 1 is noisy. PCA does not.
The failure to watch for is a noise variance that collapses to zero. Symptom: one neuron’s fitted Ψ shrinks toward 0, and its loading grows to explain it entirely. This is called a Heywood case. Measurement: print the fitted Ψ and watch for values near 0. Fix: set a small floor under every Ψ (the device uses 0.001), or add a prior on Ψ. A second worry is a local maximum; run EM from several starts and keep the best likelihood.
Chapter 7
Force every neuron to share one noise variance and see what the model gains and what it loses
The lecture splits here: Part II: Probabilistic PCA. Imagine you record from sixty electrode channels of one array. The channels are built the same way and sit in the same tissue. You might reasonably expect each to have about the same noise. If that is true, you can fit a simpler model, and you can fit it in one step instead of many EM turns.
The simpler model is probabilistic PCA (PPCA), introduced by Tipping and Bishop in 1999, as the slide credits. It is factor analysis with one extra rule: every neuron has the same noise variance.
Factor analysis has a separate noise variance for each neuron: Ψ = diag(σ12, …, σd2). PPCA ties them together: Ψ = σ2I, where σ2 is one number and I is the identity. The slide highlights it in red: identical noise vars! The generative recipe of Chapter 1 stays the same. Only the noise step changes: every neuron gets noise drawn with the same variance.
The slide’s key result is that the answer comes from an eigendecomposition of the data covariance, just like PCA. The slide writes the data covariance as the sum of xixiT and says its eigenvectors give the estimate for the singular vectors of A. There is no loop and no starting guess, and the answer is the same every time. Chapter 8 derives it and gives the noise estimate too.
You also keep everything that makes factor analysis useful. PPCA is a full probability model. It has a likelihood, so you can compare two choices of m by how well each predicts held-out trials. It has a recognition distribution, so you get uncertainty on every trial’s factors. Plain PCA offers neither. That is what “probabilistic” buys you.
You lose the flexibility that Chapter 3 praised. If one neuron really is much noisier than the others, PPCA must pick one compromise noise level. That compromise is too high for the quiet neurons and too low for the loud one. The fitted direction then drifts toward the loud neuron, just as PCA’s did. In fact PPCA and PCA agree on the direction exactly, because both use the same eigenvectors.
Try it. The slider sets how unequal the six neurons’ noise is. At 0 all six have noise variance 0.3. As you raise it, the noise levels fan out.
Yellow bars are each neuron’s true noise variance. Teal bars are what factor analysis estimates. The warm line is PPCA’s one shared noise level. Drag the spread and watch the line stop fitting.
Simulated: 400 trials, six neurons, the lesson’s true loadings. Neuron j has noise variance 0.3 × exp(spread × uj) with u = (0, 0.8, 1.6, 0.3, 1.2, 0.5). Factor analysis is fitted by 80 steps of EM; PPCA uses the closed form of Chapter 8. Log-likelihoods are per trial, in nats.
At spread 0 the picture is simple. The warm line runs through the tops of all the yellow bars, the two methods find the same loadings (match 1.000), and their likelihoods agree at −6.21. PPCA gives up nothing.
At spread 1 the noise levels run from 0.30 to 1.49. PPCA picks 0.69 and its loadings match the truth at 0.994, while factor analysis matches at 0.999. The likelihood gap is 0.21 nats per trial. At spread 2 the noise runs from 0.30 to 7.36. PPCA’s single level is 1.68, its match with the truth falls to 0.772, and the likelihood gap is 0.72 nats per trial. Factor analysis still matches at 0.996.
So the choice is a bet on your recording. If the neurons are alike in noise, PPCA is as good and much cheaper. If they are not, pay for the extra parameters. A neat feature: because PPCA is a special case of factor analysis, the factor analysis likelihood is always at least as high. The question is whether the gain is worth the extra d − 1 parameters, and held-out data can answer it.
The failure to watch for is a shared noise level that fits nobody. Symptom: PPCA’s noise estimate is larger than the true noise of most neurons, and its loadings lean toward one neuron. Measurement: fit factor analysis too and compare the fitted noise variances. If they differ by a large factor between neurons, the equal-noise rule is false. Fix: use factor analysis, or standardise first and check again.
Chapter 8
Derive why PPCA needs no EM, and read the noise variance off the tail of the spectrum
You have 400 trials from six neurons. You believe the PPCA story with two factors. Someone hands you the covariance matrix of the data and asks for A and σ2. The slides call the derivation “quick,” and it is: five lines, one fact about eigenvectors, and no iteration.
Two ideas from earlier lectures are enough. The singular value decomposition (SVD, Lecture 2) writes any matrix as a rotation, a stretch along axes, and another rotation: A = USVT. Here the columns of U are the left singular vectors (directions in neuron space), S is a diagonal table of singular values s1, …, sm (the stretches), and V is a rotation of the factors.
An eigenvector of a square matrix M is a direction that M only stretches: Mv = λv. The stretch λ is its eigenvalue. The covariance matrix of the data has d eigenvectors and d eigenvalues. PCA is the act of listing them from the largest eigenvalue down.
Line 1. The marginal likelihood says x ~ N(0, AAT + σ2I), so the model’s covariance is cov(x) = AAT + σ2I.
Line 2. Put in the SVD of A. AAT = (USVT)(VSUT). Since V is orthogonal, VTV = I, and this collapses to US2UT. So cov(x) = US2UT + σ2I. The rotation V disappeared. That is Chapter 4 again: V is the rotation we can never learn.
Line 3, the fun fact. Adding a multiple of the identity does not change eigenvectors. If Mv = λv, then (M + aI)v = Mv + av = (λ + a)v. The same v, with every eigenvalue shifted by a.
Line 4. Apply it with M = US2UT and a = σ2. The eigenvectors of cov(x) are the columns of U. Its eigenvalues are si2 + σ2 along those m directions, and exactly σ2 along every other direction.
Line 5. So eig(cov(x)) = eig(US2UT + σ2I) = U. The eigenvectors of the data covariance are the singular vectors of A. This is the slide’s key result.
Now go from the model to data. Compute the sample covariance of your data, and find its eigenvalues λ1 ≥ … ≥ λd and eigenvectors b1, …, bd. The slide turns the derivation into three rules, credited to Tipping and Bishop.
Why the average? In the model, all d − m small eigenvalues equal σ2. In real data they scatter around it by chance. The average is the maximum likelihood answer. Why subtract before the square root? A top eigenvalue is si2 + σ2: signal plus noise floor. Subtracting the floor leaves the signal. Then  = ÛŜ, up to the rotation.
The device uses data with two true factors and equal noise 0.3 on six neurons. Its covariance has six eigenvalues. Choose how many factors m you believe. Everything outside the top m is declared noise.
Each bar is one eigenvalue of the data covariance, largest first. The warm line is the PPCA noise estimate: the average of the bars to its right. Purple is the part of a bar above the line, the signal. Drag the number of factors.
Simulated: 400 trials, six neurons, two true factors with invented loadings, equal noise variance 0.3. The eigenvalues of the sample covariance are 4.83, 2.36, 0.35, 0.32, 0.29 and 0.25.
With m = 2 the four small eigenvalues average to 0.301, almost exactly the true 0.3. The loading lengths are √(4.83 − 0.30) = 2.13 and √(2.36 − 0.30) = 1.44. Now pick m = 1. The second factor is forced into the noise: the floor jumps to 0.713, more than twice the truth, and the single loading length is 2.03. Pick m = 3 and the floor barely moves (0.284), with a third loading of only 0.26. A floor that holds steady as you add factors is a hint that the extra factors are noise.
Apply the rules to the covariance [[101, 2], [2, 5]] from Chapter 2, with d = 2 and m = 1. The eigenvalues are 101.04 and 4.96. So σ̂2 = 4.96 and ŝ = √(101.04 − 4.96) = 9.80. The top eigenvector is about (1.00, 0.02), so  is about (9.80, 0.20). PPCA reports noise 4.96 on both neurons and a loading almost entirely on neuron 1.
The truth was A = (1, 2) with noise (100, 1). Both explanations give the same covariance: AAT + σ2I = [[101.0, 1.96], [1.96, 5.0]]. The data cannot tell them apart without extra assumptions. PPCA’s assumption of equal noise is false here, so it names the wrong story. This is Chapter 3’s warning in numbers.
pythonimport numpy as np
def ppca(X, m): # X: (N, d), mean already removed
S = X.T @ X / len(X) # data covariance, (d, d)
lam, B = np.linalg.eigh(S) # ascending order
lam, B = lam[::-1], B[:, ::-1] # largest first
sigma2 = lam[m:].mean() # average of the d - m smallest
s = np.sqrt(lam[:m] - sigma2) # signal lengths, (m,)
A = B[:, :m] * s # loadings up to a rotation, (d, m)
return A, sigma2
The failure to watch for is a sloppy choice of m. Symptom: the noise estimate jumps when you change m by one. Measurement: plot the eigenvalues, as the device does, and look for the elbow where they flatten. Fix: pick m at the elbow, and confirm on held-out trials that the likelihood stops improving.
Chapter 9
Replace the straight map from driver to neurons with a curved one, and see why the next lecture needs a deep network
Picture a population of head direction cells. Each fires when the animal faces one compass direction. As the animal turns through a full circle, the population’s activity traces a loop in neuron space. The hidden variable is one number, the angle. Yet the cloud of data is a ring, not a straight line.
Factor analysis cannot draw a ring. Its recipe is x = Az + ε, and Az is always a straight line, flat plane, or flat hyperplane through the origin. The last three slides of the lecture, a warm-up for Lecture 20, ask what you would change.
Slide 21 redraws the PPCA model as a small diagram with three parts. On the left sits the latent z, low-dimensional, drawn from N(0, I). On the right sits the data x, high-dimensional. A box labelled A connects them. The data given z is N(Az, σ2I).
This is the same model as before, drawn as a flow: z goes in, one linear layer A turns it into a mean, and noise of variance σ2 is added. Seen this way, A is a decoder. It decodes a short code z into a long recording x.
Slide 22 shows the VAE generative model (variational autoencoder, the topic of Lecture 20). It looks almost identical. The only change is the box: x = fθ(z) + ε, with ε ~ N(0, σ2I). The slide names it key idea #1: replace linear mapping with a deep neural network. The weights of the network are θ.
Nothing else needs to change in the story. The latent is still drawn from N(0, I). The noise is still Gaussian. But the mean of x given z is now a curve (or a curved surface) through neuron space. A ring is one point of z bent around a circle. A network with enough layers can draw it.
The device bends a one-factor model. The hidden z is drawn as before, but the two neurons follow x = (z, b(z2 − 1)/√2) plus noise of variance 0.0625. Raise the bend b and see what PPCA does.
Blue dots are trials from two neurons. The purple curve is the true map from z to the neurons. The warm line is the best straight line, found by PPCA. Drag the bend from straight to curved.
Simulated: 250 trials, one factor, two neurons. The curve is (z, b(z² − 1)/√2) for z from −2 to 2; the noise variance is 0.0625 on each neuron. PPCA with one factor is fitted live in the closed form of Chapter 8. This toy is not a VAE; it shows only what a straight decoder cannot do.
At bend 0 the data is a straight band along the first neuron. PPCA draws the line through it, and its noise estimate is 0.05, close to the true 0.0625. At bend 0.4 the band curls. The line still runs through the middle, but dots sit well off it at both ends, and the noise estimate has risen to 0.26. At bend 0.8 the data is a clear arc. The straight line cuts across it and PPCA reports a noise variance of 0.79, about 13 times the truth.
Notice what went wrong. PPCA did not fail by a small error. It blamed the curvature on noise. The part of the arc that a line cannot reach shows up as a big noise variance. A correct curved decoder would leave only the 0.0625.
Three things from today carry over. The latent prior N(0, I) stays. The Gaussian noise stays. And the training goal stays: raise a bound on the likelihood, the ELBO of Chapter 6. One thing breaks. Chapter 5 completed a square in z because the exponent was quadratic in z. With a network fθ, the exponent contains ‘x − fθ(z)’ squared, which is not quadratic in z. The exact recognition distribution is gone. Lecture 20 shows how the VAE deals with that. For the PPCA of this lesson, see also the VAE and VQ-VAE lesson, which carries the idea forward.
The failure to watch for is forcing a curved population through a linear model. Symptom: you need many factors to reach a good fit. Measurement: the eigenvalues have no clear elbow, and the noise estimate keeps falling as you add factors. Fix: ask whether the population lies on a curve, ring or surface, and consider a nonlinear decoder.
Chapter 10
Review the numbers, terms and code, and see where to go next
You can now rebuild Lecture 19 from memory. A population of neurons is explained by a few shared factors plus private noise. Run forwards, the model is x = Az + ε, with covariance AAT + Ψ. Run backwards, Bayes’ rule gives a Gaussian over the factors. EM fits A and Ψ by alternating those two views. PPCA ties all the noise variances together and then needs only an eigendecomposition. The VAE keeps the shape and bends the map.
Factor analysis draws z ~ N(0, I), scales it by the loadings A (shape d × m), and adds noise with diagonal covariance Ψ (the uniquenesses). Its marginal is N(0, AAT + Ψ): low rank plus diagonal. It is identifiable only up to a rotation of the factors. The recognition distribution is N(ΛATΨ−1x, Λ) with Λ = (ATΨ−1A + I)−1. EM uses it as the E-step and refits A and Ψ in the M-step. Probabilistic PCA sets Ψ = σ2I, so the fit is the top eigenvectors of the data covariance, with σ2 the average of the remaining eigenvalues.
| What | Number | Why it matters |
|---|---|---|
| Lecture example, covariance | A = (1, 2), Ψ = diag(100, 1) gives [[101, 2], [2, 5]] | Low rank plus diagonal, built from four numbers |
| Top PC against loading direction | 1.2 degrees against 63.4 degrees | PCA follows the noisy neuron, not the shared signal |
| Decoding weights, same example | 0.0020 and 0.3992; Λ = 0.1996; x = (5, 3) gives 1.208 | A neuron with 100 times the noise gets about 200 times less say |
| Parameters, d = 6, m = 1 | 12 in factor analysis, 21 in a full covariance | Structure saves data: 600 against 5,050 for 100 neurons and 5 factors |
| Enough neurons to identify | d = 3 for m = 1; d = 5 for m = 2 | Counting equations against unknowns (necessary, not sufficient) |
| EM on the device data | −11.99 to −7.748 per trial in 20 turns | The likelihood only rises; PCA matches the truth at 0.66 |
| PPCA noise estimate, m = 2 | 0.301 against a true 0.300; with m = 1, 0.713 | The floor is the average of the eigenvalues you call noise |
| Unequal noise, spread 2 | PPCA match 0.772, factor analysis 0.996, gap 0.72 nats | Equal noise is a bet, and it can lose |
| Curved data, bend 0.8 | PPCA noise 0.79 against a true 0.0625 | A straight decoder blames curvature on noise |
| Term | Meaning |
|---|---|
| Factor (latent) | A hidden number per trial that several neurons share; z in the recipe |
| Loadings | The matrix A: how strongly each neuron follows each factor |
| Uniquenesses | The diagonal of Ψ: each neuron’s own noise variance |
| Marginal | The distribution of the data with the factors integrated out: N(0, AAT + Ψ) |
| Recognition distribution | p(z | x): what the neurons say about the factors on one trial |
| Identifiable up to rotation | A and AU give the same data distribution for any orthogonal U |
| E-step and M-step | Infer each trial’s factors; then refit A and Ψ with the factors held fixed |
| PPCA | Factor analysis with Ψ = σ2I; fits in closed form by eigendecomposition |
| VAE decoder | PPCA with the linear map replaced by a deep network fθ |
Factor analysis by EM, for any number of factors, in the form of Chapter 6. It uses only the data covariance S, so each turn costs the same however many trials you have. This is a sketch: it has no convergence test, and its random start is the simplest possible.
pythonimport numpy as np
def fa_em(X, m, iters=200, seed=0): # X: (N, d), mean already removed
N, d = X.shape
S = X.T @ X / N # data covariance, (d, d)
A = np.random.default_rng(seed).normal(size=(d, m)) * 0.5
psi = np.diag(S) / 2 # noise variances, (d,)
for _ in range(iters):
W = A / psi[:, None] # Psi^-1 A, (d, m)
Lam = np.linalg.inv(A.T @ W + np.eye(m)) # posterior covariance, (m, m)
B = Lam @ W.T # Lam A^T Psi^-1, (m, d): mu_i = B x_i
SB = S @ B.T # (1/N) sum x_i mu_i^T, (d, m)
A = SB @ np.linalg.inv(B @ SB + Lam) # M-step for A, (d, m)
psi = np.maximum(np.diag(S - A @ SB.T), 1e-3) # M-step for Psi, with a floor
return A, psi
def recognise(x, A, psi): # E-step for one trial x, (d,)
W = A / psi[:, None]
Lam = np.linalg.inv(A.T @ W + np.eye(A.shape[1]))
return Lam @ W.T @ x, Lam # posterior mean (m,), covariance (m, m)
Earlier lectures asked why hidden-variable models are hard, and gave EM and sampling. This lecture shows the case where nothing is hard: a Gaussian hidden variable with a linear map, where every step has a formula. The price is the straight line, which Lecture 20’s VAE removes. Adding time to the same idea gives hidden states that evolve and generate the neurons. The Kalman filter is the linear Gaussian version of that picture.
Two honest limits. This lesson re-teaches the slides and checks every number by computation, but it did not draw on a separate source for the PPCA derivation; the slides credit Tipping and Bishop (1999), whose paper “Probabilistic Principal Component Analysis” (Journal of the Royal Statistical Society B, 61(3), 611 to 622) is the primary source to read. And every toy dataset here is simulated, as each device says.
Now press Present or Teach and explain the model from memory: the three-step recipe, why the covariance is low rank plus diagonal, why PCA is fooled by a loud neuron, what rotation cannot change, how the recognition mean downweights noisy neurons, and why PPCA needs only eigenvalues. Then go back to the hero and drag the noise again.