The Efficient, Predictive Brain
Is there one principle from which the mind's mechanisms follow?
In 1961 Horace Barlow proposed that sensory neurons exist to remove redundancy; in 1996 a network asked to describe natural images with as few active units as possible grew the oriented receptive fields of visual cortex. The part runs that optimization on screen, derives a fly's contrast code and the retina's centre-surround from efficiency, predicts the tilt after-effect and repulsive biases from an efficient code, derives Shepard's law from rate-distortion theory, meets normalization's one equation, builds predictive coding and the free energy step by step, weighs the Bayesian brain, resource rationality and learning rules, and scores each principle by what it risked.
What you need. Part 11's psychophysics, Part 13's receptive fields, Part 14's inference and Part 22's generalization; logarithms, probability and a little linear algebra.
- Hook
- Barlow's redundancy, 1961
- Ideas, models and mathematics
- efficient coding, sparse coding and the emergence of receptive fields, normalization, predictive coding, the free-energy principle derived and criticized, resource rationality, unified architectures
- Psyche gains
- sparse coding on natural images
- On you
- adaptation after-effects, predicted
What you will be able to do
Psych 101 and the major
- Explain the efficient coding hypothesis and give two of its successful predictions.
- Explain why an adapted population code produces the tilt after-effect.
Graduate
- Derive Laughlin's histogram-matching code and the whitening filter, and run sparse coding.
- Derive the variational free energy as a divergence plus surprise, and compute it for a Gaussian model.
Research
- State what a unified theory of the mind would have to risk, and design an experiment that separates predictive coding from adaptation.
Practice
- Explain how perceptual codecs and sensors spend bits where perception needs them.
Contents
Each chapter has a home level. Choose a track to see what to read and watch: Psych 101 and the major 13 min · Graduate 14 min · Research 28 min · Practice 14 min.
- 0A network that grew receptive fieldsPsych 101 and the major2 min
- 1On you: an after-effect, and four numbersPsych 101 and the major2 min
- 2Efficient codingPsych 101 and the major2 min
- 3Sparse codingResearch2 min
- 4Efficiency explains biasesPsych 101 and the major2 min
- 5Rate-distortionResearch1 min
- 6NormalizationResearch1 min
- 7Predictive codingPsych 101 and the major2 min
- 8The free-energy principleResearch2 min
- 9The Bayesian brain and its criticsResearch2 min
- 10Resource rationalityResearch1 min
- 11Learning rulesResearch1 min
- 12Unified theoriesResearch1 min
- 13The LedgerPsych 101 and the major1 min
- 14In practice: codecs and representationsPractice1 min
- 15Frontier: one principle?Research1 min
- Recap, problems, and the road aheadAll tracks3 min
Also on this page: Lecture · Key results · Try it · Lab · Problems · Notes and sources · Build the film.
Lecture
The text of each chapter is the film's narration, as it is spoken, so you can read along or revise without the film. The pictures are in the film.
A network that grew receptive fieldsPsych 101 and the major2 min
In 1959 Hubel and Wiesel found cells in the cat's visual cortex that respond to edges at one orientation, in one place. Part 13 told that story. Here's another way to arrive at the same cells. Psyche's world is a dead-leaves image: discs of random size and shade, piled on top of each other, a standard stand-in for the statistics of natural scenes. Sixty-four units must describe small patches of it, with as few units active as possible. Nobody tells them what to become. They start as random patches. After ten steps, nothing much. After fifty, structure. After four hundred, they've become small, oriented edge detectors: Part 13's simple cells, grown from a principle.
So this part asks: is there one principle from which the mind's mechanisms follow? In 1961 Horace Barlow proposed that sensory neurons exist to remove redundancy from their input. In 1996 Bruno Olshausen and David Field ran the optimization you just watched, on photographs of nature, and got the same result. An optimization principle produced biology. We'll follow its descendants: efficient coding, predictive coding, and the free-energy principle, a theory that claims to explain everything a brain does. And we'll ask the question every grand theory must answer: what would it have to risk?
This is Part 58 of Psychology, Built: the efficient, predictive brain. We'll derive centre-surround cells and edge detectors from efficiency. We'll predict after-effects and biases from an efficient code. We'll derive generalization from rate-distortion theory, and meet normalization's one equation. We'll build predictive coding and the free energy, step by step. We'll weigh the Bayesian brain, resource rationality and learning rules. And we'll ask what a unified theory would have to risk.
What it does: Sparse coding on screen; the question; objectives
1On you: an after-effect, and four numbersPsych 101 and the major2 min
Can a code that adapts fool you?
First, an experiment on you. Look at the small yellow bar between the two circles, and let your eyes drift slowly from one end of it to the other. Keep looking. The top lines lean one way, the bottom lines the other. Stay on the bar for the next half minute. Your orientation-tuned neurons are adapting, turning down their gain for the orientations they've been shown. Keep your eyes on the bar. It's the same mechanism that makes a waterfall's rocks seem to rise when you look away. Now. Are these lines vertical?
They are vertical. Most people see the top lines tilted to the left and the bottom lines to the right, away from what they adapted to. It's the tilt after-effect. The adapted units respond less, and a readout that assumes they didn't is pushed away from the adapter. Chapter four predicts its size from an efficient code.
Now four numbers. One: after staring at lines tilted twenty degrees clockwise, a vertical line looks tilted which way, and by about how much? Two: vertical and horizontal are the commonest orientations in the world. Is a line near vertical seen pulled toward vertical, or pushed away? Three: a neuron has twenty response levels for contrast. Which contrasts should get the most levels? And four: you decide by drawing samples from your beliefs, and each sample costs time. What's the best number of samples? Pause here, and write them down.
What it does: The tilt after-effect, experienced; four predictions
2Efficient codingPsych 101 and the major2 min
Why would a neuron care about statistics? In 1954 Fred Attneave pointed out that natural images are redundant: most of a picture can be guessed from neighbouring points and edges. In 1961 Horace Barlow argued that the senses have limited capacity, so a good code spends it on what can't be predicted. That's the efficient coding hypothesis: neurons are tuned to the statistics of the world, to carry as much information as their limits allow. It's a normative theory. It says what a code should be, then checks whether neurons are like that.
Here's the first clean test. In 1981 Simon Laughlin studied cells in a fly's eye that have a limited range of responses. To use every level equally often, the response should be the cumulative distribution of the contrasts the fly meets: steep where contrasts are common, flat where they're rare. He measured the contrasts in the fly's habitat, and the cells' response curve matched the prediction. In Psyche's world, twenty levels carry about four point two bits per response when they're matched, and three point seven when they're spaced evenly. Your third number: the commonest contrasts, near zero, get the most levels.
Now take the same idea to space. Natural images have most of their power at low spatial frequencies, falling roughly as one over frequency squared. Here's the variance of each component of Psyche's patches, on log scales. Removing that redundancy, called whitening, flattens the spectrum, so every component carries equal variance. And here's the filter that does it, for one pixel: a bright centre and a dark ring. It's Part 13's retinal ganglion cell. Joseph Atick and Norman Redlich added that the retina should roll off at high frequencies, where noise dominates, and that's what it does.
What it does: Redundancy; a fly's contrast code; centre-surround derived
3Sparse codingResearch2 min
Why edges? Here's the objective, written out. Describe each patch x as a sum of basis functions: D times a code a. Minimize the squared error plus lambda times the sum of the absolute values of the code. Fit well, with few active units. For each patch, find the code with a few steps of shrinkage, an algorithm called ISTA. Then nudge the basis functions to fit better, and repeat. Lambda sets the price of activity. Too low, and the units stay spread out. Too high, and the fit is poor. Olshausen and Field ran this on whitened photographs in 1996, and got localized, oriented, band-pass units, like V1's simple cells.
Is it the sparseness that matters? Compare two codes for the same patches. The sparse units are small and oriented. The principal components, which only decorrelate, are global ripples, like a Fourier basis. Measure how much of each unit's energy sits in its strongest three by three spot. The sparse code: about zero point eight. The components and random patterns: about zero point two five. Decorrelation alone gives ripples. Sparseness asks for independent causes, and edges are what images are made of.
How far does it go? It's replicated. Independent component analysis gives the same filters, as Anthony Bell and Terrence Sejnowski showed in 1997, and so do many later methods, including the first layers of deep networks. The same objective applied to sounds gives filters like the cochlea's, as Michael Lewicki showed in 2002. But it isn't exact. Measured V1 fields are rounder and more varied than the model's, as Dario Ringach found. And a note on Psyche: its images are synthetic dead leaves, not a licensed set of photographs. The result is the same in kind, and the fields come out smaller.
What it does: The objective; sparse against principal components; how far it goes
4Efficiency explains biasesPsych 101 and the major2 min
Does an efficient code see the world straight?
Start with the after-effect you just saw. Psyche's population has seventy-two units tuned to orientation. Adaptation lowers the gain of the units tuned near the adapter. The readout still assumes the old gains, so every test is pushed away from the adapter. The shift is largest ten to twenty-five degrees away: about four degrees at twenty, your first number. People report a few degrees. Why adapt at all? Re-centring the code on recent input keeps it efficient when the world changes. The illusion is the price.
Now a bias that seemed to break the Bayesian story. Vertical and horizontal are the commonest orientations, so a plain Bayesian observer should be pulled toward them. But people judge lines near vertical as pushed away from vertical. In 2015 Xue-Xin Wei and Alan Stocker showed why. If the encoder spends its precision where the prior is high, the likelihood becomes lopsided, and the posterior lands on the far side. The result is repulsion. Psyche's efficient observer is biased about two and a half degrees away from vertical and horizontal. That's your second number. Their 2017 rule, that the bias is proportional to the slope of the squared discrimination threshold, held across many published data sets.
What else does efficiency explain? Weber's law: a code whose resources follow a heavy-tailed distribution of intensities gives thresholds proportional to intensity, as Deep Ganguli and Eero Simoncelli showed. That's Part 11. Capacity limits: working memory as a channel with limited information, Part 19, where precision falls as items are added. Value: neurons that code value normalize by the options on offer, which can produce context effects in choice, Part 26. And the warning: almost any bias can be fitted by some prior and some resource limit. The real test is a prior that's measured independently, as Laughlin measured his fly's world.
What it does: The tilt after-effect predicted; repulsive biases; Weber, capacity and value
5Rate-distortionResearch1 min
What is the cheapest representation that is good enough?
What's the cheapest representation that's good enough? Rate is how many bits a representation carries about the stimulus. Distortion is the expected cost of the errors it allows. Shannon's rate-distortion theory gives, for each tolerated distortion, the least rate that achieves it. Equivalently, minimize the rate plus beta times the distortion, where beta is how much errors cost. Richard Blahut and Suguru Arimoto's algorithm finds the best channel by alternating two simple updates. For a brain, perception and memory are channels that must be cheap, and their errors should be cheap ones.
Here's a law it derives. In Part 22, Roger Shepard's universal law of generalization: across species and stimuli, generalization falls off roughly exponentially with psychological distance. Here's Psyche's best channel at three costs of error. A cheap code, with a low rate, confuses nearby stimuli broadly. A costly one generalizes narrowly, and every gradient is a smooth fall. In 2018 Chris Sims showed that the law falls out of an efficient channel, without any assumption about the geometry of mental space.
What it does: Shannon's other theorem; Shepard's law derived
6NormalizationResearch1 min
Is there a canonical computation? Here's a candidate: one equation. A neuron's drive, divided by the summed activity of a pool of neighbours plus a constant. Its response saturates at high contrast, and a mask that drives the pool but not the cell suppresses it. On a log axis, the curve shifts sideways: a change of gain, not of shape. David Heeger proposed it for visual cortex in 1992, and in 2012 Matteo Carandini and Heeger argued it's a canonical neural computation.
The same equation appears everywhere. In the retina, light adaptation divides responses by the mean light level. In visual cortex, it gives contrast saturation and cross-orientation suppression. In attention: John Reynolds and David Heeger's 2009 model has attention multiply the drive before normalization, and it reproduces many of Part 18's findings. In value: the value of an option divided by the others on offer, from Part 26. And why it's efficient: dividing out shared activity removes redundancy between neighbours. That's Barlow's principle again, as Odelia Schwartz and Eero Simoncelli showed in 2001.
What it does: One equation; the same equation everywhere
7Predictive codingPsych 101 and the major2 min
Does the cortex send its predictions down? In 1999 Rajesh Rao and Dana Ballard built a hierarchy where each level predicts the activity of the level below. What goes up is only the error: the part of the input the prediction didn't explain. Each level adjusts its causes to shrink the errors above and below it. That's inference by gradient descent. It explained end-stopping: cells that stop firing when a line extends past their field, because long lines are predicted from above. It's the same idea as efficient coding: don't send what the receiver can already predict.
Here's the loop, small enough to watch. Psyche's two-level network has sixteen inputs, four causes, and a prior on the causes. Give it an expected input, and the error units barely respond. Give it a surprising one, and there's a burst of error that the causes absorb as they settle. What remains is a disagreement with the prior. The network has learned something. So the prediction for physiology is that responses to the expected are suppressed, and responses to the unexpected are enhanced.
What does the evidence support? Expected stimuli evoke smaller responses: repetition suppression, the mismatch negativity from Part 15, and responses to omitted stimuli. Mouse primary visual cortex responds to mismatches between running and visual flow, as Georg Keller and colleagues found in 2012. Contested: separate error neurons and prediction neurons, in separate layers, as the scheme requires. The evidence is patchy. And the catch: suppression of the expected is also predicted by adaptation and by attention, so on its own it can't single out predictive coding.
What it does: Predictions down, errors up; error units; what the evidence supports
8The free-energy principleResearch2 min
Can one quantity explain everything a brain does? First, the mathematics, step by step. Bayes' rule gives the posterior over causes z given data x, but it needs the probability of the data, which is usually impossible to compute. So pick a simple family of distributions q, and define the free energy F: the expected log of q minus the log of the joint. Rearranged, it's the divergence between q and the true posterior, plus the surprise, minus log p of x. The divergence is never negative, so minimizing F over q does inference, and its minimum is a bound on surprise. It's the variational inference of AI, Built.
Here's the free energy of a small model. A cause z has a standard normal prior, and a reading of two arrives with noise of standard deviation zero point five. Plot F against the mean of q, and it's a bowl. Its bottom is the exact posterior mean, one point six, and its height is the surprise, about two point six nats. So far this is a theorem. It's true of any model, and it can be tested only through the model that's chosen.
Now the principle. Karl Friston argues that any system that persists must keep its sensory states unsurprising, so it must minimize free energy. In perception, it changes its beliefs to fit the input, and predictive coding is one implementation. In action, it changes the input to fit its beliefs. That's active inference, with desires recast as predictions of preferred states. The charge: with free choice of model and priors, any behaviour can be described as minimizing free energy, and a principle that can't fail isn't tested by its successes. The reply: the principle is a framework, like Hamilton's principle in physics, and the specific models built with it do make testable predictions.
What it does: Variational inference step by step; a small model's free energy; the claims
9The Bayesian brain and its criticsResearch2 min
Optimal against what? First, where the Bayesian account earned its place. Cue combination: vision and touch are weighted by their reliabilities, as the optimum requires. That was Marc Ernst and Martin Banks in 2002, and Part 14. Motor control: people learn the distribution of perturbations and their own noise, and plan accordingly, as Konrad Kording and Daniel Wolpert showed. Illusions as optimal guesses: a prior for slow motion explains why things look slower at low contrast. The strength is quantitative predictions from measured noise, with no free weights.
Now the critics. Jeffrey Bowers and Colin Davis called many Bayesian accounts just-so stories: with priors and likelihoods chosen after the fact, any behaviour can be called optimal. Matt Jones and Bradley Love warned against Bayesian fundamentalism, which fits data without asking how the computation is done. Dobromir Rahnev and Rachel Denison showed that people are reliably suboptimal in many tasks, and argued the useful question is how. The defence: used as a model with measured priors, the Bayesian account predicts. Used as a description of everything, it doesn't.
So how do you keep it honest? Measure the prior independently: from the environment's statistics, like Laughlin's fly, or from training. Measure the noise independently, from discrimination thresholds. Then predict a new task with no parameters left to fit. And compare against a named alternative, not against no model at all. That's Part 48's model comparison.
What it does: Successes; critics; how to keep it honest
10Resource rationalityResearch1 min
Are heuristics optimal after all? In 2014 Edward Vul, Noah Goodman, Thomas Griffiths and Joshua Tenenbaum modelled decisions made by drawing a few samples from the posterior and taking the majority. More samples give more accuracy: from zero point six five with one, to zero point nine eight with fifty. But if each sample costs time, reward per unit time peaks at a single sample. That's your fourth number. Probability matching, often called irrational, is just what one-sample deciders do.
Resource rationality makes this general. Falk Lieder and Thomas Griffiths define it as the best strategy given the cost of thinking, not the best answer given unlimited time. Heuristics such as anchoring and adjusting, or taking the best cue from Part 26, can be rational when thinking is costly. A test: people shift strategies when costs and stakes change, in the direction the analysis predicts. And the risk is the same as before: with costs chosen freely, any behaviour is resource-rational, so the costs must be measured too.
What it does: One and done; optimal use of limited computation
11Learning rulesResearch1 min
How does a brain learn what to predict? Deep networks learn by sending exact error gradients backward through every synapse, and neurons can't obviously do that. But random backward weights still teach a network, which Timothy Lillicrap and colleagues called feedback alignment. And predictive coding's error units, once settled, approximate backpropagation's gradients, as James Whittington and Rafal Bogacz showed. In a 2020 review, Lillicrap and colleagues argued the brain may approximate backpropagation with local signals and feedback. It hasn't been tested in detail.
There's a second kind of learning. Part 17's dopamine prediction error trains slow weights in prefrontal cortex. In 2018 Jane Wang and colleagues showed that a recurrent network trained this way learns, in its activity, a fast learning algorithm of its own. It reproduced Harry Harlow's learning sets: monkeys that get faster at each new problem of a kind. The same idea runs today's language models, which learn from examples in the prompt without changing a weight. That's Part 60.
What it does: Backpropagation and the brain; learning to learn
12Unified theoriesResearch1 min
What would a theory of everything a mind does have to risk? In 1973 Allen Newell complained that psychology studies effect after effect, each with its own little model, and will never add up. You can't play twenty questions with nature and win. His answer was unified theories of cognition: one architecture that does every task. John Anderson's ACT-R, and Soar, built by John Laird, Newell and Paul Rosenbloom, have decades of models of memory, skill and problem solving in one system. In 2017 the common model of cognition set out what those architectures agree on. Today's rivals are large brain simulations, and models trained on many experiments at once, which Part 60 takes up.
Here's each principle in this part, and what it risked. Efficient coding predicted after-effects, repulsive biases and Laughlin's curve before they were measured, and held. Normalization predicted gain changes, suppression, and attention effects, and held. Predictive coding predicted separate error neurons and suppression of the expected, with mixed results. The Bayesian brain risked cue weights from measured noise, and does well where priors are measured. The free-energy principle risks nothing on its own. Its models predict. The more a principle explains without measurement, the less it has risked.
What it does: Newell's twenty questions; what each principle risked
13The LedgerPsych 101 and the major1 min
What the four have in common. Principles that predicted measured quantities held: efficient codes and their biases. The bigger the claim, the weaker the test. Error neurons are contested, and the free-energy principle isn't tested. Each principle earns its keep through models with measured inputs. So here's the answer to this part's question. One principle doesn't yet explain the mind, but several explain a great deal of perception.
What it does: Four rows; what they have in common
14In practice: codecs and representationsPractice1 min
Where does efficient coding earn money? In perceptual codecs. JPEG quantizes fine detail coarsely, where the eye is least sensitive, and MP3 drops sounds that Part 15's masking hides. In neuromorphic sensors: event cameras report only the changes at each pixel, which is predictive coding in silicon. In representation learning: sparse dictionaries and autoencoders, now used to find interpretable features inside AI models. And in display and imaging, where tone mapping and gamma curves spend levels where people can see differences.
Here's a worked example. A sensor has twenty output levels for local contrast in Psyche's images. With evenly spaced levels, the middle few are used constantly and the rest rarely. With levels at the quantiles of the contrast distribution, each is used about equally often. One is empty, because many patches are perfectly flat. That gives four point two bits per reading, against three point seven. That's about fourteen percent more information from the same hardware, by Laughlin's rule.
What it does: Where this is a job; twenty levels, worked
15Frontier: one principle?Research1 min
What would settle it? First, what's new. Recordings across cortical layers and areas, shared openly, and designed to test predictive coding against adaptation. Rate-distortion accounts of working memory, and of what's forgotten. Deep networks trained on images predict visual cortex's responses, and which objective makes them brain-like is an open test. And Olshausen and Field's method has been revived to read the features inside language models.
And the open problems. A normative account of why working memory and attention have the limits they do. Which learning rule cortex actually uses. Whether any unified theory makes a risky prediction that the special theories don't. And what the brain is optimizing, if anything, beyond each sense's code.
What it does: What is new; open problems
Recap, problems, and the road aheadAll tracks3 min
First, your four numbers. After lines tilted twenty degrees clockwise, a vertical line looks tilted counterclockwise, by about four degrees in Psyche and a few in people. Lines near vertical are pushed away from it, by about two and a half degrees. The commonest contrasts, near zero, get the most levels. And when each sample costs time, the best number is one. Each answer follows from a code doing its best with limited resources.
Part fifty-eight in twelve lines. Sparse codes for images grow edge detectors. Efficient codes match the world's statistics, as Laughlin's fly showed. Whitening derives centre-surround cells. Adaptation re-centres the code, and after-effects are the price. Efficient encoding makes biases repulsive. Rate-distortion theory derives generalization gradients. Normalization is one equation in many places. Predictive coding sends errors up and predictions down, and is contested. The free energy is a theorem and a framework, untested as a principle. Bayesian models predict when priors are measured. Heuristics can be rational when thinking costs. And a principle is judged by what it risks.
Where this comes back. Priors and precision in psychiatry are Part 59. Machines that learn from examples in context are Part 60. And Part 62's dissertation can test a principle.
Seven problems, with full solutions in this part's README. One applies Laughlin's rule. One designs a whitening filter. One computes a normalized response. One does variational inference by hand. One counts a majority of samples. One asks what would count against the free-energy principle. And the last, with the star, asks you to separate predictive coding from adaptation. Pause here if you'd like to try them.
The books and papers behind this part are listed here and in the README. Hyvarinen, Hurri and Hoyer's book is the best introduction to natural image statistics; Dayan and Abbott's is the standard text on theoretical neuroscience; and Parr, Pezzulo and Friston's sets out active inference from its authors' side.
The first part of the frontier is done. It asked whether one principle explains the mind, and found several that explain a great deal of perception. The next part takes those models to the clinic: learning rates, priors and precision as places where illness might live. Part 59: computational psychiatry.
Where it goes next. Part 59 takes priors, precision and learning rates to the clinic; Part 60 compares learning in context in machines; Part 62's dissertation can test a principle.
Key results
The part's results in one place, for revision.
Try it
Lab 58 · The Efficient, Predictive Brain
Grow edge detectors by sparse coding, compare them with principal components, and predict the tilt after-effect from an adapting population code.
python -m videos.psychology.labs 58
needs numpy, scipy, matplotlib · download lab58.py ·
source on GitHubmedian localization: sparse; principal components 0.79; 0.27
share of zero coefficients at the end 0.75
tilt after-effect: peak shift (degrees) and where 4.3 at 22
largest efficient-coding bias (degrees) 2.56
Sparseness, not decorrelation, gives localized oriented units; adaptation that keeps a code efficient also pushes perception away from the adapter.
The code (59 lines; it asserts its own result)
"""Lab 58: the efficient, predictive brain: sparse coding, Laughlin's code and the tilt after-effect."""
import numpy as np
from videos.coursekit import labs
from explainer.psychology.psyche import efficient as E
TITLE = "The Efficient, Predictive Brain"
GOAL = ("Grow edge detectors by sparse coding, compare them with principal components, and predict the tilt "
"after-effect from an adapting population code.")
TASKS = [
"Lower lambda to 0.1. Are the basis functions still localized?",
"Learn on unwhitened patches. What do the basis functions look like now?",
"Make the adapted units lose 80% of their gain. Where does the after-effect peak, and how large is it?",
]
def run(seed=0):
out = labs.Lab()
imgs = [E.dead_leaves(size=96, seed=seed + s) for s in range(4)]
X = E.patches(imgs, n=8000, seed=seed)
Xw, _, _ = E.zca(X, eps=1.0)
Xw = Xw / Xw.std()
d = E.learn_dictionary(Xw, atoms=64, lam=0.4, epochs=150, seed=seed)
loc = E.localization(d["D"])
pcs = np.linalg.eigh(np.cov(X, rowvar=False))[1][:, ::-1]
ploc = E.localization(pcs)
assert np.median(loc["localization"]) > np.median(ploc["localization"]) + 0.2
out.row("median localization: sparse; principal components",
f"{np.median(loc['localization']):.2f}; {np.median(ploc['localization']):.2f}")
out.row("share of zero coefficients at the end", f"{d['sparsity'][-1]:.2f}")
t = E.tilt_aftereffect()
i = int(np.argmax(t["shift"]))
assert 5 <= t["tests"][i] <= 35
out.row("tilt after-effect: peak shift (degrees) and where", f"{t['shift'][i]:.1f} at {t['tests'][i]:.0f}")
b = E.efficient_bias()
out.row("largest efficient-coding bias (degrees)", f"{np.max(np.abs(b['bias'])):.2f}")
out.note = ("Sparseness, not decorrelation, gives localized oriented units; adaptation that keeps a code "
"efficient also pushes perception away from the adapter.")
fig, ax = labs.figure(2, size=(11, 4.0))
tiles = np.full((8 * 9 + 1, 8 * 9 + 1), np.nan)
for k in range(64):
f = d["D"][:, k].reshape(8, 8)
r, c = divmod(k, 8)
tiles[1 + r * 9:1 + r * 9 + 8, 1 + c * 9:1 + c * 9 + 8] = f / np.abs(f).max()
ax[0].imshow(tiles, cmap="gray", vmin=-1, vmax=1)
ax[0].set(title="sparse basis functions")
ax[0].axis("off")
ax[1].plot(t["tests"], t["shift"], "o-")
ax[1].axhline(0, color="grey", lw=0.8)
ax[1].set(title="tilt after-effect", xlabel="test minus adapter (deg)", ylabel="perceived shift (deg)")
out.fig = fig
return out
if __name__ == "__main__":
print(run())
Now change it
- Lower lambda to 0.1. Are the basis functions still localized?
- Learn on unwhitened patches. What do the basis functions look like now?
- Make the adapted units lose 80% of their gain. Where does the after-effect peak, and how large is it?
Problems, with solutions
Try each problem before opening its solution.
-
Laughlin's rule. Laughlin's rule: contrasts are uniform on \([-1, 1]\). The best response curve? And if they are normal?
Solution
The response is the cumulative distribution: for contrasts uniform on [-1, 1], the straight line (c + 1)/2; for normal contrasts, the normal CDF, a sigmoid steepest at the mean.
-
Whitening. Image power falls as \(1/f^2\). How must a whitening filter's gain grow with \(f\), and what does that do to noise?
Solution
Power falls as 1/f^2, so amplitude as 1/f; the filter's gain must grow as f to flatten it. That amplifies high-frequency noise without limit, so a real filter rolls off where noise dominates (the retina's band-pass shape).
-
Normalization. Normalization with \(n = 2\), \(\sigma = 0.15\): the response to \(c = 0.15\) alone, and with a mask of 0.15?
Solution
Alone: 0.0225/(0.0225 + 0.0225) = 0.5. With a mask of 0.15: 0.0225/0.0675 = 1/3.
-
Variational inference by hand. Prior N(0, 1), reading \(x = 2\) with noise SD 0.5. The posterior mean and variance, and the surprise?
Solution
Posterior precision 1 + 4 = 5, variance 0.2, mean (2 x 4)/5 = 1.6. Surprise: -log N(2; 0, 1.25) = 0.5 log(2 pi x 1.25) + 4/2.5 = 1.03 + 1.6 = 2.63 nats.
-
A majority of three. Each sample is right with probability 0.65. The accuracy of a majority of three?
Solution
p^3 + 3p^2(1 - p) = 0.275 + 0.444 = 0.718.
-
Against free energy. "The brain minimizes free energy." What observation would count against it?
Solution
As a principle, nothing: any behaviour has some generative model under which it minimizes free energy. A specific model (a stated generative model with measured priors and precisions) can be refuted by behaviour or physiology it does not predict; that is where the principle's content is tested.
-
★ Predictive coding against adaptation. Design an experiment that separates predictive coding from adaptation as the cause of a mismatch response.
Solution
Use a many-standards control: present the deviant tone in a sequence where it is as rare as in the oddball sequence but no standard sets a prediction. Adaptation predicts the same response in both (equal rarity); predictive coding predicts a larger response in the oddball sequence. Add omissions (a predicted tone left out): adaptation predicts no response, predictive coding an error response.
Notes and sources
Sources
- F. Attneave, Some informational aspects of visual perception, Psychological Review 61 (1954) 183-193; H. B. Barlow, Possible principles underlying the transformations of sensory messages, in W. A. Rosenblith (ed.), Sensory Communication (MIT Press, 1961) 217-234; S. Laughlin, A simple coding procedure enhances a neuron's information capacity, Zeitschrift fur Naturforschung C 36 (1981) 910-912; J. J. Atick and A. N. Redlich, What does the retina know about natural scenes?, Neural Computation 4 (1992) 196-210; E. P. Simoncelli and B. A. Olshausen, Natural image statistics and neural representation, Annual Review of Neuroscience 24 (2001) 1193-1216.
- B. A. Olshausen and D. J. Field (1996); A. J. Bell and T. J. Sejnowski (1997); J. H. van Hateren and A. van der Schaaf (1998); D. L. Ringach (2002); M. S. Lewicki, Efficient coding of natural sounds, Nature Neuroscience 5 (2002) 356-363; D. H. Hubel and T. N. Wiesel, Receptive fields of single neurones in the cat's striate cortex, Journal of Physiology 148 (1959) 574-591.
- X.-X. Wei and A. A. Stocker (2015, 2017); D. Ganguli and E. P. Simoncelli, Efficient sensory encoding and Bayesian inference with heterogeneous neural populations, Neural Computation 26 (2014) 2103-2134; C. W. G. Clifford et al., Visual adaptation: neural, psychological and computational aspects, Vision Research 47 (2007) 3125-3131.
- C. E. Shannon, Coding theorems for a discrete source with a fidelity criterion, IRE National Convention Record (1959) 142-163; R. Blahut, Computation of channel capacity and rate-distortion functions, IEEE Transactions on Information Theory 18 (1972) 460-473; R. N. Shepard, Toward a universal law of generalization for psychological science, Science 237 (1987) 1317-1323; C. R. Sims, Efficient coding explains the universal law of generalization in human perception, Science 360 (2018) 652-656.
- D. J. Heeger, Normalization of cell responses in cat striate cortex, Visual Neuroscience 9 (1992) 181-197; M. Carandini and D. J. Heeger, Normalization as a canonical neural computation, Nature Reviews Neuroscience 13 (2012) 51-62; J. H. Reynolds and D. J. Heeger, The normalization model of attention, Neuron 61 (2009) 168-185; O. Schwartz and E. P. Simoncelli, Natural signal statistics and sensory gain control, Nature Neuroscience 4 (2001) 819-825.
- R. P. N. Rao and D. H. Ballard (1999); G. B. Keller, T. Bonhoeffer and M. Hubener (2012); K. S. Walsh et al. (2020).
- K. Friston (2010); M. Andrews (2021); T. Parr, G. Pezzulo and K. J. Friston, Active Inference (MIT Press, 2022).
- M. O. Ernst and M. S. Banks, Humans integrate visual and haptic information in a statistically optimal fashion, Nature 415 (2002) 429-433; K. P. Kording and D. M. Wolpert, Bayesian integration in sensorimotor learning, Nature 427 (2004) 244-247; Y. Weiss, E. P. Simoncelli and E. H. Adelson, Motion illusions as optimal percepts, Nature Neuroscience 5 (2002) 598-604; J. S. Bowers and C. J. Davis, Bayesian just-so stories in psychology and neuroscience, Psychological Bulletin 138 (2012) 389-414; M. Jones and B. C. Love, Bayesian fundamentalism or enlightenment?, Behavioral and Brain Sciences 34 (2011) 169-188; D. Rahnev and R. N. Denison, Suboptimality in perceptual decision making, Behavioral and Brain Sciences 41 (2018) e223.
- E. Vul, N. Goodman, T. L. Griffiths and J. B. Tenenbaum, One and done? Optimal decisions from very few samples, Cognitive Science 38 (2014) 599-637; F. Lieder and T. L. Griffiths, Resource-rational analysis, Behavioral and Brain Sciences 43 (2020) e1.
- T. P. Lillicrap, D. Cownden, D. B. Tweed and C. J. Akerman, Random synaptic feedback weights support error backpropagation for deep learning, Nature Communications 7 (2016) 13276; J. C. R. Whittington and R. Bogacz, An approximation of the error backpropagation algorithm in a predictive coding network with local Hebbian synaptic plasticity, Neural Computation 29 (2017) 1229-1262; T. P. Lillicrap, A. Santoro, L. Marris, C. J. Akerman and G. Hinton, Backpropagation and the brain, Nature Reviews Neuroscience 21 (2020) 335-346; J. X. Wang et al., Prefrontal cortex as a meta-reinforcement learning system, Nature Neuroscience 21 (2018) 860-868.
- A. Newell, You can't play 20 questions with nature and win, in W. G. Chase (ed.), Visual Information Processing (Academic Press, 1973) 283-308; J. R. Anderson, How Can the Human Mind Occur in the Physical Universe? (Oxford University Press, 2007); J. E. Laird, C. Lebiere and P. S. Rosenbloom, A standard model of the mind, AI Magazine 38 (2017) 13-26.
About this partfrom its README
In 1961 Horace Barlow proposed that sensory neurons exist to remove redundancy from their input. In 1996 Bruno Olshausen and David Field asked a network to describe patches of natural photographs with as few active units as possible, and its units turned into the oriented, localized receptive fields Hubel and Wiesel had found in cortex. An optimization principle produced biology. The part opens with that optimization run on screen on Psyche's dead-leaves images, then follows its most ambitious descendants, up to a theory that claims to explain everything a brain does, and asks what each would have to risk.
The viewer adapts to tilted gratings and sees the tilt after-effect, then predicts four numbers. Then efficient coding (Attneave, Barlow, Laughlin's fly and its histogram-matching code, whitening and the centre-surround filter it implies); sparse coding written out and compared with principal components; efficient-coding biases (the tilt after-effect from adaptation in a population code, Wei and Stocker's repulsion, Weber's law, capacity, value); rate-distortion theory and Shepard's law of generalization; normalization as a canonical computation; predictive coding built small enough to watch, and what the physiology does and does not support; the free energy derived step by step, the principle, and the charge of unfalsifiability; the Bayesian brain and its critics; resource rationality and "one and done"; learning rules (feedback alignment, predictive coding as approximate backpropagation, meta-learning); and unified theories from Newell to the common model, with a scorecard of what each principle risked.
What is computed and built
explainer/psychology/psyche/efficient.py: dead-leaves images, patches, whitening, sparse coding by ISTA with dictionary learning and a localization measure, Laughlin's code, an efficient-coding observer, Blahut-Arimoto rate-distortion and generalization, normalization, a predictive-coding network, a Gaussian free energy, the tilt after-effect and resource-rational sampling. Tested intests/psychology/test_efficient.py.- The Ledger gains four rows.
- The course's interactive: adapt to a grating, then judge test lines, and see the after-effect predicted by a population of adapting units.
Chapter notes
| # | Chapter | What it does |
|---|---|---|
| 0 | A network that grew receptive fields | Sparse coding on screen; the question; objectives |
| 1 | On you: an after-effect, and four numbers | The tilt after-effect, experienced; four predictions |
| 2 | Efficient coding | Redundancy; a fly's contrast code; centre-surround derived |
| 3 | Sparse coding | The objective; sparse against principal components; how far it goes |
| 4 | Efficiency explains biases | The tilt after-effect predicted; repulsive biases; Weber, capacity and value |
| 5 | Rate-distortion | Shannon's other theorem; Shepard's law derived |
| 6 | Normalization | One equation; the same equation everywhere |
| 7 | Predictive coding | Predictions down, errors up; error units; what the evidence supports |
| 8 | The free-energy principle | Variational inference step by step; a small model's free energy; the claims |
| 9 | The Bayesian brain and its critics | Successes; critics; how to keep it honest |
| 10 | Resource rationality | One and done; optimal use of limited computation |
| 11 | Learning rules | Backpropagation and the brain; learning to learn |
| 12 | Unified theories | Newell's twenty questions; what each principle risked |
| 13 | The Ledger | Four rows; what they have in common |
| 14 | In practice: codecs and representations | Where this is a job; twenty levels, worked |
| 15 | Frontier: one principle? | What is new; open problems |
| Recap, problems, and the road ahead | Your numbers; twelve lines; payoffs; problems; references; Part 59 |
NotesWhere the numbers come from
| What | Source |
|---|---|
| Six 128 by 128 dead-leaves images (discs with radius density proportional to r^-3 between 1.5 and 40 pixels, uniform grey levels, occluding); 20,000 random 8 by 8 patches, mean removed | Psyche (efficient.dead_leaves, patches), items images and sparse |
| Patch spectrum and whitening (ZCA, regularized at 1% of the largest eigenvalue); the whitening filter for one pixel: centre about 6.3, nearest surround about -0.6 to -0.7 | Psyche (efficient.zca), item images |
| Sparse coding: 64 basis functions, whitened patches (regularized at 100%, a low-pass roll-off), lambda 0.4, ISTA with 80 steps per batch of 500, 400 dictionary steps; median localization 0.80 (energy in the strongest 3 by 3 spot) against 0.25 for principal components and 0.26 for random patterns; orientedness 0.36 against 0.22 and 0.13 | Psyche (efficient.learn_dictionary, localization), item sparse |
| Laughlin's code: local contrasts in Psyche's images, 20 levels: 4.21 bits per response at the quantiles, 3.68 evenly spaced (4.32 at most) | Psyche (efficient.laughlin), items laughlin and codes |
| Efficient-coding bias with a cardinal prior (density 2 - abs(sin 2 theta)), encoding noise 0.08 in the warped space: repulsive biases up to 2.6 degrees | Psyche (efficient.efficient_bias), item bias |
| Rate-distortion on 41 points with squared-error cost at beta = 0.02, 0.1, 0.5: rates 1.2, 2.2 and 3.3 bits | Psyche (efficient.blahut_arimoto), item rd |
| Normalization: n = 2, sigma = 0.15, masks 0, 0.2 and 0.5 | Psyche (efficient.normalization), item norm |
| Predictive coding: 16 inputs, 4 causes, prior precision 1; error activity 0.16 for an expected input and 5.7 for a surprising one at the start | Psyche (efficient.predictive_coding), item pc |
| Free energy: prior N(0, 1), x = 2, noise SD 0.5; posterior mean 1.6, surprise 2.63 nats | Psyche (efficient.free_energy_gaussian), item fe |
| Tilt after-effect: 72 units with tuning width 20 degrees, gain lost up to 50% near the adapter; shifts peak at 4.3 degrees about 25 degrees away (4 degrees at 20) | Psyche (efficient.tilt_aftereffect), item tilt |
| One and done: each sample right with probability 0.65, cost 0.02 per sample; reward rate best at one sample | Psyche (efficient.samples_value), item samples |
| Every published number on screen | the studies listed under Sources, quoted as reported |
Notes
| Finding | Original | Status |
|---|---|---|
| A code that describes natural image patches with as few active units as possible learns localized, oriented, band-pass basis functions like the receptive fields of simple cells in primary visual cortex. | Olshausen and Field 1996 | replicated |
| An encoder that spends its precision where stimuli are common, read out by a Bayesian decoder, predicts biases away from the common values, and a lawful link between bias and discrimination threshold. | Wei and Stocker 2015 | replicated |
| Cortex is organized as predictive coding requires: predictions sent down a hierarchy, and distinct neurons that signal the error between prediction and input sent up. | Rao and Ballard 1999 | contested |
| Everything a brain does, perceiving, learning and acting, minimizes variational free energy, a bound on the surprise of its sensory states. | Friston 2010 | not directly tested |
Shown without a row, with the reason recorded in explainer/psychology/ledger.py: Barlow; Laughlin; Sims;
Carandini and Heeger; Bowers and Davis; Vul and colleagues; Lieder and Griffiths; Lillicrap and colleagues; Newell.
Notes
The web-search budget for this session was spent on earlier parts, so the facts in this part come from the standard literature and were not re-checked online today; each is listed here to be checked against its source: Hubel and Wiesel's 1959 paper; Attneave (1954); Barlow (1961) and its pages; Laughlin (1981)'s cells and habitat measurements; Atick and Redlich (1992); Olshausen and Field (1996) and its patch sizes; Bell and Sejnowski (1997); van Hateren and van der Schaaf (1998); Ringach (2002); Lewicki (2002); Wei and Stocker (2015, 2017) and the 2017 rule's form; Ganguli and Simoncelli (2014); Shannon (1959); Blahut (1972) and Arimoto; Shepard (1987); Sims (2018)'s claim and data; Heeger (1992); Reynolds and Heeger (2009); Schwartz and Simoncelli (2001); Rao and Ballard (1999) and end-stopping; Keller, Bonhoeffer and Hubener (2012); Walsh et al. (2020); Friston (2010); Andrews (2021); Ernst and Banks (2002); Kording and Wolpert (2004); Weiss, Simoncelli and Adelson (2002); Bowers and Davis (2012); Jones and Love (2011); Rahnev and Denison (2018); Vul et al. (2014); Lieder and Griffiths (2020); Lillicrap et al. (2016, 2020); Whittington and Bogacz (2017); Wang et al. (2018) and Harlow's learning sets; Newell (1973); Laird, Lebiere and Rosenbloom (2017); and every page range in Sources.
Companion material in this repository
The syllabus's plan for this partfrom SYLLABUS.md, the plan of record
- Hook: sparse coding (Olshausen and Field 1996), run on screen: Gabor patches emerge from natural images.
- Efficient coding: Attneave and Barlow; a fly's contrast code matching the histogram of its world (Laughlin 1981); whitening and centre–surround (Part 13) derived.
- Efficiency explains biases: resource-limited codes predict Weber's law (Part 11), capacity limits (Part 19) and "anti-Bayesian" repulsions; value coding in choice (Part 26).
- Rate–distortion theory: the cheapest representation for a tolerated error; Shepard's law (Part 22) derived from it.
- Normalization as a canonical computation: one equation in retina, cortex, attention (Part 18) and value.
- Predictive coding (Rao and Ballard 1999): cortex as a hierarchy sending predictions down and errors up; what the physiological evidence does and does not support.
- The free-energy principle: variational inference derived step by step (link to AI, Built Part 7); action as inference; what is a theorem, what is a model, and the charge of unfalsifiability.
- On you: adaptation after-effects (tilt, motion, colour), each predicted by an efficient code.
- The Bayesian brain and its critics: optimal against what, with which priors; "Bayesian just-so stories".
- Resource rationality: heuristics (Part 26) as optimal use of limited computation.
- Learning rules: backpropagation and the brain; predictive coding as an approximation to it; meta-learning in prefrontal cortex.
- Unified architectures: Newell's "twenty questions" complaint (1973); ACT-R, Soar and the common model; large brain simulations; the scorecard against the Battery.
Psyche: psyche.efficient: whitening and sparse coding on a licensed natural-image set; a predictive-coding
network; a rate–distortion derivation of generalization gradients; an efficient-coding observer reproducing
adaptation effects.
On you: three after-effects with predicted direction and size.
Ledger: sparse coding yielding V1-like fields (replicated); efficient-coding predictions of perceptual bias
(replicated in several domains); prediction-error neurons as predictive coding requires (contested); the
free-energy principle (not directly tested: the question is whether it can be).
In practice: compression and perceptual codecs, neuromorphic design, representation learning in AI.
Frontier: the part's subject. Stated open problems: a normative account of capacity limits; which learning rule
cortex uses; whether any unified theory makes a risky prediction that the special theories do not.
Reading: Barlow 1961; Laughlin 1981; Olshausen & Field 1996; Simoncelli & Olshausen 2001; Carandini & Heeger
2012; Rao & Ballard 1999; Friston 2010; Bowers & Davis 2012; Jones & Love 2011; Wei & Stocker 2015; Sims 2018;
Lieder & Griffiths 2020; Lillicrap et al. 2020; Newell 1973.
Build the film
python -m videos.psychology.psych58.compute # the part's numbers, into .cache/psych58
python tools/build.py psych58 # render and assemble the film
EXPLAINER_TTS=silent python tools/qa_scene.py psych58 Hook # one chapter, silent, with a contact sheet
Scenes: videos/psychology/psych58. Setup: see the course page. Source of these notes: the README and the scenes' narration.
Build it
python -m videos.psychology.psych58.compute # every number (a minute)
python tools/qa_scene.py psych58 Sparse # one chapter, silent, at 480p, with a contact sheet
EXPLAINER_TTS=silent python tools/build.py psych58 -q l # the whole part, silent preview
python tools/build.py psych58 # 1080p30 with narration
python tools/qa_scene.py psych58 Free --lang zh # the Chinese edition of one chapter
python tools/make.py psych58 # both editions, with the checks a long build needs
python -m videos.psychology.labs 58 # the lab: sparse coding, efficient biases, after-effects
python tools/check_ledger.py psych58 # every study shown has its Ledger row, or a reason
python -m pytest tests/psychology # Psyche's efficient module, the Ledger, the Archive
The Chinese edition is zh_lines.py (the narration, line by line) and the series table
videos/psychology/psychology_text_zh.json (the text on screen); the terms are in
PSYCHOLOGY_ZH_GUIDE.md.