Neuroscience Applications of PCA and Least Squares

Motor cortex can plan a reach while the muscles stay still, because the muscles read only one direction of the population. Least squares and PCA find that direction.

Learn how two old tools, regression and principal components, found a hidden direction in a monkey’s motor cortex and showed that a mouse’s whole cortex is full of movement.

Press Prepare, then Move, and slide the direction. Watch two neurons change while the muscle bar stays put. Then we build, piece by piece, the regression that finds the muscle direction, the PCA that makes it findable, and the three papers that used both.

You need the idea of a firing rate (spikes per second) and a little school algebra. We build vectors, matrices, regression and PCA from zero.

Based on Lecture 5 of Princeton NEU 560, Statistical Modeling and Analysis of Neural Data (Spring 2024), taught by Jonathan Pillow, and the two papers it covers in depth: Kaufman et al. 2014 and Musall et al. 2019. Lecture slides. Every idea is re-taught here in our own words and devices. It follows Lecture 4, Least Squares.

Change the population, spare the muscle

135°
1.00

Illustrative toy from the lecture’s own example: the muscle is the sum of two neurons, M = N1 + N2. Both neurons start at 1 spike per second, a made-up baseline. At 135 degrees the change cancels in the sum; at 45 degrees it adds.

Chapter 0

One Table, Two Tools, Three Papers

See how a block of spike counts turns into a question, and why two tools from linear algebra answer most of those questions

Picture a neuroscientist at the end of a recording day. A monkey reached for a target about two hundred times. Electrodes in its motor cortex listened to 100 neurons the whole time. The scientist has a folder of files and one question: what was the brain doing?

Every file holds the same kind of thing. A neuron is a cell that sends short electrical pulses called spikes. Count the spikes in each slice of time, say 10 milliseconds, and divide by the slice length. The result is a firing rate, in spikes per second. Do this for every neuron and every slice, and the day becomes a table.

rows = neurons, columns = time slices  →  N [100 neurons × 5,000 slices]

A table of numbers is not an answer. You need a way to ask it things. This lecture teaches two ways, and then shows what they found in three real studies. We call them tools because each one takes a table in and hands a small, readable thing back.

Tool one: regression asks “what predicts what?”

Regression predicts one list of numbers from another. You give it inputs, such as the light shown to an eye, and outputs, such as a neuron’s rate. It finds the weights that turn inputs into the best possible guess of the outputs. The “best” guess is the one with the smallest total squared error, so the method is called least squares. Chapters 1 to 3 revisit it with two proofs.

Tool two: PCA asks “where does the table vary most?”

PCA, short for principal component analysis, has no inputs and outputs. It looks at one table and finds the directions along which the numbers spread out most. A direction here means a recipe: a weighted sum of all the neurons. The first such recipe is the first principal component. PCA is the subject of Lecture 3, and our PCA lesson builds it from zero. Chapter 4 uses it on faces.

The two tools can look alike on a plot, so it helps to see them side by side before going further. Take two neurons that tend to fire together. Slide the link between them from weak to strong, and compare what each tool draws.

Draw both tools on one cloud

Each dot is one time slice: neuron 1’s rate across, neuron 2’s rate up. The warm line is regression. The purple line is the first principal axis. Slide the link, then flip which neuron is predicted.

0.60

Toy data: 60 made-up time slices from two neurons, seeded so they are the same on every visit. Both neurons are scaled to the same spread. The regression slope and the axis angle are computed live from the dots.

Notice two things. Regression depends on the question: predicting neuron 2 from neuron 1 gives a different line from predicting neuron 1 from neuron 2. The principal axis does not change, because it never asked a question. It only describes the cloud.

The three papers

The lecture first reviews least squares with two proofs, then shows three papers that put the tools to work. The slide deck runs 44 slides in four parts.

  1. Slides 2 to 12, the proofs. Two ways to show that the best weights are (XᵀX)⁻¹XᵀY.
  2. Slides 14 to 21, paper 1. Turk and Pentland (1991) used PCA on face photos, so a face becomes a short list of numbers.
  3. Slides 22 to 37, paper 2. Kaufman, Churchland, Ryu and Shenoy (2014) used regression and PCA to find a direction in motor cortex that muscles cannot see.
  4. Slides 38 to 44, paper 3. Musall, Kaufman, Juavinett, Gluf and Churchland (2019) used regression with video PCA to show that a mouse’s cortex mostly tracks what the mouse is doing.

The lecture itself carries no logistics, only these slides. The course site, linked in the hero above, has the full syllabus and the notes. Everything here is re-taught in our own words and devices.

One plain fact ties the three papers together. Each starts with a table of neural activity and a question about it. Each answers with a small, linear piece of maths. And each answer changes how you read the table. That pattern is the whole lecture.

The road

  1. The least-squares question: inputs, outputs, weights and squared error.
  2. Proof one, geometry: the best guess is a shadow, and the miss is a right angle.
  3. Proof two, calculus: slide to the bottom of the bowl, and when the bowl breaks.
  4. Eigenfaces: PCA turns a photo into a short list of numbers.
  5. Preparing without moving: the puzzle of motor cortex.
  6. Output-null dimensions: the muscles add, so some changes cancel.
  7. Finding the directions: principal components regression and the tuning ratio.
  8. What the result does not show: trial averages, validation, and how many PCs.
  9. Behaviour as regressors: a design matrix built from video.
  10. The mouse is moving: the numbers that surprised a field.
  11. Field guide: numbers, checklist, code, and links onward.
You have a table of 100 neurons over 5,000 time slices and no outputs to predict. Which tool describes where the activity varies most?

Chapter 1

The Least-Squares Question

Turn “find the best line” into one number to minimise, and meet the formula that minimises it

You show a monkey a patch of light at four brightness levels, labelled 1, 2, 3 and 4. For each trial you count the spikes one visual neuron fires. The counts are 2, 3, 7 and 8. The neuron clearly likes brighter light. But how much more does it fire for each step of brightness? Four dots will not give a perfect line, so you need a rule for choosing one.

That rule is least-squares regression, and slides 2 to 4 of the lecture restate it. It starts with names for the pieces. An input is what you control or measure, here the brightness. An output is what you want to predict, here the spike count. A weight says how much the output moves per unit of an input. Regression finds the weights.

Inputs as rows, outputs as a column

With many trials and many inputs, we stack the numbers into two blocks. The design matrix X has one row for each trial. Each row, written x⃗ᵢ, lists that trial’s inputs. The vector Y has one entry for each trial, the output yᵢ. If there are N trials and d inputs, X has N rows and d columns, and Y has N entries.

The weights form a vector w with d entries. A trial’s prediction is the dot product of its row with the weights: multiply matching entries, then add. For one input that is just “weight times brightness”. For two inputs it is “weight one times input one, plus weight two times input two”.

Why we square the misses

A prediction is rarely exact. The gap between the true output and the prediction is the residual, rᵢ = yᵢ − x⃗ᵢ · w⃗. A residual can be positive or negative, so adding raw residuals lets misses cancel. Squaring makes every miss positive. It also punishes a big miss far more than a small one: a miss of 2 costs 4, a miss of 4 costs 16.

squared error
The single number we want small. The lecture labels it as equivalent to minimising the squared residuals.
∑i=1N
Add up the term after it for every trial, from the first (i = 1) to the last (i = N).
yi
The true output on trial i, such as a spike count.
x⃗i · w⃗
The prediction for trial i: the dot product of that trial’s input row with the weights.
‖Y − Xw⃗‖2
The same sum in one matrix expression. Xw gives all N predictions at once, and the double bars mean squared length.

Now play with it. The device below holds the four brightness trials. You choose a slope and an offset, and it draws each residual as a square. The total area of the squares is the squared error. Try to make that area as small as you can.

Shrink the squares

Blue dots are trials. The warm line is your guess. Each yellow square has a side equal to one residual. Slide the weight and the offset to shrink the total area, or press Snap to best.

1.00
2.00

Toy numbers: brightness 1, 2, 3, 4 with spike counts 2, 3, 7, 8, made up for this lesson. The wild trial adds brightness 5 with a count of 1. The best line is computed live with the normal equations of Chapter 3.

The answer, and a worked example

The lecture gives the minimiser in one line: w⃗ = (XᵀX)⁻¹ XᵀY. Chapters 2 and 3 prove it two ways. Here we only use it, with every step shown, on the four trials. Add a column of ones to X so the line can have an offset. Then X has four rows and two columns, and w holds a slope and an offset.

X = [1 1; 2 1; 3 1; 4 1]      Y = [2, 3, 7, 8]
XᵀX = [30 10; 10 4]            (30 = 1+4+9+16, 10 = 1+2+3+4, 4 = four ones)
XᵀY = [61, 20]                 (61 = 2+6+21+32, 20 = 2+3+7+8)
det = 30·4 − 10·10 = 20        (XᵀX)⁻¹ = (1/20) [4 −10; −10 30]
w   = (1/20) [4·61 − 10·20, −10·61 + 30·20] = [2.2, −0.5]

So the best line is a count of 2.2 times the brightness, minus 0.5. Its predictions are 1.7, 3.9, 6.1 and 8.3. The residuals are 0.3, −0.9, 0.9 and −0.3. Squared, they are 0.09, 0.81, 0.81 and 0.09, and they sum to 1.8. No other line can do better on these four dots.

Read the real-world meaning too. Each extra brightness step adds about 2.2 spikes. That is a claim about the neuron, not just a line on a plot.

The same recipe scales up. Suppose you also log the monkey’s pupil size on each trial. That adds a third column to X, and w gains a third entry. Nothing else changes: XᵀX becomes a 3 by 3 table, and the formula still returns one weight per column. With 100 neurons as inputs, X has 100 columns and w is a list of 100 numbers, one per neuron. That is the setting of Chapter 6, where neurons are the inputs and a muscle is the output. One habit helps: write the shape next to every symbol before you compute. X [N × d] times w [d] gives N predictions.

When the fit fools you

Here is the failure to expect. The symptom: the line tilts toward one odd trial and misses the others. The measurement: press Add a wild trial above. One extra dot at brightness 5 with a count of 1 drops the best slope from 2.20 to 0.30 and raises the best squared error from 1.8 to 37.9 (the device computes both live). That one trial now owns most of the squared error. The fix: always look at the residuals, not only the line. A single huge square means one trial is steering the fit. Then ask whether that trial is a recording error or a real, rare event. Later lectures add tools for this, such as regularisation.

Why does least squares square each residual before adding them?

Chapter 2

Proof One: The Best Guess Is a Shadow

Picture all your trials as one point in space, and see why the closest reachable point leaves a right-angled miss

Stand in a room with a torch overhead and a small ball in the air. The ball casts a shadow on the floor. Of all the points on the floor, the shadow is the nearest one to the ball, and the line from ball to shadow hits the floor at a right angle. Least squares is exactly this picture, drawn in a space with one axis for each trial.

One point for all the trials

Take the two-trial case. Trial 1 gave a spike count of 2 and trial 2 gave 3. Draw a plane with trial 1 across and trial 2 up. The whole output list Y = (2, 3) is now one point. With N trials the point lives in N dimensions, which you cannot draw, but the logic is the same.

Each column of X is a point in that same space too. In the two-trial case, one input column is a single arrow, say (3, 1): the brightness on trial 1 and on trial 2. Multiplying that arrow by a weight w stretches it. So the predictions Xw can only land on a line through the origin along that arrow. The set of all reachable predictions is the column space of X: every weighted sum of its columns. With two input columns it is a flat sheet, and with d columns a d-dimensional sheet.

That is the whole limit of a linear model. It can only predict points inside its column space. Real data points almost never sit exactly there, because of noise, so there is always a miss.

Closest point, right angle

Least squares asks for the reachable point nearest to Y. Squared error is just the squared distance from Y to the prediction, so “smallest squared error” means “nearest point on the sheet”. That nearest point is the shadow of Y on the sheet, and the residual vector from the shadow up to Y stands at a right angle to the sheet.

Try it. The device below uses one input column, (3, 1), and an output point whose second coordinate you can move. Slide the weight and watch the residual arrow. When it turns square against the line, the squared error stops falling.

Find the shadow

The grey line is every prediction the weight can reach. The blue dot is the true output Y. Slide the weight along the line. The yellow arrow is the residual. The number in the read-out is its dot product with the input column.

0.30
3.0

Toy numbers: input column (3, 1), trial 1 count fixed at 2, trial 2 count set by the slider. The best weight is the dot product of Y with the column divided by the column’s dot product with itself. Counts are made up.

At the best weight the dot product reads zero. That is the right angle written as arithmetic: two arrows are perpendicular exactly when their dot product is zero. Away from it, the dot product is not zero, and the sign tells you which way to slide.

From the right angle to the formula

Now turn the picture into algebra. The residual is Y − Xŵ, where the hat marks the best weights. It must be perpendicular to every column of X, not just one. The lecture writes the condition for column i as a dot product, and slide 8 stacks all of them.

X⃗i · (Y − Xŵ) = 0
Column i of X, now written as an arrow, is perpendicular to the residual. One such statement for each of the d columns.
XT(Y − Xŵ) = 0
The same d statements in one line. Transposing X turns its columns into rows, so each row dotted with the residual gives one zero.
XTX ŵ = XTY
Multiply out and move one term across. These are the normal equations: d equations for d unknown weights.
ŵ = (XTX)−1XTY
Undo the matrix XTX by multiplying with its inverse. This needs the inverse to exist, which Chapter 3 discusses.

Check it on Chapter 1’s four trials. The best residuals were 0.3, −0.9, 0.9 and −0.3. Dot them with the brightness column (1, 2, 3, 4): 0.3 − 1.8 + 2.7 − 1.2 = 0. Dot them with the column of ones: 0.3 − 0.9 + 0.9 − 0.3 = 0. Both columns see a zero. Nothing the model can express is left in the miss.

That last sentence is the practical meaning. The residual is whatever the inputs cannot explain. If it still correlated with an input, you could add a bit of that input to the weights and do better. The right angle says there is nothing left to add.

Here is one more way to feel it. Hold a flat card at arm’s length and ask which point on the card is closest to your nose. You do not search the whole card. You slide your finger until the line to your nose meets the card at a right angle, then you stop. Least squares runs the same search in N dimensions, and the normal equations are the finger’s stopping rule. This also shows when the error is exactly zero: only when Y already lies on the sheet, so the outputs are an exact weighted sum of the input columns.

Where it can fail

The symptom: your fitted weights look wild, perhaps huge with opposite signs, yet the predictions are fine. The measurement: the shadow is unique, but the weights that build it need not be. If two columns point the same way, many weight pairs give the same shadow. The fix: check whether columns of X are nearly parallel before you trust single weights. Chapter 3 shows the exact test.

At the least-squares weights, how does the residual vector Y − Xŵ relate to the columns of X?

Chapter 3

Proof Two: Slide to the Bottom of the Bowl

Reach the same formula by finding where the error stops falling, and learn the one condition that breaks it

Drop a marble into a smooth bowl. It rolls down and stops at the lowest point, where the floor is flat. Squared error, seen as a function of the weights, is a bowl. The best weights sit at the bottom. At the bottom the slope is zero in every direction, so we can find it by asking where the slope vanishes. That is the second proof on the slides.

The plan, in two steps

Slide 9 states the goal: find the minimum of ‖Y − Xw‖². The approach has two steps. First, take the derivative with respect to w and set it to zero. Second, solve for w. A derivative says how fast a quantity changes when you nudge one input. When w is a list of weights, the list of all those rates is the gradient, written with a nabla symbol, and slide 10 names it as the vector of partial derivatives.

Slide 10 then gives two facts about gradients, and both are one-variable facts in disguise. Fact one: for a linear function a⃗ · x⃗, the gradient is just a⃗. It is the vector version of “the slope of 3x is 3”. Fact two: for a quadratic function x⃗ᵀAx⃗ with A symmetric, the gradient is 2Ax⃗. It is the vector version of “the slope of ax² is 2ax”.

Expand, differentiate, solve

Slide 11 expands the squared error. A squared length is a vector dotted with itself, so ‖Y − Xw‖² = (Y − Xw)ᵀ(Y − Xw). Multiply it out and you get three terms.

‖Y − Xw‖2
The squared error, as a function of the weights w.
YTY
The squared length of the outputs. It does not contain w, so its derivative is zero. On slide 12 the lecture crosses it out.
2wTXTY
A linear term in w. By fact one, its gradient is 2XTY.
wTXTX w
A quadratic term in w, with A = XTX. By fact two, its gradient is 2XTX w.

Slide 12 differentiates and sets the result to zero: −2XᵀY + 2XᵀXw = 0. Divide by 2 and move one term across to get XᵀXw = XᵀY. These are the same normal equations the geometry gave in Chapter 2. Multiply both sides by the inverse of XᵀX and out comes ŵ = (XᵀX)⁻¹XᵀY. Two completely different routes reach one formula, which is why we trust it.

The footnote that matters

Slide 12 ends with a warning, and a builder should read it twice. The formula requires XᵀX to be invertible, meaning a matrix that can be undone. In practice it must be well-conditioned, meaning not close to non-invertible. The lecture promises more when it covers regularisation. We can see the problem now.

The trouble starts when two input columns carry almost the same information. Think of two neurons that nearly always fire together, so you use both as inputs. The data cannot tell whether neuron 1 or neuron 2 drove the output. Many weight pairs fit equally well. The bowl then has a long, flat valley instead of a round dip, and the marble can stop almost anywhere along it.

The device below makes the valley visible. It builds a fresh set of 40 trials, fits the weights, and repeats 40 times. The true weights are (1, 1), and the noise is fixed. Each dot is one refit. Raise the link between the two neurons and watch the dots smear along a line.

Refit until the bowl breaks

Each blue dot is the pair of weights fitted to one fresh set of 40 trials. The cross marks the truth, (1, 1). The warm ellipse is the spread of the dots. Slide the link between the two neurons up toward 1.

0.20

Toy simulation, seeded: output = neuron 1 + neuron 2 + noise with spread 1, both neurons with spread 1. The ridge button adds 10 to the diagonal of XTX before inverting, a preview of regularisation. The condition number is the ratio of the two eigenvalues of XTX.

Look at the two numbers in the read-out. When the link is high, each single weight wanders widely, but their sum stays steady. The data does pin down “neuron 1 plus neuron 2”. It cannot pin down how to split the credit. A big condition number (the ratio of the largest to the smallest eigenvalue of XᵀX) warns you in advance.

Two practical notes. First, good code does not compute the inverse of XᵀX directly. Solving the equations XᵀXw = XᵀY in place is faster and loses less accuracy, so the code in Chapter 11 calls a solver. Second, the bowl picture holds because squared error is a quadratic function of w, so it has exactly one bottom whenever XᵀX is invertible. A curve with many dips could trap the marble in the wrong one. That cannot happen here, which is why the answer is a formula and not a search.

Where it fails, and what to do

The symptom: weights that flip sign or double between two fits on similar data. The measurement: compute the condition number of XᵀX, or refit on random halves of the trials and compare. The fix: drop or merge near-duplicate inputs, collect data that separates them, or add a small penalty on the weights. That last fix is ridge regression, which Chapter 9 uses on real data.

Two recorded neurons almost always fire together. You use both as inputs in least squares. What do you expect?

Chapter 4

Eigenfaces: A Face as a Few Numbers

Use PCA to squeeze a photograph into a short list, then recognise a face by where that list lands

A door at a lab must open for the people who work there and stay shut for everyone else. A camera takes a photo of whoever stands in front of it. How can a program decide whether the photo shows a known person, a stranger, or no face at all? The slides call the first paper Eigenfaces for Recognition, by Turk and Pentland, 1991, with over 21,000 citations. It answers that question with the PCA you already know.

A photo is a point in a huge space

A grey photo is a grid of pixels, and each pixel is a brightness number. The lecture uses 256 by 256 images. Unroll the grid row by row into one long list, and the photo becomes a vector with 65,536 entries, about 65K. That makes every photo one point in a space with 65,536 axes.

Most points in that space are television static. Faces occupy a thin sliver, because all faces share a layout: two eyes above a nose above a mouth. If the sliver is thin, a few well-chosen directions should describe a face well. Finding those directions is a job for PCA.

The three steps on slide 15

The lecture states the whole method in three lines. Step one: do PCA on a bunch of face images. Step two: project a new face onto the top principal components, which gives a point in what the paper calls face space. Step three: classify by finding the nearest face class, meaning the mean of the face-space points of one known person.

Slides 16 to 18 carry out step one. The first slide shows the raw training faces. The second subtracts the mean face, the pixel-wise average of all faces, so that every face becomes a difference from the average. The third unrolls each image into a row of a matrix X and takes its SVD. That matrix has 115 rows, one for each training photo, and about 65K columns. The resulting directions, reshaped back into pictures, are the eigenfaces. The slide shows seven of them.

Why the SVD of X, not of XᵀX

The slide has a small blue note: use svd(X) instead of svd(XᵀX). It is worth understanding. The covariance matrix XᵀX would be 65,536 by 65,536. That is 4.3 billion numbers, about 17 gigabytes at four bytes each, to describe a sliver you can fit in 115 photos. The SVD of X itself works on a 115 by 65K block and gives the same directions. With 115 centred photos there are at most 114 useful directions anyway, so almost nothing is lost.

Project, reconstruct, classify

Slide 19 shows how a new face is processed. Subtract the mean face from the new photo to get x − μ. Collect the top k eigenfaces as the columns of a matrix B, so B has 65K rows and k columns. Multiply Bᵀ(x − μ) and you get k numbers, the face-space coordinates. To see what those k numbers still say, map back with BBᵀ(x − μ) + μ. That is the reconstruction. Slide 19 shows an original face beside its reconstruction, and they look alike.

x̂
The reconstructed photo, with all 65K pixels, built from only k numbers.
B BT
Project onto the top k eigenfaces and map back. BT makes the k coordinates. B turns them into a picture again.
x − μ
The new photo minus the mean face: how this face differs from the average.
μ
The mean face, added back at the end so the picture has normal brightness.

Slide 20 shows why this also detects faces. A face reconstructs well, because it lies close to face space. A photo of a flower does not, because the top eigenfaces cannot describe it. The reconstruction comes back as a ghostly face-like blob. So the distance between a photo and its reconstruction is a test: small means face, large means not a face.

The device below runs this on a toy. We made 8 by 8 grey “faces” from a few hidden patterns, found the eigenfaces by PCA in your browser, and let you choose how many to keep.

Rebuild a face from k numbers

Left to right: the photo, the mean face, the reconstruction from k components, and the left-over miss in yellow and blue. Pick a face or a non-face, then raise k.

3

Toy data, not the paper’s photos: 60 training faces of 64 pixels (8 by 8), each a made-up mean face plus three smooth patterns with random strengths plus a little noise. The eigenfaces come from a live PCA of those 60 faces. The paper used 256 by 256 photos and 115 training images.

Slide 21 sketches a bridge to neuroscience. It names a 2017 Cell paper by Chang and Tsao, The code for facial identity in the primate brain, as a use of PCA to characterise face space from neural data. The slide gives only the title, so we do not summarise its findings here. You can read it through the course site. The idea to carry over is that a “space” of faces, built by PCA, gives you coordinates you can compare to neural responses.

Where it fails

The symptom: a face under odd lighting, or turned away, gets called a non-face, or two different people land on the same point. The measurement: the reconstruction error and the distance to each face class both grow. PCA is linear and sees only pixel-wise differences, so a shifted shadow looks like a large change. The fix: train on photos that cover the conditions you expect, and set the face threshold on held-out photos, not on the training set. This is our own remark, not a claim from the slides.

Why does the lecture take the SVD of X rather than the SVD of XTX for 115 photos of 65K pixels each?

Chapter 5

Preparing Without Moving

Meet the puzzle of a brain area that is busy before a reach but leaves the arm still

A sprinter crouches on the blocks. Every muscle is ready, the mind has the race planned, and the body does not move. Then the gun fires and the legs explode. Somewhere in the brain, the plan is already written before the signal to go. Yet the legs are quiet. How can a brain area hold a plan without acting on it?

Slide 22 introduces the second paper: Cortical activity in the null space: permitting preparation without movement, by Kaufman, Churchland, Ryu and Shenoy, Nature Neuroscience, 2014. Slide 23 states the motivation as two questions. How can we plan a course of action while we wait for the right moment to act? And since preparatory activity, the firing in motor cortex before a movement, is there, why does it not cause movement?

Two obvious answers, and why the paper rejects them

The slide lists two guesses in brackets: sub-threshold, and gating. The slide marks them with a red arrow and the word “no”. Both are natural.

The first guess says preparation is a weaker copy of movement activity, too weak to push the muscles over their threshold. The paper’s own text says the data do not fit: preparatory activity is not just a weaker version of movement activity. The second guess says a gate, such as an inhibitory switch, holds the signal back until the go cue, as it does in the brainstem circuit that moves the eyes. The paper reports that its authors had already looked and found no clear signs of a simple inhibitory gate in these areas.

That leaves the slide’s last bullet, which sounds like a joke and is meant seriously: the new proposed mechanism is linear algebra. Chapter 6 shows what it means. First we need the experiment.

The experiment on slide 24

Slide 24 gives the methods in three bullets. Multi-electrode recordings listened to many neurons at once in two areas: dorsal premotor cortex, written PMd, and primary motor cortex, written M1. PMd helps plan arm movements and M1 sends commands toward the spinal cord and muscles. The behaviour was a delayed reach: the monkey is cued about an upcoming movement, and must wait through a delay before a go cue lets it reach.

The third bullet notes that preparatory activity predicts aspects of the movement, such as reaction time and variability. So it carries real information about the coming reach. The figure on the slide shows the timeline: Target, Go, then Move, with the target position, the cursor, a muscle signal called EMG, and the firing rate of one typical PMd neuron stacked above each other. EMG, short for electromyography, is the electrical activity of a muscle, so it is a direct read-out of how hard the muscle is working.

The paper adds how far preparatory activity travels. It is prevalent in PMd, somewhat less so in M1, present but modest in the spinal cord, and essentially absent in the muscles. Information is thinning out along the pathway. The question is how.

Test the two guesses against the timeline

The device below draws a delayed-reach trial. Scrub through time, then pick one of the two guesses. A dashed line shows what that guess predicts for the muscle. Compare the dashed line with the solid trace.

Scrub a delayed reach

Three traces: a premotor neuron (blue), a motor-cortex neuron (blue, lighter) and the muscle EMG (pink). The vertical lines mark Target, Go and Move. Drag the time marker, then choose an idea to see its dashed prediction.

500 ms

Illustrative shapes drawn to match the pattern on slide 24, not real recordings: Target at 100 ms, Go at 700 ms, movement onset at 850 ms, a made-up PMd rate near 50 spikes per second during the delay, and an EMG that stays at zero until movement. The two predictions are the lesson’s own sketches of what each idea would imply.

If preparation were a weaker copy, the muscle should show a small, early bump, shaped like the movement but smaller. It does not. If a gate held preparation back, the neurons that drive the muscle should stay quiet until the gate opens. They do not: they are active during the delay. Neither idea fits what the timeline shows, a busy cortex and a still muscle.

What would a better answer look like?

It must let the cortex be active and the muscle be silent, with no switch and no weakening. A cleaner way to do that is for the muscle to read out only part of the population’s activity. If preparatory activity lives in the part the muscles do not read, the muscles never feel it. That sentence is the whole paper. The next chapter builds it from a two-neuron example.

The symptom that sends scientists in this direction is a mismatch between the brain and the body. The measurement is a recording of both at once: neurons and EMG on the same trial. The fix, in the spirit of this lecture, is a model that connects the two, which is why regression comes back in Chapter 6.

Which observation makes the “weaker copy of movement activity” idea hard to believe?

Chapter 6

Output-Null Dimensions: Changes the Muscles Cannot See

Write the muscles as a weighted sum of neurons, and watch some changes of the population cancel exactly

Two friends pull a rope from opposite ends of a table. One pulls harder, the other pulls harder too, and the knot in the middle does not move. Both friends are working. The knot sees only the difference. Motor cortex and the muscles may be in the same situation: lots of effort on both sides, and a read-out that sees only a sum.

The model on slide 25

Slide 25 turns that idea into one line of regression: M = W N. Each symbol is a table. N holds neural activity, one row per neuron and one column per time step. M holds muscle activity, one row per muscle and one column per time step. W holds the neuron-to-muscle weights, one row per muscle and one column per neuron. Each muscle is a weighted sum of all the neurons.

N : [n neurons × T time steps]     the recorded population
W : [m muscles × n neurons]        the weights, found by regression
M : [m muscles × T time steps]     the muscle signals (EMG)
M = W N        for example n = 100 neurons, m = 3 muscles

You already know how to find W: it is a least-squares problem (Chapters 1 to 3). Chapter 7 shows the twist the paper adds. First, the idea on the slide: neural activity patterns orthogonal to the row space of W won’t affect the muscles.

Row space and null space in plain words

Take one row of W. It is a recipe: “this much of neuron 1, that much of neuron 2, and so on.” Multiply it by the population at one moment and you get that muscle’s signal. The row space of W is every combination of its rows. A change in the population that lies along the row space moves the muscles. This is the output-potent part of the population: output because it feeds the muscles, potent because it has power over them.

A change that is perpendicular to every row gives zero when multiplied by W. The set of all such changes is the null space of W. The paper calls it output-null: the part that is not read out. Activity can swing wildly there and the muscles will not notice. When there are more neurons than muscles, a null space must exist. The paper says this is likely inevitable, since cortex has many more neurons than there are muscles to command.

The lecture’s two-neuron toy

Slide 26 offers a toy, and calls it the whole paper in one picture. The muscle force equals the sum of two neurons, M = N₁ + N₂. So W is the single row [1 1]. Take a baseline of both neurons at 1 spike per second, so M = 2. Now let preparation push neuron 1 up to 2 and neuron 2 down to 0. The muscle reads 2 + 0 = 2. Nothing changed for the muscle, though both neurons changed by a full spike per second.

Slides 27 to 29 draw this in a state space: a plane with neuron 1’s rate across and neuron 2’s rate up, so one dot is the whole population. A diagonal line along (1, 1) is the potent direction, because the sum grows as you move along it. A diagonal line along (1, −1) is the null direction, because the sum cannot change there. Preparing means sliding along the null line. Moving means sliding along the potent line.

Walk a reach through the state space

The dot is the population: neuron 1 across, neuron 2 up. The pink line is the potent direction and the purple line is the null direction. Choose a reach, then slide through the trial from baseline to prepare to move.

45%

Illustrative toy after the lecture’s slides 26 to 29, with M = N1 + N2 and a baseline of 1 spike per second for each neuron. The path is the lesson’s own drawing: the first half moves along the null direction to (2, 0) or (0, 2), the second half along the potent direction to a muscle readout of 4.

Read the numbers as you slide. Over the first half, the null coordinate changes by about 1.4 spikes per second while the muscle stays at 2. Over the second half, the potent coordinate changes and the muscle climbs to 4. Same two neurons, two different jobs, depending on direction.

Why this is a real answer

It explains the puzzle of Chapter 5 with no weakening and no gate. Preparatory activity is large, but it sits in directions the muscles do not read. When the go cue arrives, the population moves into the potent directions, and only then does the muscle respond. There is also a prediction you can test, and that is why it is a scientific claim and not just a story: preparatory tuning, meaning how much preparatory activity depends on the planned reach, should sit mostly in null directions. Chapter 7 tests exactly that.

The failure mode to watch is mixing up an observation with a cause. A symptom such as “neurons change but the muscle does not” can arise from more than one mechanism. The measurement that separates them is the geometry: do the changes lie in the null space of W? The fix is to estimate W from data rather than guess it, which is the next chapter.

In the toy M = N1 + N2, preparation moves the neurons from (1, 1) to (2, 0). What happens to the muscle readout, and why?

Chapter 7

Finding the Directions: Principal Components Regression

Estimate which directions the muscles read from movement alone, then test whether preparation avoids them

A detective has a suspect and a theory. If the detective builds the theory from the very clues that will later convict the suspect, the case proves nothing. Science has the same trap. To show that preparation avoids the directions the muscles read, you must find those directions without looking at preparation. Slide 32 states this rule in its first line: estimate the output-potent and output-null dimensions from movement-period activity only.

Step one: regress muscles on neurons, in the movement epoch

During the movement, the muscles are clearly driven by the brain, so this is where W shows itself. Slide 32 writes the fit as Ŵ = argmin ‖M − WN‖². In words: choose the weights that make the squared miss between the real muscle signals and the predicted ones as small as possible. That is the least-squares problem of Chapters 1 to 3, with neurons as inputs and muscles as outputs.

The paper adds one practical detail from its methods. Cortex acts on muscle after a short lag, so the muscle signal M was advanced by 50 ms relative to the neural signal N. Each muscle sample is then paired with the neural activity that came about 50 ms before it.

Step two: why the PCA comes first

Real neurons in a population are strongly correlated, so the raw table N is exactly the badly-conditioned case of Chapter 3: weights would swing from fit to fit. The paper’s remedy is on the slide as principal components regression, or PCR, credited to Massy, 1965. It is two steps: first project the data onto its top k principal components, then do the regression. The paper’s own text states why this works. The principal components of the neural table have orthogonal, uncorrelated rows, so the regression is viable and W can be found.

The slide fixes the sizes: 6 principal components for N and 3 for M. The paper reports that the three components of the muscle data captured 77 to 92 percent of its variance. With 6 neural components and 3 muscle components, the weights form a 3 by 6 table (the slide draws the same table turned on its side, as 6 by 3). Three directions are read by the muscles, the potent space. The other three of the 6 neural directions are the null space.

N'  : [6 neural PCs × T]        top 6 PCs of the population, rows uncorrelated
M'  : [3 muscle PCs × T]        top 3 PCs of the EMG (77 to 92% of its variance)
W'  : [3 × 6]                   fitted by least squares, movement epoch only
potent space = row space of W'  (3 dimensions)
null space   = what W' maps to zero (the other 3 dimensions)

Step three: the tuning ratio

Now, and only now, look at preparation. Project the preparatory activity onto the potent directions and onto the null directions. Tuning means how much activity changes between different planned reaches. The paper’s measure is the tuning ratio: the strength of preparatory tuning in the output-null dimensions divided by the strength in the output-potent dimensions. If preparation ignored the geometry, the ratio would be about 1, which is chance. If the idea of Chapter 6 holds, it should be well above 1.

It was. In all four data sets, from two monkeys, the ratio was above 1. It ranged from 2.8 to 8.2 (slide 34 shows 3.0, 8.2, 2.8 and 5.6 for the four), and the geometric mean was 4.5. One example pair of dimensions, on the paper’s Figure 4, reached 9.2. The paper also ran simulations to check that its method detects the effect when it is there, and does not invent it when it is not.

A worked example you can do by hand

Take two neurons and one muscle. In the movement epoch we record four moments, with neuron rates measured from their average: neuron 1 reads (−2, −1, 1, 2), neuron 2 reads (−1, −2, 2, 1), and the muscle reads (−3, −3, 3, 3). The normal equations from Chapter 2 need three sums. The sum of squares of neuron 1 is 10, of neuron 2 is 10, and the cross-product is 8. The sums with the muscle are 18 and 18. Solve the pair of equations 10w₁ + 8w₂ = 18 and 8w₁ + 10w₂ = 18 and you get w = (1, 1). So the potent direction is (1, 1) and the null direction is (1, −1).

Now look at preparation for two planned reaches. Reach A prepares at (1.6, 0.6) and reach B at (0.4, 1.4). Along the potent direction these project to 2.2/√2 = 1.56 and 1.8/√2 = 1.27, a difference of 0.28. Along the null direction they project to 1.0/√2 = 0.71 and −1.0/√2 = −0.71, a difference of 1.41. The tuning ratio is 1.41 divided by 0.28, which is 5.0, inside the paper’s range.

The device below does this with noise. It draws movement data, fits the weights by least squares, then places the preparatory points and reports the ratio.

Estimate, then test

Blue dots are movement-epoch moments. The pink line is the potent direction fitted from them by least squares, the purple line is the null direction. The two large dots are preparation for two reaches. Tilt the preparation, then add muscle noise.

11°
0.3

Toy simulation, seeded: 60 movement moments of two neurons with a true muscle rule M = N1 + N2 plus noise. The ratio here is the lesson’s simplified version: the separation of the two reaches along the fitted null direction divided by their separation along the fitted potent direction. The paper’s ratio of 2.8 to 8.2 uses a fuller measure over many dimensions and times.

Push the noise up. The fitted line tilts away from (1, 1), and the ratio drifts. Muscle noise makes the estimated potent direction wrong, and a wrong direction spreads preparatory tuning across both axes. The paper reports that when its analysis erred, it nearly always underestimated the effect, so its numbers are most likely conservative.

When the method misleads

The symptom: a high ratio that vanishes on new data. The measurement: refit the potent directions on half the movement trials and compute the ratio on the other half, and compare. The fix: never fit and test on the same epoch, which is the detective’s trap. The slide also records a link back to the lecture’s earlier ideas: this finding “accords nicely” with the observation that preparatory tuning is often uncorrelated with tuning during the movement.

A tuning ratio of 1 for preparatory activity would mean what?

Chapter 8

What the Null-Space Result Does Not Show

Read the lecture’s own critique, and measure what happens when you keep too many components

A good teacher does not stop at “wow”. After showing a clever paper, Pillow turns to its limits. Slides 35 to 37 are a model of how to read a result: say what it explains, then say what it leaves open. We do the same here, because the limits teach as much as the finding.

The summary on slide 36

Slide 36 gives two points. First, null spaces offer a simple reason that preparatory neural activity fails to generate movement: the muscles add it up in a way that cancels out. Second, preparatory activity in PMd also lies in the null space of the weights that drive M1 from PMd. So the same trick may control the conversation between brain areas, not only the one between brain and muscle. The slide also names the new technique: principal components regression, first project onto the top k PCs, then regress.

Caveat one: trial averages only

Slide 35 carries a quote from the paper: trial-averaged data were used except where noted. The goal was to explain how preparatory tuning can exist without movement, not to explain trial-by-trial variability. Averaging is a choice with a price. If one trial is noisy with spread σ, the average of n repeats has spread σ divided by the square root of n. With 20 repeats of one reach, noise falls by a factor of 4.5, so smooth, clean curves emerge. The monkeys were highly practised, and the paper notes that repeated reaches to the same targets were extremely similar across months, which is what makes averaging meaningful.

But averaging also throws away every difference between one trial and the next. The paper’s claim is about the mean geometry, not about what a single trial does.

Caveats two and three: validation and single trials

Slide 37 lists three comments. First, there is no model validation: the lecture asks how well this linear model accounts for the data. Second, there are no single-trial analyses. As an example question: does trial-to-trial spiking variability in a potent neuron correlate better with movement variability than variability in a null neuron? That would be a direct test of Chapter 6, and the paper does not run it. Third, the lecture wonders what would have happened without restricting the fit to 6 PCs for neural data and 3 PCs for muscles.

The third question is one you can answer yourself with a toy. More components mean more weights, and more weights always fit the training moments better. Whether they fit new moments better is a separate question. The device below fits a muscle from 12 neurons, using the first k principal components, and scores the fit twice: on the moments used to fit it, and on fresh moments held back.

Keep too many components

The blue curve is the fit on the data used to learn the weights. The yellow curve is the fit on new data. Slide the number of components k, then cut the amount of training data.

8
40

Toy simulation, seeded: 12 neurons built from 3 hidden signals plus noise, and a muscle that reads two of the hidden signals plus noise. The fit is R², the share of muscle variance explained. The paper’s 6 and 3 are its own choices; this device does not test them.

With few training moments, the held-out curve peaks at a small k and then sinks, while the training curve keeps climbing. That gap is overfitting: the model has memorised the noise of the training moments. It is the same disease as Chapter 3, seen from the other side. A fix is to choose k on held-out data. The lecture’s question, in effect, is whether the paper’s 6 and 3 were chosen that way. The slide leaves it open, and so do we.

A short habit helps when you read any paper that fits a model. Ask what data the model was fitted on, what data it was scored on, and how many knobs it has compared with the number of data points. Here the knobs are few: 3 muscle components and 6 neural components give a table of 18 weights, fitted to many time points. That ratio is a reason to trust the fit more. The lecture still asks for the held-out score, because a small ratio is a hint and not a proof.

How to hold both the finding and the doubt

The paper does take steps to guard its claim. It ran extensive simulations to check that the analysis detects the effect when it exists and not otherwise. It tested simulated data with saturating nonlinearities of the kind real firing rates have, and found the results held. Errors in the assumed dimension count were also tested. The authors note that when results were off, they were nearly always underestimates. These are checks on the method. The lecture’s comments are about the model and the data: a separate list.

The symptom of a result that is too clean is a model that was never scored on new data. The measurement is held-out fit. The fix is a validation step before the story is told. You will meet it again as regularisation and model selection in later lectures.

As you raise the number of principal components in a regression, what usually happens to the fit on the training data and on held-out data?

Chapter 9

Behaviour as Regressors

Build a design matrix from task events and from video of the animal, and ask which one the brain tracks

You sit at a desk and answer a hard question. While you think, your foot taps, your eyes drift, and you shift in the chair. A scientist records your brain the whole time. Is the activity about the question, or about the foot? The third paper asks the mouse version of that. Slide 38 introduces Single-trial neural dynamics are dominated by richly varied movements, by Musall, Kaufman, Juavinett, Gluf and Churchland, Nature Neuroscience, 2019.

The motivation on slide 39

Slide 39 asks what your brain does while you perform a task. It lists two options. Does it encode the variables needed to perform the task? Or does it encode the random stuff you are doing that is unrelated to the task, such as tapping your foot or shifting in your chair? The paper points out that most studies of well-learned tasks assume the first. They assume uninstructed movements have a negligible effect, and that such movements occur at random, so averaging removes them. Both are assumptions, and the paper tests them.

The setup on slides 40 and 41

Mice gripped a handlebar to start a trial. They then observed clicks, or flashes of light, on the right or the left, and licked a left or right spout to get a water reward. The data come from 11 mice and 22 sessions. Some movements are instructed: the task requires them, such as licking the spout. Others are uninstructed: the animal makes them without being asked, such as whisking or moving its face and body. Slide 40 flags this split as the key idea.

Slide 41 shows the recording method. Mice expressed a fluorescent calcium indicator in their cortical neurons, and the team imaged the fluorescence across the whole dorsal cortex through the cleared skull. This is widefield calcium imaging. When a neuron fires, calcium floods in and the indicator glows brighter, so brightness is a slow, blurred proxy for spiking. Each pixel of the image is a time series, like one very coarse neuron.

The analysis on slide 42

Slide 42 gives the plan: fit a regression model using either task events or uninstructed movements, with features extracted from video using PCA. This is regression exactly as in Chapters 1 to 3. The output Y is the activity of one pixel or neuron over time. The design matrix X has one column for each behaviour. Slide 42 shows the formula in its figure as ridge regression.

β
The weights, one per column of X. The paper calls the time-shifted ones event kernels.
XTX
The same matrix as Chapter 3. Behaviours that move together make it nearly singular.
λI
A small number added along the diagonal. It keeps the matrix invertible and shrinks wild weights. This is the ridge.
XTY
As before: how each behaviour column lines up with the neural activity.

Two kinds of column fill the design matrix. A discrete event, such as a lick or the choice, becomes a column of 0s with a 1 at each event time, then copies shifted in time so the fit can learn a delayed response. An analog variable, such as pupil size or the video, is a continuous signal. Video has far too many pixels, so the paper first applied PCA to the video of the face and body and kept the top dimensions. On average more than 90 percent of the video variance was explained by 8 dimensions. Those 8 numbers per frame became the movement columns.

Why overlap needs a careful score

Behaviours overlap. A mouse licks after the choice, so licks and choices are correlated. Whisking often begins when a stimulus appears. If two columns carry the same information, a model can credit either one. The paper therefore scores two ways. Cross-validated explained variance, written cvR², is how much activity the model predicts on held-out data. The unique contribution, written ΔR², is how much that score drops when you shuffle one variable in time. The drop is a lower bound on what only that variable knows.

Build the design matrix yourself below. Switch groups of behaviours into the model and watch both numbers.

Switch groups into the model

The blue line is one simulated neural trace. The warm line is the model prediction from the groups you switch on. The strips below are the regressors. Turn groups on and off, then slide the ridge.

1

Toy simulation, seeded: 300 time steps, six regressors (stimulus and choice, lick and handle, whisk and pupil) built so that licks follow choices and some whisking follows stimuli. The trace mixes all six plus noise, with whisking weighted most by construction, so the result echoes the paper’s finding by design and is illustrative. Scores are from 2-fold cross-validation over blocks of 20 steps. Here the unique contribution is the drop when a group is removed; the paper shuffles the variable in time instead. The paper’s own numbers come in Chapter 10.

Try the groups one at a time. Each alone gives a score. Then switch all three on, and notice that the three single scores do not add up to the full score. The overlap is counted more than once when you add them. That is why the unique contribution matters.

When the regression misleads

The symptom: a variable that looks important alone and useless once others join. The measurement: compare its single-variable score with its unique contribution. A big gap means it mostly repeats something else. The fix: judge importance by the drop when the variable is removed, and fit the ridge on held-out data so that near-duplicate columns do not produce random weights.

Why does the paper report a unique contribution (ΔR²) as well as the cross-validated R² of each single variable?

Chapter 10

The Mouse Is Moving, and the Cortex Knows

Guess how much of cortical activity the animal’s own movements explain, then check against the paper

Before we show the numbers, make a bet. A mouse has learned a task well. It sees a flash, makes a choice and licks for water. Over the whole cortex, how much of the moment-to-moment activity do you expect its task variables to explain, compared with its random whisking, face and body movements? Most labs, before this paper, would have put the task first. Commit to a guess below, then reveal the paper’s numbers.

Guess, then reveal

Slide your guess for what uninstructed movements explain on their own (the teal marker). Press Reveal to see the paper’s bars for task, instructed movements and uninstructed movements. Switch between the cortex-wide images and the single neurons, and between the two scores.

15%

These are Musall et al. 2019 as printed in the text: widefield, 22 sessions from 11 mice; two-photon, over 13,000 neurons in 10 mice. Bars show means; the paper reports standard errors, listed in the read-out and in the Field Guide. cvR² is cross-validated explained variance, ΔR² is the drop when a group is shuffled.

What slide 43 says

Slide 43 shows the result from a “ton of regressions”: uninstructed movements account for a lot more of the variance than task variables or instructed movements. The figure splits the model into single variables, such as left audio, right vision, choice and time, then instructed ones such as licks and the handle, and then uninstructed ones such as whisking, nose, body and video. Two measures appear, the single-variable model score and the unique contribution. The green boxes for the uninstructed group sit highest.

The numbers behind it

In the widefield data, the task group predicted 17.6 percent of the variance (± 0.6) and the instructed movements 17.3 percent (± 0.6). Uninstructed movements predicted 38.3 percent (± 0.9), more than twice as much. The unique contributions told the same story more sharply: 2.9 percent for the task (± 0.2), 3.6 for instructed movements (± 0.2) and 17.8 for uninstructed movements (± 0.6), roughly five to six times larger.

One might object that widefield imaging blurs many neurons together. The team therefore imaged over 13,000 single neurons with two-photon microscopy in ten mice. Here the predicted shares were 12.3 percent for the task (± 1.0), 10.7 for instructed movements (± 0.9) and 32.6 for uninstructed movements (± 1.8). The unique contributions were 1.8 (± 0.1), 1.2 (± 0.3) and 21.2 (± 1.2). The uninstructed share is now about twelve to eighteen times the others. The full model reached a cross-validated score of 43.7 percent in anterior lateral motor cortex and 31.1 percent in the primary visual cortex, V1.

What slide 44 adds

Slide 44 lists two further results. First, task and instructed variables become more relevant during training: their share grows as the mouse learns the task. Second, the results differ somewhat across brain regions, but uninstructed movements explain most of the variance even in V1, the primary visual cortex. A visual area is the last place you would expect a whisker to matter.

The paper adds one more check that the slide only hints at. Uninstructed movements stayed the strongest predictor across up to 50 days of training. The animals do not stop moving as they become experts. Their movements change, and an expert mouse still performs richly varied, unrequested movements.

Keep the size of these numbers in perspective. A cvR² of 38.3 percent means the model still leaves about 62 percent of the moment-to-moment variance unexplained, so the absolute scores are modest. The comparison is what matters. The same model, the same data and the same cross-validation give the three groups very different scores, so the ranking does not depend on the absolute level. Reading the figure on slide 43 the same way, look at the height of each green box relative to its neighbours, and ask first which group sits highest before asking by how much.

Connect it back to Chapter 8

Chapter 8 warned that trial averages hide trial-to-trial variation. This paper shows what was hiding. The paper’s abstract says that neurons with similar trial-averaged activity often reflected utterly different combinations of cognitive and movement variables. Two neurons can have the same average curve, and for one of them it is a decision, while for the other it is a whisker. Only the single-trial regression tells them apart.

The failure mode follows. The symptom: an analysis says a brain area “encodes the choice”. The measurement: the choice column overlaps with licking, whisking and posture, and its unique contribution (ΔR²) is small. The fix: record the behaviour on video, put it into the design matrix, and report the unique contribution, not only the single-variable score. That fix applies to any lab that records neurons from an awake animal, and to the decoders in our linear decoder lesson.

In the widefield data, task variables had a unique contribution of 2.9 percent and uninstructed movements 17.8 percent. What is the fair reading?

Chapter 11

Field Guide: The Whole Lecture on One Page

Keep the numbers, the checklist and the core code, and see where each idea leads next

Two tools carried the whole lecture. Least squares fits weights that turn inputs into outputs. Its answer, (XᵀX)⁻¹XᵀY, follows from a right angle or from a flat spot at the bottom of a bowl. PCA finds the directions along which a table varies most. Eigenfaces used PCA to turn a photo into a few numbers. The null-space paper used both to show that motor cortex hides its plan in directions the muscles cannot read. The mouse paper used regression with video PCA to show that cortical activity is full of the animal’s own movement.

The numbers to remember

QuantityValueWhere it comes from
Best weights(XᵀX)⁻¹XᵀYSlides 4, 8, 12
Worked fit, four trialsslope 2.2, offset −0.5, squared error 1.8Chapter 1, our example
Eigenface images256 × 256 pixels = 65K dimensions; X is 115 × 65KSlide 18
Covariance if you used XᵀX65,536² = 4.3 billion numbersOur arithmetic
Components used for PCR6 neural, 3 muscle; 3 potent and 3 null dimensionsSlide 32, Kaufman et al. 2014
Muscle variance in 3 PCs77 to 92 percentKaufman et al. 2014 methods
Muscle lead over neuronsM advanced by 50 msKaufman et al. 2014 methods
Tuning ratio, four data sets2.8 to 8.2, geometric mean 4.5 (chance is 1)Slide 34, Kaufman et al. 2014
Mice and sessions, widefield11 mice, 22 sessionsMusall et al. 2019
Widefield cvR² (task, instructed, uninstructed)17.6, 17.3, 38.3 percentMusall et al. 2019
Widefield ΔR²2.9, 3.6, 17.8 percentMusall et al. 2019
Single-neuron cvR²12.3, 10.7, 32.6 percent (over 13,000 neurons, 10 mice)Musall et al. 2019
Single-neuron ΔR²1.8, 1.2, 21.2 percentMusall et al. 2019
Video dimensions kept8 dimensions, over 90 percent of video varianceMusall et al. 2019

Terms in one line each

TermPlain meaning
Design matrix XOne row per trial, one column per input.
ResidualWhat is left of an output after the model’s prediction.
Column spaceEvery output the weights can build from the columns of X.
Well-conditionedInputs that are not near-duplicates, so XᵀX inverts safely.
EigenfaceA principal component of face photos, shown as an image.
Output-potent, output-nullThe population directions the muscles read, and the ones they do not.
Tuning ratioPreparatory tuning in null directions divided by that in potent directions.
Uninstructed movementA movement the task did not ask for, such as whisking.
cvR², ΔR²Predicted variance on held-out data, and the drop when a variable is shuffled.

A checklist before you trust a fit

  1. Plot the residuals. One huge square means one trial steers the fit.
  2. Check the conditioning. Near-duplicate inputs make single weights unstable.
  3. Fit and test on different data. Choose the directions on one epoch and test on another.
  4. Choose the component count on held-out data. More components always fit the training set better.
  5. Report the unique contribution, not only the single-variable score.
  6. Record behaviour. A video of the animal is a regressor you cannot add later.

The core as code

pythonimport numpy as np

def least_squares(X, Y, lam=0.0):
    """X [N, d] inputs, Y [N, m] outputs. Ridge when lam > 0."""
    d = X.shape[1]
    return np.linalg.solve(X.T @ X + lam * np.eye(d), X.T @ Y)   # solve, never an explicit inverse

def pca(X, k):
    """X [samples, features]. Returns the mean and B [features, k]."""
    mu = X.mean(0)
    _, _, Vt = np.linalg.svd(X - mu, full_matrices=False)   # svd(X), not svd(X.T @ X)
    return mu, Vt[:k].T

def reconstruct(x, mu, B):
    return B @ (B.T @ (x - mu)) + mu                    # B B^T (x - mu) + mu

def potent_null(N, M, kn=6, km=3, lag=5):
    """N [neurons, T], M [muscles, T], movement epoch only. lag in samples."""
    Xn, Xm = N[:, :N.shape[1] - lag].T, M[:, lag:].T      # advance M relative to N
    mn, Bn = pca(Xn, kn);  Zn = (Xn - mn) @ Bn             # [T, 6] uncorrelated columns
    mm, Bm = pca(Xm, km);  Zm = (Xm - mm) @ Bm             # [T, 3]
    W = least_squares(Zn, Zm)                              # [6, 3], fitted in the movement epoch
    _, _, Vt = np.linalg.svd(W.T)                          # rows of Vt: orthonormal basis of the 6-d PC space
    return mn, Bn, Vt[:km], Vt[km:]                        # potent [3, 6], null [3, 6]

def tuning_ratio(Zprep, potent, null):
    """Zprep [conditions, T, 6]: trial-averaged preparatory activity in PC space."""
    spread = lambda Q: (Zprep @ Q.T).var(axis=0).sum()   # variation across conditions
    return spread(null) / spread(potent)                 # simplified; chance is about 1

def cv_r2(X, Y, lam, block=20):
    """2-fold cross-validated R^2 over alternating blocks of time."""
    fold = (np.arange(len(Y)) // block) % 2
    sse = sst = 0.0
    for f in (0, 1):
        tr, te = fold != f, fold == f
        w = least_squares(X[tr], Y[tr], lam)
        sse += ((Y[te] - X[te] @ w) ** 2).sum()
        sst += ((Y[te] - Y[te].mean()) ** 2).sum()
    return 1 - sse / sst

def unique_contribution(X, Y, cols, lam, rng=np.random.default_rng(0)):
    Xs = X.copy()
    Xs[:, cols] = np.roll(Xs[:, cols], rng.integers(50, len(Y) - 50), axis=0)   # shuffle in time
    return cv_r2(X, Y, lam) - cv_r2(Xs, Y, lam)

Where it sits, and where to go next

Each tool here has a fuller home on the site. Lecture 3 and our PCA lesson build the directions of greatest spread. Lecture 4 builds regression in more depth. Regularisation explains the ridge from Chapters 3 and 9. When the output is a spike count and not a smooth number, generalised linear models replace the straight line. In the BCI series, the idea of directions that matter and directions that do not returns in neural manifolds, linear decoders and latent variable models. Chapter 10’s warning about movement belongs next to spikes to rates.

The sources. Slides: Lecture 5, Neuroscience Applications on the NEU 560 course site. Papers: Turk and Pentland, Eigenfaces for Recognition, J. Cognitive Neuroscience, 1991. Chang and Tsao, The Code for Facial Identity in the Primate Brain, Cell, 2017. Kaufman, Churchland, Ryu and Shenoy, Cortical activity in the null space: permitting preparation without movement, Nature Neuroscience 17(3), 2014. Musall, Kaufman, Juavinett, Gluf and Churchland, Single-trial neural dynamics are dominated by richly varied movements, Nature Neuroscience 22, 2019, doi 10.1038/s41593-019-0502-4.

Credit: NEU 560 is taught at Princeton University by Jonathan Pillow. This lesson follows his slides in its own words and devices, uses none of the course’s images, and adds our own toy examples, each labelled as illustrative.

The takeaway. A population can change a lot and leave the read-out untouched, if the change lies in the read-out’s null space. And a brain signal that predicts the task may be predicting the animal’s own movement. Both lessons come from the same two tools: ask what predicts what, and ask where the table varies.

Now press Present or Teach and explain one idea out loud from memory: why the residual is perpendicular to the columns, how eigenfaces compress a photo, why preparation can sit in the null space, or why unique contribution beats a single score. Then go back to the two neurons at the top, press Prepare and Move, and say which direction the muscle reads.

NEU 560 Lecture 5: Neuroscience Applications of PCA and Least Squares
The course site · Lecture slides · Musall et al. 2019 · Back to microLearning