Reward and Prediction
How does a brain learn what to do when the reward comes later?
A monkey's dopamine neurons fire at unannounced juice; after training they fire at the cue instead, and fall silent when promised juice is withheld. In 1997 those recordings were matched to the temporal-difference error of reinforcement learning, derived here from the Bellman equation: learn each prediction from the next one. On a delay line the error moves from reward to cue, and an artificial dopamine error, made with light, teaches as a real one does. The same error drives action: actor and critic, Q-learning, and the basal ganglia's Go and NoGo, tested in patients with Parkinson's disease. A bandit's learning rate can be read from choices, if parameter recovery says it can; directed exploration beats greedy choice. Tolman's rats learned maps without reward, and the brain has place and grid cells. Habits and plans are told apart by devaluation, the two-step task and revaluation, with the successor representation between them and replay offline. Dopamine also ramps, signals movement and encodes a distribution; a drug can fake its error; and the same mathematics runs recommender systems and the side effects of a medicine.
What you need. Part 16's Rescorla-Wagner rule and Part 11's maximum likelihood. Expected values, geometric sums and a little linear algebra.
- Hook
- Schultz's monkeys, 1997
- Ideas, models and mathematics
- temporal-difference learning derived, the error's migration and Steinberg's unblocking, actor–critic, Q-learning and Go/NoGo, a bandit fitted and parameter recovery, exploration policies, latent learning, place and grid cells, devaluation and the two-step task, the successor representation and replay, ramps and a distributional code, Redish's drug
- Psyche gains
- a TD learner, Q-learning bandits, a maze planner, two-step agents and a successor learner
- On you
- two slot machines: your α and β fitted
What you will be able to do
Psych 101 and the major
- Describe Schultz's three dopamine recordings and what a reward prediction error is.
- Explain the explore-exploit dilemma, latent learning, and the difference between habits and plans.
- Explain why a drug that raises dopamine directly could hijack learning.
Graduate
- Derive the TD error from the Bellman equation and run TD learning on a conditioning task.
- Fit a Q-learning model to choices by maximum likelihood, and check it by parameter recovery.
- Compute a successor matrix and predict reward and transition revaluation.
Research
- Weigh the evidence that dopamine signals prediction errors against ramps and salience accounts.
- Assess what the two-step task's mixture weight measures.
Practice
- Explain how bandit algorithms run recommendations and A/B tests.
- Explain why dopamine agonists can cause impulse-control disorders.
Contents
Each chapter has a home level. Choose a track to see what to read and watch: Psych 101 and the major 29 min · Graduate 32 min · Research 42 min · Practice 32 min.
- 0A neuron that fires at surprisePsych 101 and the major3 min
- 1Credit over timePsych 101 and the major2 min
- 2Temporal-difference learningResearch3 min
- 3The error moves to the cuePsych 101 and the major3 min
- 4From prediction to actionPsych 101 and the major3 min
- 5A bandit, and your learning ratePsych 101 and the major3 min
- 6Explore or exploitPsych 101 and the major3 min
- 7Tolman's mapsPsych 101 and the major3 min
- 8Habits and plansPsych 101 and the major4 min
- 9Between habit and planResearch3 min
- 10Is dopamine only an error?Research2 min
- 11When the signal is hijackedPsych 101 and the major1 min
- 12The LedgerPsych 101 and the major2 min
- 13In practice: recommenders, medicine, habitsPractice3 min
- 14Frontier: learning to learnResearch2 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 neuron that fires at surprisePsych 101 and the major3 min
In the late 1980s and 1990s, in Fribourg, Wolfram Schultz recorded single dopamine neurons in the midbrains of monkeys while they worked for drops of fruit juice. Here is what he saw, drawn on Psyche rather than copied from his figures. A drop of juice, unannounced: the neuron, ticking along at a few spikes a second, fires a burst. Juice is good, dopamine is pleasure; so far, the obvious story. Now a light comes on a second and a half before every drop. After training, the burst has moved. The neuron fires at the light, and when the juice arrives, nothing: the same juice, no burst. And on a trial when the light comes on but the juice doesn't, the neuron falls silent, briefly, at exactly the moment the juice was due. It isn't signalling reward. It is signalling the difference between the reward it got and the reward it expected.
In 1997 Schultz, with the theorists Peter Dayan and Read Montague, laid those recordings beside an equation. It comes from reinforcement learning, the branch of computer science that teaches machines to act: the temporal-difference error. The reward you got, plus the value of where you are now, minus the value you expected a moment ago. Every feature of the three recordings falls out of it. It is Part 16's prediction error, with one thing added back: time.
Part 16 ended with a rule written for trials, as if nothing happened between a cue and its reward. Real rewards come later: a chess game is won forty moves after the move that won it. How can a brain give credit to a cue or an action that came long before? Is dopamine really the error signal of a learning algorithm, or does the story break somewhere? How do animals and people balance trying something new against using what works? And when do we plan, using a map of the world, rather than just repeating what paid off before?
This is Part 17 of Psychology, Built: reward and prediction. We'll start with the problem of credit over time, and derive temporal-difference learning from the Bellman equation. We'll run it on Pavlov's task and watch Schultz's recordings appear. Then from prediction to action: actor and critic, Q-learning, and the Go and NoGo pathways of the basal ganglia. Then a bandit game, with your learning rate fitted, and the mathematics of exploring. Then Tolman's rats and their maps, place and grid cells, habits against plans, and a representation that sits between them. And at the end, what dopamine does besides the error, how a drug can hijack it, and where this mathematics runs your life: in the recommendations you're shown, and in the side effects of a medicine.
What it does: Schultz's three recordings, drawn on Psyche; the 1997 equation; the questions; objectives
1Credit over timePsych 101 and the major2 min
Here's the problem in its plainest form. A cue appears, time passes, an action is taken, more time passes, and food arrives. The food is the only feedback. Which of the earlier events deserves the credit? Rescorla and Wagner's rule can't say: it updates once per trial, on the trial's outcome, and there is no time inside a trial. The problem is much bigger than rats. A chess game is won forty moves after the move that won it. The first program to learn a game well, Arthur Samuel's checkers player of 1959, used a trick: don't wait for the end of the game. Nudge your estimate of how good each position is toward your estimate of the next one. Learn a guess from a later, better-informed guess. That trick is the subject of this part.
Animals solve a small version of it every day. Train a dog that a buzzer means food. Then pair a light with the buzzer, and never with food. The light comes to bring saliva too. Pavlov's laboratory called it second-order conditioning, and it can be chained further. Rescorla and Wagner's rule has trouble with it: the light is never followed by food, so the outcome on its trials is zero. A learner of values in time has no trouble. The light predicts the buzzer, the buzzer is worth something, and that value flows back to the light. Here it is in Psyche, using the equation from the hook.
What it does: The credit-assignment problem; Samuel's checkers; second-order conditioning
2Temporal-difference learningResearch3 min
First, what is being predicted. Not the next reward, but all the reward still to come, from this moment on: the reward now, plus the reward a step later, discounted a little, plus the one after that, discounted a little more. That sum, averaged over what might happen, is the value of the state you're in. The state is whatever the animal knows about where it is: here, that a light came on three tenths of a second ago. Rewards are mostly zero. And gamma, the discount, a number just below one, says that a reward a step later is worth a little less than the same reward now.
Now the trick. Pull the first reward out of the sum, and what's left is just gamma times the value of the next state. So the value of now equals the reward now plus the discounted value of next. Richard Bellman wrote that equation for engineering problems in the 1950s. If your predictions were right, the two sides would agree on average, so their difference, the reward plus the next value minus the current value, would average zero. That difference is the temporal-difference error, delta. When it isn't zero, move the current prediction a little toward the target. Richard Sutton set this out as a learning method in 1988. Notice what it doesn't need: the end of the game. Every step teaches the step before it, so value flows backward in time, a step per experience. A program built on it taught itself backgammon to world-class level in the early 1990s, and its descendants learned Go. AI, Built takes that road in Part 26.
To use TD on Pavlov's task, the animal needs states within a trial. The simplest assumption is a clock: the cue starts a chain of units, each active at one moment after the cue, like the taps on a delay line. Each moment gets its own value, the reward still to come from then. It's a crude model of how brains keep time, and Part 16 showed that real timing is scalar and fuzzy. But it's enough to show the logic, and it's the representation Schultz, Dayan and Montague used.
What it does: Value as discounted future reward; the Bellman equation; the TD error derived; a delay line
3The error moves to the cuePsych 101 and the major3 min
Here is that clock running on Pavlov's task, for a hundred and twenty trials. Each row is a trial; time runs left to right; green is a positive error. On the first trial nothing is predicted, so all the error is at the juice. The juice raises the value of the moment just before it. On the next trial, reaching that moment is itself a pleasant surprise, so the error appears a step earlier, and the value of the step before that grows in turn. Trial by trial the error slides back until it reaches the cue. The cue itself can't be predicted, because nothing announces it, so the error stops there. And the juice, now fully predicted, produces no error at all. In a real brain, with a fuzzier clock, the error doesn't visibly slide; it fades at the reward and grows at the cue. Either way, the endpoint is Schultz's second recording.
So each of the three recordings is one case of the equation. Juice with no warning: reward minus a prediction of zero, a positive error, a burst. A cue that predicts juice: the cue itself arrives unannounced, so reaching it is a jump in value, a positive error. The juice after the cue: reward, minus the value that predicted it, about zero. And the omitted juice: zero minus the prediction, a negative error, the dip, at the time the clock said the juice was due. Later experiments pushed the match further. A cue that promises juice half the time produces a burst about half as large, and a larger reward a larger one: the neurons report expected value, as the theory says they should.
A correlation between a neuron and an equation is suggestive. A causal test is better. In 2013 Elizabeth Steinberg, Patricia Janak and colleagues gave rats Part 16's blocking design. The added cue should teach nothing, because the reward is already predicted and there's no error. Then they used light, through optogenetics, to switch on the rats' dopamine neurons for a moment, just when the predicted reward arrived. The blocked cue was learned. An artificial prediction error taught the rats exactly what a real one would have. The same stimulation at other times didn't. Dopamine at the moment of reward acts as the teaching signal. Part 16's rule, with the light added to the error, draws the same four bars.
What it does: The migration, computed; every feature from one line; optogenetic unblocking
4From prediction to actionPsych 101 and the major3 min
Predicting reward is half the job. The other half is choosing what to do. In an actor-critic system, an actor chooses actions in each state, and the world responds. A critic learns how good each state is, its value, by temporal-difference learning. The critic's error, delta, says whether things just went better or worse than expected. And the same error teaches the actor: if delta is positive after an action, make that action more likely in that state; if negative, less. It's Thorndike's law of effect, with the critic deciding what counts as satisfying. A popular mapping puts the critic in the ventral striatum, the actor in the dorsal striatum, and the error in dopamine, which reaches both.
A simpler design drops the separate actor. Learn a value for every action in every state, Q of s and a: the reward still to come if you take that action and behave well afterwards. The update is the same temporal-difference error, using the best action available next. Then choose by a softmax: actions with higher values are chosen more often, and a second parameter, beta, sets how strongly. A large beta always takes the best-looking action; a small one spreads its bets. Chris Watkins introduced Q-learning in 1989, and in 2015 a version of it, with a deep network for Q, learned dozens of Atari games from the pixels on the screen.
The basal ganglia offer a two-sided version. In the striatum, one pathway, the direct, promotes an action: Go. Another, the indirect, suppresses it: NoGo. They carry different dopamine receptors. A dopamine burst strengthens Go for whatever was just done; a dip strengthens NoGo. That makes a prediction. A brain short of dopamine should learn better from punishments than from rewards, and one with extra dopamine the reverse. In 2004 Michael Frank, Lauren Seeberger and Randall O'Reilly tested it in people with Parkinson's disease, who lose dopamine neurons, on and off their medication. Off medication, patients were better at learning to avoid symbols that had lost; on it, better at choosing symbols that had won. The asymmetry has been reported again since, though some later studies argue the task mixes reward with plain feedback about being right. Psyche runs the same task on a Go and NoGo learner, with dopamine setting the balance between the two. Avoiding the loser rises as dopamine falls; choosing the winner barely moves. The model gets the direction of the effect, not all of it.
What it does: Actor and critic; Q-learning and the softmax; Go and NoGo; Parkinson's on and off medication
5A bandit, and your learning ratePsych 101 and the major3 min
The simplest place to watch a learner choose is a two-armed bandit, named after slot machines, the one-armed bandits. Two machines; one pays eighty percent of the time and the other twenty. Halfway through, without warning, they swap. Here's Psyche playing, a Q-learner with a learning rate of point three. The lines are its two values; each tick is a choice, coloured when it paid. It settles on the good machine, keeps sampling the other now and then, and after the swap it takes a few disappointments to notice and switch. A summary often used with people is win-stay, lose-shift: how often you repeat a choice that paid, and leave one that didn't. The course page lets you play this game yourself, and fits your own learning rate.
Now the reverse problem, the one experimenters face. Given only someone's choices and rewards, what are their learning rate and their beta? Replay the sequence through the model. At each trial the model, with candidate parameters, says how likely each choice was; multiply the probabilities of the choices actually made. Then search for the parameters that make the observed sequence most likely, maximum likelihood, the same idea as fitting a psychometric function in Part 11. From Psyche's two hundred choices, the fit finds a beta close to the true five, but a learning rate of point five, where the truth was point three. Two hundred choices from one player constrain the learning rate only loosely, and that is worth checking systematically.
Before trusting a fitted number, check that the method can find it. Simulate many players whose parameters you know, fit each one, and compare. The learning rate comes back well. Beta, the decisiveness, comes back less well, especially when it's large: two hundred choices can't tell a very decisive player from an extremely decisive one, since both almost always pick the better machine. This check, parameter recovery, is routine in computational psychiatry, where fitted parameters are compared between patients and controls. A difference in a parameter that can't be recovered is a difference in noise.
What it does: A reversal bandit; reading α and β back by likelihood; parameter recovery
6Explore or exploitPsych 101 and the major3 min
Every learner who chooses faces a dilemma. Exploit: take the option that has paid best so far. Or explore: try something else, because your estimates are built on few samples and might be wrong. Exploit only, and one lucky early win can lock you onto a worse option forever. Explore only, and you never cash in on anything you learn. The right balance depends on how long you'll be choosing. A new restaurant is worth trying on your first week in a city, not on your last night.
How well do simple policies do? Regret measures the reward lost by not knowing which machine is best. Four machines paying between forty and sixty percent, played five thousand times, averaged over a hundred runs. Greedy, always the best so far, often locks onto the wrong machine early, and its regret keeps growing. Epsilon-greedy explores at random a tenth of the time: it finds the best machine, but keeps wasting a tenth of its plays for ever, so its regret keeps climbing in a straight line. Softmax on averages this close together explores far too much, and does no better than greedy. The upper confidence bound adds a bonus to options you know little about; with the textbook bonus it's guaranteed to do well in the long run, but it explores for a long time before it settles, and its curve bends only slowly. Thompson sampling, from 1933, draws a plausible payoff for each machine from what you know and plays the best draw. It directs its exploring to where uncertainty is, tapers it off as it learns, and here it does best.
Do people explore like this? In 2014 Robert Wilson and colleagues gave people two options, some samples of each, and either one more choice to make or six. With six choices ahead, people picked the option they knew less about more often, even when it looked a little worse: directed exploration, like the uncertainty bonus. They also became more random: a softer softmax. So people use both kinds, and tune both to the horizon, as they should. Later studies find that children explore more than adults, which is what a long horizon calls for.
What it does: The dilemma; five policies and their regret; directed and random exploration in people
7Tolman's mapsPsych 101 and the major3 min
Edward Tolman, at Berkeley, thought rats learned more than responses. In 1930 he and Charles Honzik ran rats through a maze once a day. One group found food in the goal box every day; one never did; and one found nothing for ten days, then food from the eleventh. The rats fed every day improved steadily. The unfed rats wandered. And the third group, on the day after food first appeared, ran the maze about as well as rats that had been fed all along. They had been learning the maze all the while, without any reward to strengthen anything, and showed it only when there was a reason to. Here are the same three groups run on Psyche, with a learner that builds a map and plans on it. It learns far faster than any rat, so the fed group masters the maze in two days; what matters is the late group's jump. In blue, a learner without a map, which has nothing to show when the food appears.
In 1948 Tolman gave the idea its name. Rats, he argued, build cognitive maps of their environment, not chains of stimulus and response. A rat with a map can take a shortcut it has never run, or find a way round a blocked path. His opponents explained each result some other way, and the argument lasted decades. In reinforcement learning, the map is what's called a model: knowledge of which states lead to which, and what each pays. With a model you can plan. Without one, you can only repeat what paid before.
Tolman's map turned out to be literal. In 1971 John O'Keefe, recording in the hippocampus of rats, found neurons that fire whenever the animal is in one particular place in the room, and almost never elsewhere: place cells. In 2005 May-Britt and Edvard Moser, in Trondheim, found cells next door, in the entorhinal cortex, that fire at many places, arranged in a triangular lattice that tiles the whole floor: grid cells, a coordinate system for space. The three shared the Nobel Prize in 2014, and grid-like signals have since been found in human brains, during navigation and even when people move through abstract spaces of ideas.
What it does: Latent learning on Psyche; cognitive maps; place and grid cells
8Habits and plansPsych 101 and the major4 min
How can you tell whether an animal is planning or acting from habit? Tony Dickinson and Christopher Adams found a way in the early 1980s. Rats learn to press a lever for sugar pellets. Then the pellets are devalued, outside the box: paired with mild sickness, or eaten until the rats are sick of them. Back in the box the lever delivers nothing, so the rats can only act on what they know. Do they still press? After moderate training they press much less: the action is aimed at a goal they no longer want. After extensive training they press as hard as ever. The action has become a habit, triggered by the box, and blind to what the goal is now worth. In the terms of this part: a model-based planner, which values an action by what it leads to, sees the change at once. A model-free learner, which has cached a value for the action itself, cannot until it experiences the new outcome.
In 2011 Nathaniel Daw and colleagues built a task that separates the two strategies trial by trial. A first choice, between A and B. A usually leads to the pink state and B to the blue, seventy percent of the time; the other thirty percent, the transition is rare and you land in the other state. In each second state you choose again, and each option there pays with a probability that drifts slowly, so there's always something to learn. Now suppose you chose A, had a rare transition to blue, and were rewarded. A model-free learner credits A with the reward and repeats it. A planner reasons differently: blue is what's good now, and the way to reach blue is usually B. So after a rewarded rare transition, a planner switches.
The two strategies leave different fingerprints in how often people repeat their first choice. A model-free learner repeats after reward and switches after no reward, whatever the transition was: the coloured and grey bars match. A model-based learner shows an interaction: after a rare transition, the effect of reward reverses. And a mixture shows both. Daw's seventeen participants looked like the mixture, and their striatum, in functional imaging, carried prediction errors computed both ways. People are neither pure creatures of habit nor pure planners.
The task became famous, and its interpretation became an argument. The weight on planning became a measure: it's lower, on average, in people with compulsive symptoms, under stress, and when people are distracted by a second task. But a model-free learner given the right states, for instance one that treats a rare transition as a different situation, can produce the planner's signature without planning. And in 2020 Carolina Feher da Silva and Todd Hare found that when the task is explained very carefully, people look almost purely model-based; much of the apparent habit may be misunderstanding. The Ledger keeps the two apart: the pattern replicates; what it measures is contested.
What it does: Devaluation; the two-step task; three signatures; what the weight means
9Between habit and planResearch3 min
There's a middle way between caching values and planning from scratch. Instead of caching how good each state is, cache where you tend to go from it: for every other state, how often, discounted, you'll find yourself there. That table is the successor representation, M. For a known transition matrix it's the inverse of the identity minus gamma times T. A value is then a single multiplication: expected future visits, times what each state pays. Its strengths and weaknesses are exactly predictable. Change what a state pays, and every value updates at once, as if you'd planned. Change the paths between states, and the cached visits are out of date, as if it were a habit. Peter Dayan proposed it in 1993; twenty-five years later it became a serious candidate for what the hippocampus computes.
Ida Momennejad, Sam Gershman and colleagues turned this into a test in 2017. People learn two short paths: from state one, through three, to five, which pays ten; from two, through four, to six, which pays one. Then they learn a change, but only by visiting the later states. In reward revaluation, five now pays one and six pays ten. A model-free learner, with cached values for one and two, still prefers one. The successor learner and the planner both switch to two. In transition revaluation, three now leads to six and four to five. Now the successor learner is stuck too, because its cached predictions from one and two still say where they used to lead. Only the planner switches. People did better at reward revaluation than at transition revaluation: the successor signature, though they managed some transition revaluation too, suggesting a mixture with planning.
How might a brain plan, or update its cached predictions, without acting? In 1994 Matthew Wilson and Bruce McNaughton found that place cells which had fired together while a rat ran a track fired together again while it slept. Later work found whole sequences: the place cells of a path firing in order, compressed into a fraction of a second, forwards and backwards. Backward replay, just after a reward, runs from the goal toward the start, the order that would spread value back along the path in a single sweep. Forward replay, before a choice, looks like trying routes out. One recent theory says the brain prioritizes which experiences to replay by how much replaying them would improve its choices. Memory and its consolidation are Part 21.
What it does: The successor representation; reward and transition revaluation; replay
10Is dopamine only an error?Research2 min
The prediction-error account is one of psychology's great successes, and it is not the whole story. In 2013 Mark Howe, Ann Graybiel and colleagues measured dopamine in the striatum as rats ran a maze toward a reward. It didn't burst; it ramped up steadily as the rats got closer. A pure TD error, once learning is complete, shouldn't do that. Other recordings found dopamine neurons that fire as movements begin, whatever the reward. And some respond to anything surprising or intense, pleasant or not, which sounds more like salience than value. There are replies. A ramp can be a TD error if the animal is uncertain where it is or how much time has passed, and some argue ramps encode value directly. The likeliest resolution is that dopamine neurons aren't all alike, and the reward prediction error is one important message among several.
The newest twist came from artificial intelligence. Suppose rewards vary: usually small, sometimes large. A single prediction error learns the average. But imagine many learners, each weighing good surprises and bad surprises differently. An optimist, which counts good news heavily, settles high; a pessimist settles low. Each settles at a particular point of the distribution, called an expectile. Together, the population encodes the whole distribution of rewards, not just its mean. In 2020 Will Dabney and colleagues, working with Naoshige Uchida's recordings in mice, found that dopamine neurons do differ in exactly this way: some reverse their response at small rewards, some only at large ones, consistently. The idea had first improved game-playing agents. Here, for once, a trick from machine learning came back as a discovery about brains.
What it does: Ramps, movement and salience; a distributional code
11When the signal is hijackedPsych 101 and the major1 min
If dopamine is a teaching signal, what happens when a drug produces it directly? In 2004 David Redish wrote the simplest answer down. For a natural reward, the error shrinks as the cue comes to predict it, and learning stops: the value levels off. Drugs such as cocaine and amphetamine raise dopamine pharmacologically, whatever the brain predicted. In Redish's model the drug adds a surge that learning can't cancel: the error never falls below it. So the value of everything that leads to the drug keeps rising, use after use, far beyond any natural reward. It makes a testable prediction, that drug rewards shouldn't show blocking, and tests have given mixed results. Addiction involves much more: withdrawal, stress, habits that outlast pleasure, and a person's whole situation. Part 41 takes it up. But the model shows why a learning system built on prediction errors is vulnerable to anything that fakes one.
What it does: Redish's model of a drug that cannot be predicted away
12The LedgerPsych 101 and the major2 min
Four rows today. The first: midbrain dopamine neurons signal reward prediction errors. The original: Schultz, Dayan and Montague, 1997, drawing on Schultz's recordings in monkeys. The record: the error signature has been found across species and methods, and in 2013 Steinberg and colleagues showed that an artificial error, made with light, teaches like a real one. The core finding is among the best replicated in neuroscience. What else dopamine signals, ramps, movement and salience, is argued. Replicated, with its scope contested.
The second: in the two-step task, people's choices show both model-free and model-based signatures. The original: Daw and colleagues, 2011, seventeen people. The record: the pattern has been found in thousands of people since, online and in the laboratory; but Feher da Silva and Hare, in 2020, found that with careful instructions people look almost entirely model-based. The pattern replicates. Whether it measures two systems, or partly misunderstanding, is contested. Replicated; the reading contested.
The third: rats explore a maze without reward and learn its layout, showing it as soon as a reward appears. The original: Tolman and Honzik, 1930. The record: reviewed by Thistlethwaite in 1951, latent learning was found in most of the many experiments that looked, with failures in some designs. The effect is robust where the animal can explore freely; the theoretical war it started is over, and maps won. Replicated.
The fourth: cells in the entorhinal cortex fire on a triangular grid as an animal moves through space. The original: Hafting, Fyhn, Molden and the Mosers, 2005, in rats. The record: found in mice, bats and monkeys, and as grid-like signals in human imaging, beginning with Doeller, Barry and Burgess in 2010. The cells are as solid as anything in neuroscience; what grid-like signals mean in human thought is newer. Replicated.
What it does: Dopamine errors; the two-step task; latent learning; grid cells
13In practice: recommenders, medicine, habitsPractice3 min
The mathematics of this part runs much of the internet. A news site, a shop or a video feed faces a bandit problem with every visitor: which item to show this person, now. A click is a reward, each item is an arm, and the system must explore new items while exploiting known favourites. In 2010 Lihong Li and colleagues at Yahoo! showed that a contextual bandit, one that uses what it knows about the visitor, chose front-page stories that drew more clicks than a system that only exploited. Bandit tests now replace many fixed A/B tests: instead of splitting traffic evenly to the end, they shift visitors toward the better version while the test runs. On two versions clicked five and six percent of the time, a Thompson sampler sends most visitors to the better one within a few thousand, and collects about seventy more clicks in twenty thousand visits than an even split. There's a catch that psychologists should notice. A system that learns from your clicks also changes what you'll click next. The learner and the learned-about are training each other.
The second application is in medicine, and it's a warning. Parkinson's disease kills dopamine neurons, and it's treated by restoring dopamine: with levodopa, its precursor, or with drugs called agonists that mimic it. Agonists stimulate dopamine receptors steadily, whatever happens. In 2010 Daniel Weintraub and colleagues surveyed more than three thousand patients. About one in seven had an impulse-control disorder, and among those taking agonists, about one in six, compared with one in fifteen on levodopa alone. Pathological gambling, compulsive shopping, binge eating, compulsive sexual behaviour: often new since treatment, and often hidden from doctors. One reading is a reinforcement signal that no longer tracks outcomes, so that a loss doesn't teach as it should. Patients and families are now warned to watch for it, and the drugs adjusted when it appears.
And the theory says something about everyday habits. A habit is a cached value: cheap and fast, and slow to notice when the outcome has changed, like the overtrained rats pressing for pellets they no longer want. That's why breaking a habit rarely works by reasoning alone. The cached value hasn't heard the argument. What tends to work is changing the cues and the context that call up the action: the phone left in another room. Building a habit is the same in reverse: the same cue, the same action, reliably rewarded, for a long time. Apps that reward unpredictably, with streaks and badges, use the same tools aimed the other way. Part 52 is about designing for minds.
What it does: Bandits online; impulse-control disorders on agonists; habits
14Frontier: learning to learnResearch2 min
Here's where things stand. Solid: dopamine neurons carry reward prediction errors; an error at the time of reward teaches, causally; rats and people learn maps without reward; and place and grid cells exist. Argued: what dopamine ramps and movement signals mean; whether people are ever purely model-free; what the two-step task's weight really measures; and where the brain keeps its model of the world, and how it plans with it. One more question is at the frontier.
The question is whether the brain contains a learner that learns how to learn. In 1949 Harry Harlow gave monkeys hundreds of small problems: two objects, one with a raisin under it. Each problem used new objects. The monkeys got faster and faster. By the end they solved a new problem in a single trial: if the first object paid, stay with it; if not, switch. They had learned a strategy, a learning set, not any particular answer. In 2018 Jane Wang, Matthew Botvinick and colleagues proposed how. Slow, dopamine-driven learning, of the kind this part describes, gradually tunes the dynamics of the prefrontal cortex. The tuned circuit then learns each new task quickly, in its pattern of activity, without needing to change its connections at all. A recurrent network trained this way behaves like Harlow's monkeys. Learning to learn is one theme of Part 58.
And some questions nobody has answered. The TD story assumes the animal knows what state it's in. Often it doesn't, and building states, deciding which situations count as the same, may be the hardest part of learning. How does the brain represent time within a trial? The delay line was a stand-in. What decides when to plan and when to trust a habit? Proposals weigh the cost of thinking against what's at stake. And can any learning rule of this kind explain how people learn in a world of language, where one sentence can change what we expect? Part 16's frontier asked the same question from the other side.
What it does: What is solid and argued; Harlow's learning sets and meta-learning; open questions
Recap, problems, and the road aheadAll tracks3 min
Part seventeen in ten lines. Dopamine neurons fire at surprise: at unpredicted reward, at a cue that predicts reward, and they dip when a promised reward fails. Credit over time is solved by learning each prediction from the next one. Temporal-difference learning follows from the Bellman equation, and its error is reward plus discounted next value minus current value. On Pavlov's task that error moves to the cue, and an artificial error teaches as a real one does. Actor and critic, Q-learning, and the Go and NoGo pathways turn errors into actions. A learning rate can be read from choices, if you check that it can be recovered, and good explorers direct their exploring. Animals learn maps without reward, and the brain contains place and grid cells. Habits and plans can be told apart, by devaluation, the two-step task and revaluation, with replay in between. Dopamine is more than one error. And a drug can fake it, a recommender can exploit it, and a medicine can derail it.
Kant's wager. The first objection, that mathematics can't apply to the mind, met its strongest answer yet: a single neuron whose firing follows a term in an equation from computer science. And the second, that the mind can't be experimented on, met an experiment that switched a learning signal on with light and watched the learning change.
Where this comes back. Attention, and what's worth learning about, is next, Part 18. Memory, replay and consolidation are Part 21. Decisions, value and risk are Part 26. Motivation, and the difference between wanting and liking, is Part 28. Addiction is Part 41, products designed around habits Part 52, and the predictive brain, with learning to learn, Part 58.
Seven problems, with full solutions in this part's README. One computes values on a short chain by hand. One derives the TD error. One times the error's journey back to the cue. One writes the likelihood of a bandit player's choices. One builds a successor matrix. One uses Psyche to trace the two-step signature as planning increases. And the last, with the star, asks how to tell what a dopamine ramp means. Pause here if you'd like to try them.
The books and papers behind this part are listed here and in the README. Sutton and Barto's Reinforcement Learning, especially its chapters on psychology and neuroscience, is the place to start.
Learning needs something to learn about, and the world offers far more than any brain can take in. Mackintosh and Pearce and Hall argued that attention itself is learned. Next time, attention in its own right: why a gorilla can walk through a basketball game unseen by half the people watching it, and what a brain does with the rest. It's Part 18: attention.
Where it goes next. Attention is Part 18, memory and replay Part 21, decisions and risk Part 26, motivation Part 28, addiction Part 41, products built around habits Part 52, and the predictive brain Part 58.
Key results
The part's results in one place, for revision.
Try it
Lab 17 · Reward and prediction: TD learning, bandits, maps and the successor representation
Run TD(0) with a delay line and watch the error move from the juice to the cue and dip at an omission; teach a second cue through the first; fit a Q-learner's learning rate and inverse temperature from its choices, and check whether a fit can be trusted; compare how five policies explore; tell model-free from model-based agents in the two-step task; compute a successor matrix and predict which revaluations it passes; recover a reward distribution from optimistic and pessimistic learners; and see why a drug's surge never stops teaching.
python -m videos.psychology.labs 17
needs numpy, scipy, matplotlib · download lab17.py ·
source on GitHubtrial 1: the error at the juice, and at the cue 1.00, 0.00
trial 140: the error at the juice, and at the cue 0.000, 0.72
trial 150, juice omitted: the error when it was due -1.00
the cue's error after training, and gamma^(steps to the juice) 0.722, 0.724
where the error peaks within the trial, trials 1, 11, ..., 51 (step) 20, 18, 16, 14, 12, 10
second-order conditioning: A's value after 1, 20 and 60 trials with B and no reward 0.00, 0.15, 0.78
one player (alpha 0.3, beta 5): fitted alpha, beta; win-stay, lose-shift 0.50, 5.5; 96%, 40%
parameter recovery over 16 players: correlation of true and fitted alpha 0.92
regret after 2,000 plays: greedy, epsilon, softmax, UCB1, Thompson 161, 48, 127, 100, 40
two-step, model-free: P(stay) after rewarded-common, rewarded-rare, unrewarded-common, unrewarded-rare 0.91, 0.92, 0.58, 0.57
two-step, model-based: P(stay) after rewarded-common, rewarded-rare, unrewarded-common, unrewarded-rare 0.66, 0.46, 0.47, 0.67
a three-state chain: M from the start state 1.00, 0.90, 8.10
reward revaluation: does V(2) now beat V(1)? model-free, successor, model-based no, yes, yes
transition revaluation: does V(2) now beat V(1)? model-free, successor, model-based no, no, yes
distributional TD against the exact expectiles (tau 0.05 ... 0.95), largest gap 0.29 (values 0.38 ... 7.49; mean 2.15)
Redish: the cue's value after 50 and 200 uses, food; drug 0.99, 1.00; 2.98, 10.48
The error starts at the juice and moves back to the cue, where it settles at the discounted reward; an omission dips exactly when the juice was due. The bandit's learning rate is fitted, but one player pins it loosely: recovery across players says how far to trust it. Thompson sampling explores best here. Model-free and model-based agents differ only after rare transitions; the successor learner passes reward revaluation and fails transition revaluation. Optimists and pessimists together carry the whole distribution, and a drug's surge never stops teaching.
The code (114 lines; it asserts its own result)
"""Lab 17: temporal-difference learning on Pavlov's task and the migration of the error to the cue; second-order
conditioning; a reversal bandit fitted by maximum likelihood, with parameter recovery; the regret of five exploration
policies; the two-step task's stay probabilities; the successor representation and the two revaluations;
distributional TD; and Redish's drug that cannot be predicted away."""
import numpy as np
from videos.coursekit import labs
from explainer.psychology.psyche import rl
TITLE = "Reward and prediction: TD learning, bandits, maps and the successor representation"
GOAL = ("Run TD(0) with a delay line and watch the error move from the juice to the cue and dip at an omission; "
"teach a second cue through the first; fit a Q-learner's learning rate and inverse temperature from its "
"choices, and check whether a fit can be trusted; compare how five policies explore; tell model-free from "
"model-based agents in the two-step task; compute a successor matrix and predict which revaluations it "
"passes; recover a reward distribution from optimistic and pessimistic learners; and see why a drug's "
"surge never stops teaching.")
TASKS = [
"Raise the discount gamma from 0.98 to 0.999 and lower it to 0.8. How does the size of the error at the cue, "
"after training, depend on gamma and on the delay between cue and juice? Derive the answer from the Bellman "
"equation.",
"Fit the bandit with 50, 100 and 400 trials per player. At what length does the correlation between true and "
"fitted learning rates pass 0.9? What does that say about studies that fit 80 trials?",
"Give the successor learner a learning rate for M and let it relearn M from experience after a transition "
"change. How many passes through the new path does it need to pass the transition revaluation?",
]
CUE, REW = 5, 20
def run(seed=0):
out = labs.Lab()
# 1. the error moves to the cue
D, V = rl.td_conditioning(trials=150, cue=CUE, reward=REW, omit=(149,))
out.row("trial 1: the error at the juice, and at the cue", f"{D[0, REW]:.2f}, {D[0, CUE - 1]:.2f}")
out.row("trial 140: the error at the juice, and at the cue", f"{D[140, REW]:.3f}, {D[140, CUE - 1]:.2f}")
out.row("trial 150, juice omitted: the error when it was due", f"{D[149, REW]:.2f}")
expect = 0.98 ** (REW - CUE + 1)
assert abs(D[140, CUE - 1] - expect) < 0.02, "after training the cue's error is the discounted reward"
out.row("the cue's error after training, and gamma^(steps to the juice)", f"{D[140, CUE - 1]:.3f}, {expect:.3f}")
first_peak = [int(np.argmax(D[k, CUE:REW + 1])) + CUE for k in range(0, 60, 10)]
out.row("where the error peaks within the trial, trials 1, 11, ..., 51 (step)", ", ".join(map(str, first_peak)))
so = rl.second_order()
out.row("second-order conditioning: A's value after 1, 20 and 60 trials with B and no reward",
f"{so[0]:.2f}, {so[19]:.2f}, {so[-1]:.2f}")
# 2. a bandit, fitted
P = np.r_[np.tile([0.8, 0.2], (100, 1)), np.tile([0.2, 0.8], (100, 1))]
C, R, _ = rl.q_learning_bandit(P, trials=200, alpha=0.3, beta=5.0, rng=np.random.default_rng(seed + 5))
a, b, _ = rl.fit_bandit(C, R)
ws, ls = rl.win_stay_lose_shift(C, R)
out.row("one player (alpha 0.3, beta 5): fitted alpha, beta; win-stay, lose-shift",
f"{a:.2f}, {b:.1f}; {ws:.0%}, {ls:.0%}")
rng = np.random.default_rng(seed + 23)
ta, fa = [], []
for k in range(16):
t_a, t_b = rng.uniform(0.1, 0.8), rng.uniform(2.0, 10.0)
c, r, _ = rl.q_learning_bandit(P, trials=200, alpha=t_a, beta=t_b, rng=np.random.default_rng(seed + 1000 + k))
ta.append(t_a)
fa.append(rl.fit_bandit(c, r)[0])
rec = float(np.corrcoef(ta, fa)[0, 1])
out.row("parameter recovery over 16 players: correlation of true and fitted alpha", f"{rec:.2f}")
# 3. exploring
reg = {p: np.mean([rl.explore_regret(p, trials=2000, rng=np.random.default_rng(seed + s))[-1] for s in range(20)])
for p in ("greedy", "epsilon", "softmax", "ucb", "thompson")}
out.row("regret after 2,000 plays: greedy, epsilon, softmax, UCB1, Thompson",
", ".join(f"{v:.0f}" for v in reg.values()))
# 4. habits and plans
sp = {}
for name, w in (("model-free", 0.0), ("model-based", 1.0)):
sp[name] = np.mean([list(rl.stay_probabilities(rl.two_step(w, rng=np.random.default_rng(seed + s))).values())
for s in range(12)], axis=0)
out.row(f"two-step, {name}: P(stay) after rewarded-common, rewarded-rare, unrewarded-common, unrewarded-rare",
", ".join(f"{v:.2f}" for v in sp[name]))
T = np.array([[0, 1, 0], [0, 0, 1], [0, 0, 1.0]])
M = rl.successor_matrix(T, gamma=0.9)
assert np.allclose(M, np.eye(3) + 0.9 * T @ M), "M satisfies its own Bellman equation, M = I + gamma T M"
out.row("a three-state chain: M from the start state", ", ".join(f"{v:.2f}" for v in M[0]))
for kind in ("reward", "transition"):
res = rl.revaluation(kind)
out.row(f"{kind} revaluation: does V(2) now beat V(1)? model-free, successor, model-based",
", ".join("yes" if v2 > v1 else "no" for v1, v2 in res.values()))
# 5. beyond the mean
r = np.r_[np.full(300, 0.1), np.full(200, 0.3), np.full(150, 1.2), np.full(150, 2.5), np.full(100, 5.0),
np.full(100, 10.0)]
taus = np.linspace(0.05, 0.95, 7)
v = rl.distributional_td(r, taus, lr=0.02, epochs=40, rng=np.random.default_rng(seed + 3))
ex = np.array([rl.expectile(r, t) for t in taus])
out.row("distributional TD against the exact expectiles (tau 0.05 ... 0.95), largest gap",
f"{np.abs(v - ex).max():.2f} (values {v[0]:.2f} ... {v[-1]:.2f}; mean {r.mean():.2f})")
nat, drug = rl.redish(trials=200), rl.redish(trials=200, drug=0.5)
out.row("Redish: the cue's value after 50 and 200 uses, food; drug", f"{nat[49]:.2f}, {nat[-1]:.2f}; "
f"{drug[49]:.2f}, {drug[-1]:.2f}")
out.note = ("The error starts at the juice and moves back to the cue, where it settles at the discounted reward; "
"an omission dips exactly when the juice was due. The bandit's learning rate is fitted, but one "
"player pins it loosely: recovery across players says how far to trust it. Thompson sampling "
"explores best here. Model-free and model-based agents differ only after rare transitions; the "
"successor learner passes reward revaluation and fails transition revaluation. Optimists and "
"pessimists together carry the whole distribution, and a drug's surge never stops teaching.")
fig, ax = labs.figure(2, size=(11, 4.2))
ax[0].imshow(D[:120:2], aspect="auto", cmap="Greens", vmin=0, vmax=1)
ax[0].set(title="The TD error, trial by trial", xlabel="time step (cue at 5, juice at 20)", ylabel="trial / 2")
for (name, col) in (("model-free", labs.BLUE), ("model-based", labs.PINK)):
ax[1].plot(range(4), sp[name], marker="o", color=col, lw=1.6, label=name)
ax[1].set_xticks(range(4), ["rew, common", "rew, rare", "unrew, common", "unrew, rare"], fontsize=8)
ax[1].set(title="The two-step task", ylabel="P(stay)")
ax[1].legend(fontsize=8)
out.fig = fig
return out
Now change it
- Raise the discount gamma from 0.98 to 0.999 and lower it to 0.8. How does the size of the error at the cue, after training, depend on gamma and on the delay between cue and juice? Derive the answer from the Bellman equation.
- Fit the bandit with 50, 100 and 400 trials per player. At what length does the correlation between true and fitted learning rates pass 0.9? What does that say about studies that fit 80 trials?
- Give the successor learner a learning rate for M and let it relearn M from experience after a transition change. How many passes through the new path does it need to pass the transition revaluation?
Problems, with solutions
Try each problem before opening its solution.
1. Values on a short chain. With \(\gamma = 0.9\) and one reward of 1 three steps after a cue, find the value of each step after the cue, and the TD error at the cue once learning is complete.
Solution
With the reward at the third step after the cue (steps 0, 1, 2, 3 and the juice at step 3), V(3) = 1, V(2) = 0.9, V(1) = 0.81, V(0) = 0.729. The moment before the cue has value 0, because nothing predicts the cue, so at the cue's onset δ = 0 + γV(0) − 0 = 0.656; at the juice, δ = 1 + 0 − 1 = 0.
2. The TD error from Bellman. Derive the TD error from the Bellman equation, and show that its expected value is zero when \(V\) is correct.
Solution
If V is correct, V(s) = E[r + γV(s′) | s], so E[δ | s] = E[r + γV(s′) | s] − V(s) = 0. A nonzero average error means the prediction is off, and moving V(s) by αδ is a stochastic step toward the fixed point (for a fixed policy, the Bellman operator is a contraction with factor γ, so the fixed point is unique).
3. The error's journey. On a delay line with \(\alpha = 1\), show that the error moves back one step per trial, and find how many trials it takes to reach a cue 15 steps before the reward.
Solution
With α = 1, the first trial sets the value of the juice's own moment; on the next trial the moment before it is a surprise and takes the value γ, and so on: each trial moves the first nonzero value one step earlier. Fifteen steps take fifteen trials, and from the sixteenth trial on the error sits at the cue's onset, where it stays because the cue is unpredicted. With smaller α the front still moves a step per trial but takes many trials to grow.
4. The bandit's likelihood. Write the log-likelihood of a choice sequence under Q-learning with a softmax, and say why \(\beta\) is hard to recover when it is large.
Solution
log L(α, β) = Σₜ [β Q_t(a_t) − log Σ_b e^{β Q_t(b)}], with Q updated by α after each outcome. When β is large, nearly every choice goes to the higher-valued option, so P(a_t) ≈ 1 for almost all trials whether β is 15 or 30: the likelihood is flat in β beyond a point, and β is poorly recovered (chapter five's plot). The learning rate is pinned down by the few trials around a change, which is why reversals help.
5. A successor matrix. Compute the successor matrix \(M = (I - \gamma T)^{-1}\) for a three-state chain, and show how \(V = Mr\) handles a reward change but not a transition change.
Solution
For the chain 1 → 2 → 3 (3 ends the episode), T has ones at (1, 2) and (2, 3), and M = I + γT + γ²T² has rows (1, γ, γ²), (0, 1, γ), (0, 0, 1). With a reward r at state 3, V = Mr gives V(1) = γ²r, V(2) = γr: a new r updates every value at once. If state 2 now leads to a state 4 instead, the true M changes row 1 (and row 2); a learner that revisits only state 2 updates row 2, but row 1 still predicts a visit to 3: transition revaluation fails for the successor representation and succeeds for a planner that recomputes M from T.
6. The two-step signature against w. With explainer.psychology.psyche.rl: run the two-step task with \(w\) from 0 to 1, and plot the interaction in the stay probabilities against \(w\).
Solution
Running rl.two_step with w from 0 to 1 and computing the interaction
(P(stay | rewarded, common) − P(stay | rewarded, rare)) − (P(stay | unrewarded, common) − P(stay | unrewarded, rare))
gives about 0 at w = 0, rising roughly linearly to about 0.4 at w = 1 for the default α = 0.5, β = 5; the main effect
of reward shrinks as w grows.
7. ★ What a ramp means. Design an experiment that tells a dopamine ramp that is a TD error under uncertainty from one that encodes value.
Solution
If a ramp is a TD error under uncertainty about position or time, a sudden jump forward (teleporting the animal closer in virtual reality, or a cue that tells it more time has passed) should produce a phasic burst proportional to the jump in value, and the ramp's slope should change with running speed; if the ramp encodes value itself, a jump should shift its level without a transient burst. Kim et al. (2020) ran this logic in mice in virtual reality and found the bursts.
Notes and sources
Where it comes back
Attention, and what is worth learning about: Part 18. Memory, replay and consolidation: Part 21. Decisions, value and
risk: Part 26. Motivation, wanting and liking: Part 28. Addiction: Part 41. Products designed around habits: Part 52.
The predictive brain, and learning to learn: Part 58. Psyche's rl module supplies the learners those parts extend.
Sources
Books. R. S. Sutton and A. G. Barto, Reinforcement Learning: An Introduction, 2nd ed. (MIT Press, 2018), chapters 14 and 15. P. Dayan and L. F. Abbott, Theoretical Neuroscience (MIT Press, 2001), chapter 9.
Papers. W. Schultz, P. Dayan and P. R. Montague, A neural substrate of prediction and reward, Science 275 (1997) 1593–1599. R. S. Sutton, Learning to predict by the methods of temporal differences, Mach. Learn. 3 (1988) 9–44. A. L. Samuel, Some studies in machine learning using the game of checkers, IBM J. Res. Dev. 3 (1959) 210–229. A. G. Barto, R. S. Sutton and C. W. Anderson, Neuronlike adaptive elements that can solve difficult learning control problems, IEEE Trans. Syst. Man Cybern. 13 (1983) 834–846. C. J. C. H. Watkins, Learning from Delayed Rewards (PhD thesis, Cambridge, 1989). E. E. Steinberg et al., A causal link between prediction errors, dopamine neurons and learning, Nat. Neurosci. 16 (2013) 966–973. M. J. Frank, L. C. Seeberger and R. C. O'Reilly, By carrot or by stick, Science 306 (2004) 1940–1943. H. Robbins, Some aspects of the sequential design of experiments, Bull. Am. Math. Soc. 58 (1952) 527–535. W. R. Thompson, On the likelihood that one unknown probability exceeds another, Biometrika 25 (1933) 285–294. P. Auer, N. Cesa-Bianchi and P. Fischer, Finite-time analysis of the multiarmed bandit problem, Mach. Learn. 47 (2002) 235–256. R. C. Wilson et al., Humans use directed and random exploration to solve the explore-exploit dilemma, J. Exp. Psychol. Gen. 143 (2014) 2074–2081. E. C. Tolman and C. H. Honzik, Introduction and removal of reward, and maze performance in rats, Univ. Calif. Publ. Psychol. 4 (1930) 257–275. E. C. Tolman, Cognitive maps in rats and men, Psychol. Rev. 55 (1948) 189–208. D. Thistlethwaite, A critical review of latent learning and related experiments, Psychol. Bull. 48 (1951) 97–129. J. O'Keefe and J. Dostrovsky, The hippocampus as a spatial map, Brain Res. 34 (1971) 171–175. T. Hafting et al., Microstructure of a spatial map in the entorhinal cortex, Nature 436 (2005) 801–806. C. F. Doeller, C. Barry and N. Burgess, Evidence for grid cells in a human memory network, Nature 463 (2010) 657–661. C. D. Adams and A. Dickinson, Instrumental responding following reinforcer devaluation, Q. J. Exp. Psychol. 33B (1981) 109–121. N. D. Daw et al., Model-based influences on humans' choices and striatal prediction errors, Neuron 69 (2011) 1204–1215. T. Akam, R. Costa and P. Dayan, Simple plans or sophisticated habits?, PLoS Comput. Biol. 11 (2015) e1004648. C. Feher da Silva and T. A. Hare, Humans primarily use model-based inference in the two-stage task, Nat. Hum. Behav. 4 (2020) 1053–1066. P. Dayan, Improving generalization for temporal difference learning: the successor representation, Neural Comput. 5 (1993) 613–624. I. Momennejad et al., The successor representation in human reinforcement learning, Nat. Hum. Behav. 1 (2017) 680–692. M. A. Wilson and B. L. McNaughton, Reactivation of hippocampal ensemble memories during sleep, Science 265 (1994) 676–679. M. G. Mattar and N. D. Daw, Prioritized memory access explains planning and hippocampal replay, Nat. Neurosci. 21 (2018) 1609–1617. M. W. Howe et al., Prolonged dopamine signalling in striatum signals proximity and value of distant rewards, Nature 500 (2013) 575–579. W. Dabney et al., A distributional code for value in dopamine-based reinforcement learning, Nature 577 (2020) 671–675. A. D. Redish, Addiction as a computational process gone awry, Science 306 (2004) 1944–1947. L. Li, W. Chu, J. Langford and R. E. Schapire, A contextual-bandit approach to personalized news article recommendation, WWW (2010) 661–670. D. Weintraub et al., Impulse control disorders in Parkinson disease: a cross-sectional study of 3090 patients, Arch. Neurol. 67 (2010) 589–595. H. F. Harlow, The formation of learning sets, Psychol. Rev. 56 (1949) 51–65. J. X. Wang et al., Prefrontal cortex as a meta-reinforcement learning system, Nat. Neurosci. 21 (2018) 860–868.
About this partfrom its README
A monkey gets an unannounced drop of juice and a dopamine neuron fires. After training, the neuron fires at the light that predicts the juice and not at the juice; when the juice is withheld it falls silent at the moment it was due. In 1997 those recordings were laid beside the temporal-difference error of reinforcement learning, δ = r + γV′ − V, and they matched. This part derives that error, runs it, and follows it from prediction to action, exploration, maps, habits and plans, and on to what dopamine does besides.
Credit over time and second-order conditioning; value as discounted future reward; the Bellman equation and the TD error derived (Sutton 1988), with Samuel's checkers and backgammon as history; a tapped delay line for time inside a trial; the error's migration from reward to cue, computed, and Steinberg et al.'s optogenetic unblocking; actor and critic, Q-learning and the softmax, the basal ganglia's Go and NoGo pathways and Frank et al.'s patients with Parkinson's disease; a reversal bandit played by Psyche, its learning rate read back by maximum likelihood and checked by parameter recovery; five exploration policies and their regret, and directed and random exploration in people; Tolman and Honzik's latent learning on a planner and a learner without a map, cognitive maps, place and grid cells; devaluation and habits, Daw et al.'s two-step task with its stay-probability signatures and the argument over what they mean; the successor representation, reward and transition revaluation, and replay; dopamine ramps, movement and salience signals, and a distributional code; Redish's model of a drug that cannot be predicted away. The practice chapter is recommender systems and bandit tests, impulse-control disorders on dopamine agonists, and habits; the frontier is learning to learn in prefrontal cortex.
What is computed and built
explainer/psychology/psyche/rl.py: TD(0) on a complete serial compound, with the error's migration and omission dip; second-order conditioning; Q-learning bandits with a softmax, their likelihood, a multi-start maximum-likelihood fit and win-stay/lose-shift; greedy, ε-greedy, softmax, UCB1 and Thompson sampling with regret; a maze in which a planner shows latent learning and a Q-learner does not; Daw's two-step task with model-free, model-based and hybrid agents and their stay probabilities; the successor matrix and reward and transition revaluation; a distributional population of expectile learners; Redish's drug model. Tested intests/psychology/test_rl.py.- The Ledger gains four rows; the Archive seventeen datasets.
- The course's interactive is a reversal bandit: eighty pulls on two machines paying 80% and 20%, which swap after pull 40, then the reader's learning rate and inverse temperature fitted by maximum likelihood on the page.
- The part's own simulations, in
compute.py: Steinberg's design under Rescorla-Wagner, Frank's selection task on an opponent Go/NoGo learner (after Collins and Frank 2014), and a bandit test against an even split.
Chapter notes
| # | Chapter | What it does |
|---|---|---|
| 0 | A neuron that fires at surprise | Schultz's three recordings, drawn on Psyche; the 1997 equation; the questions; objectives |
| 1 | Credit over time | The credit-assignment problem; Samuel's checkers; second-order conditioning |
| 2 | Temporal-difference learning | Value as discounted future reward; the Bellman equation; the TD error derived; a delay line |
| 3 | The error moves to the cue | The migration, computed; every feature from one line; optogenetic unblocking |
| 4 | From prediction to action | Actor and critic; Q-learning and the softmax; Go and NoGo; Parkinson's on and off medication |
| 5 | A bandit, and your learning rate | A reversal bandit; reading α and β back by likelihood; parameter recovery |
| 6 | Explore or exploit | The dilemma; five policies and their regret; directed and random exploration in people |
| 7 | Tolman's maps | Latent learning on Psyche; cognitive maps; place and grid cells |
| 8 | Habits and plans | Devaluation; the two-step task; three signatures; what the weight means |
| 9 | Between habit and plan | The successor representation; reward and transition revaluation; replay |
| 10 | Is dopamine only an error? | Ramps, movement and salience; a distributional code |
| 11 | When the signal is hijacked | Redish's model of a drug that cannot be predicted away |
| 12 | The Ledger | Dopamine errors; the two-step task; latent learning; grid cells |
| 13 | In practice: recommenders, medicine, habits | Bandits online; impulse-control disorders on agonists; habits |
| 14 | Frontier: learning to learn | What is solid and argued; Harlow's learning sets and meta-learning; open questions |
| Recap, problems, and the road ahead | Ten lines; the first two objections; payoffs; problems; references; Part 18 |
NotesWhere the numbers come from
| What | Source |
|---|---|
| Schultz's three recordings (unpredicted juice, a predicting cue, an omitted reward) | Schultz, Dayan and Montague (1997); drawn from Psyche's TD learner, not from his figures (item schultz: rates 5 + 30δ spikes/s, ten Poisson trials) |
| The TD error's migration over 120 trials; second-order conditioning | Psyche (rl.td_conditioning, rl.second_order; α = 0.2, γ = 0.98, 30 steps of 0.1 s, cue at step 5, juice at step 20), items schultz and migration |
| The TD error within one trial: the first, a trained one, a trained one with the juice omitted | Psyche (rl.td_conditioning, 150 trials), item cases |
| Bursts that scale with a cue's reward probability and size | later work from Schultz's laboratory, described without figures |
| Samuel's checkers (1959), Watkins's Q-learning (1989), TD-Gammon, DQN (2015), Bellman (1957), Sutton (1988), Barto, Sutton and Anderson (1983) | the usual history |
| Steinberg et al. (2013): optogenetic dopamine stimulation at reward unblocks learning; stimulation at other times does not | the abstract and commentaries; the four bars are Rescorla-Wagner on the design (α = 0.2, 100 pretraining trials, 40 compound trials, the light adding 0.5 to the error), item steinberg |
| Frank, Seeberger and O'Reilly (2004): off medication, better learning to avoid; on, better learning to choose | the abstract and later reviews; the bars are Psyche's opponent Go/NoGo learner after Collins and Frank (2014), 300 simulated people per dopamine level (ρ = −0.5, 0, 0.5), item frank: avoiding B falls from 0.74 to 0.66 as dopamine rises, while choosing A stays near 0.81. The learner gets the direction, not the whole pattern, and says so on screen |
| The reversal bandit: 80/20 then 20/80 at trial 100; α = 0.3, β = 5; win-stay 96%, lose-shift 40%; the fit (α 0.50, β 5.5) | Psyche (rl.q_learning_bandit, rl.fit_bandit), item bandit |
| Parameter recovery over 40 simulated players (α from 0.1 to 0.8, β from 2 to 10): r = 0.90 for α, 0.70 for β | Psyche, item bandit |
| Regret over 5,000 plays on machines paying 40, 45, 50 and 60% (100 runs): greedy 308, softmax 329, UCB1 162, ε-greedy 83, Thompson 40. Over 1,000 plays and 30 runs ε-greedy and Thompson were tied, so the longer run is shown | Psyche (rl.explore_regret), item explore |
| Wilson et al. (2014): directed and random exploration grow with the horizon | from memory and later reviews; the two curves are a logistic choice model with the bonus and noise set by hand (horizon 1: no bonus, σ = 4; horizon 6: a 6-point bonus, σ = 7) to show the direction, not fitted |
| Tolman's shortcut, the dopamine signals beyond the error, place-cell replay | schematics, labelled on screen as not data |
| Tolman and Honzik (1930): three groups; food from day 11; the late group's jump | textbook accounts and a review of the design |
| The maze on Psyche: a planner and a learner without a map, medians of 40 runs | Psyche (rl.latent_learning), item maze |
| Place cells (1971), grid cells (2005), the Nobel Prize (2014), grid-like signals in people (2010) | O'Keefe and Dostrovsky; Hafting et al.; Doeller, Barry and Burgess |
| Devaluation after moderate and extensive training | Adams and Dickinson (1981); Adams (1982), from reviews |
| The two-step task: 70/30 transitions, drifting payoffs; 17 participants | Daw et al. (2011); stay probabilities from Psyche (rl.two_step, 30 runs of 400 trials), item twostep |
| The mixture weight lower with compulsive symptoms, stress and load; model-free mimicry; careful instructions | Gillan et al. (2016), Otto et al. (2013), Akam et al. (2015), Feher da Silva and Hare (2020), from memory |
| Reward and transition revaluation for three learners | Psyche (rl.revaluation), item successor; Momennejad et al. (2017) for people |
| Replay during sleep (1994), forward and backward replay, prioritized replay | Wilson and McNaughton (1994); Foster and Wilson (2006); Pfeiffer and Foster (2013); Mattar and Daw (2018), from memory |
| Dopamine ramps; movement and salience signals | Howe et al. (2013); Howe and Dombeck (2016); Bromberg-Martin et al. (2010), from memory |
| A distributional code in mouse dopamine neurons | Dabney et al. (2020); Psyche's thirteen expectile learners, item distrib |
| Redish's model, with a drug surge of 0.5 | Redish (2004); Psyche (rl.redish), item redish |
| Yahoo!'s front-page contextual bandit | Li et al. (2010) |
| A bandit test: versions clicked 5% and 6%, 20,000 visitors, Thompson sampling against an even split (1,172 clicks against 1,100), 50 runs | Psyche, item abtest |
| 3,090 patients; 13.6% with an impulse-control disorder; 17.1% on agonists against 6.9% on levodopa (drawn as bars) | Weintraub et al. (2010), from the record and secondary summaries |
| Harlow's learning sets (1949); meta-reinforcement learning in prefrontal cortex | Harlow (1949); Wang et al. (2018) |
Notes
| Finding | Original | Status |
|---|---|---|
| Dopamine neurons signal reward prediction errors | Schultz, Dayan and Montague 1997 | replicated |
| The two-step task shows model-free and model-based signatures | Daw, Gershman, Seymour, Dayan and Dolan 2011 | replicated |
| Rats learn a maze without reward and show it when food appears | Tolman and Honzik 1930 | replicated |
| Entorhinal grid cells fire on a triangular lattice | Hafting, Fyhn, Molden, Moser and Moser 2005 | replicated |
The first row's note records that the error's scope is argued; the second's that the reading of the mixture weight is
contested. Shown without a row, with the reason recorded in explainer/psychology/ledger.py: Frank et al. (one study,
described, with Psyche's learner beside it), Wilson et al. (described), Tolman (1948, history), Adams and Dickinson (devaluation; its row is due in Part
28), Momennejad et al. (described with its partial result), Howe et al. and Dabney et al. (frontier), Redish (a model;
addiction's row is due in Part 41), Li et al. (an application), Weintraub et al. (a survey's rates) and Wang et al. (a
model).
Notes
Before the narrated master:
- Schultz's recordings are drawn from Psyche, not reproduced; the probability and magnitude scaling are described without figures.
- TD-Gammon's level and DQN's dozens of games are the usual history.
- Frank et al. (2004) and the later debate are from abstracts and reviews.
- Wilson et al.'s horizons and the claim about children are from memory.
- Tolman and Honzik's group sizes and error counts are not given; the comparison is as textbooks report it.
- Adams and Dickinson's procedures (devaluation by sickness or satiety) and Adams (1982) on overtraining are from reviews.
- Gillan et al. (2016), Otto et al. (2013) and Akam et al. (2015) are cited from memory.
- Replay results (1994, 2006, 2013, 2018) and the dopamine movement and salience results are from memory.
- Weintraub et al.'s percentages are from secondary summaries of the paper.
- Kim et al. (2020), cited in problem 7, is from memory.
Companion material in this repository
The syllabus's plan for this partfrom SYLLABUS.md, the plan of record
- Hook: Schultz's three recordings drawn on Psyche's TD learner (rasters and rates, not his figures); the 1997 equation; the questions; objectives.
- Credit over time: the problem Rescorla–Wagner cannot solve; Samuel's checkers; second-order conditioning on Psyche.
- Temporal-difference learning: value as discounted future reward; the Bellman equation; the TD error derived (Sutton 1988); TD-Gammon and AI, Built Part 26; a tapped delay line.
- The error moves to the cue: the migration over 120 trials, computed; the error within one trial (first, trained, omitted) beside each case of the equation; probability and size scaling; Steinberg et al. (2013) as four bars from Rescorla–Wagner with the light added to the error.
- From prediction to action: actor and critic; Q-learning and the softmax (Watkins 1989; DQN 2015); Go and NoGo; Frank, Seeberger and O'Reilly (2004), with Psyche's opponent learner, which reproduces the avoid-B side only.
- A bandit, and your learning rate: a reversal bandit; α and β read back by likelihood (α 0.50 against a true 0.3); parameter recovery over 40 players (r = 0.90 for α, 0.70 for β).
- Explore or exploit: five policies over 5,000 plays (Thompson 40, ε-greedy 83, UCB1 162, greedy 308); directed and random exploration with the horizon (Wilson et al. 2014), as a hand-set choice model.
- Tolman's maps: latent learning on Psyche's planner against a learner without a map; cognitive maps and a shortcut; place cells (O'Keefe 1971) and grid cells (Hafting et al. 2005).
- Habits and plans: devaluation after moderate and extensive training (Adams and Dickinson 1981); the two-step task (Daw et al. 2011) with three agents' stay probabilities; what the mixture weight means (Feher da Silva and Hare 2020).
- Between habit and plan: the successor representation, M = (I − γT)⁻¹; reward and transition revaluation for three learners (Momennejad et al. 2017); replay, forward and backward.
- Is dopamine only an error? Ramps (Howe et al. 2013), movement and salience; a distributional code of expectile learners (Dabney et al. 2020).
- When the signal is hijacked: Redish (2004), a drug that cannot be predicted away; continued in Part 41.
- The Ledger. 13. In practice: contextual bandits (Li et al. 2010) and a bandit test against an even split; impulse-control disorders on dopamine agonists (Weintraub et al. 2010: 13.6%, 17.1% against 6.9%); habits by design. 14. Frontier: what is solid and argued; Harlow's learning sets and meta-reinforcement learning (Wang et al. 2018); open questions.
Psyche: rl: TD(0) with a complete serial compound and second-order conditioning; Q-learning bandits, their
likelihood and fit; five exploration policies with regret; a maze with a planner and a model-free learner; the two-step
task with model-free, model-based and hybrid agents; the successor matrix and both revaluations; distributional TD;
Redish's model.
On you: two slot machines: eighty pulls, a swap after forty, and your α and β fitted on the page.
Ledger: dopamine reward-prediction errors (replicated; scope argued); the two-step model-based signature
(replicated; the weight's meaning contested); latent learning (replicated); grid cells (replicated). Shown
without rows, with reasons: Frank et al., Wilson et al., Tolman (1948), Adams and Dickinson (row due in Part 28),
Momennejad et al., Howe et al., Dabney et al., Redish (row due in Part 41), Li et al., Weintraub et al., Wang et al.
In practice: recommender systems and bandit tests are this mathematics; impulse-control disorders on agonists;
habits, made and broken.
Frontier: what dopamine ramps mean; whether humans are ever purely model-free; meta-reinforcement learning in
prefrontal cortex (Part 58).
Reading: Schultz, Dayan & Montague 1997; Sutton & Barto, Reinforcement Learning (ch. 14–15 on psychology and
neuroscience); Tolman 1948; Daw et al. 2011; Niv 2009; Dabney et al. 2020; Dayan & Daw 2008.
Build the film
python -m videos.psychology.psych17.compute # the part's numbers, into .cache/psych17
python tools/build.py psych17 # render and assemble the film
EXPLAINER_TTS=silent python tools/qa_scene.py psych17 Hook # one chapter, silent, with a contact sheet
Scenes: videos/psychology/psych17. Setup: see the course page. Source of these notes: the README and the scenes' narration.
Build it
python -m videos.psychology.psych17.compute # every number (about a minute), into .cache/psych17/
python tools/qa_scene.py psych17 Dopamine # one chapter, silent, at 480p, with a contact sheet
EXPLAINER_TTS=silent python tools/build.py psych17 -q l # the whole part, silent preview
python tools/build.py psych17 # 1080p30 with narration
python tools/qa_scene.py psych17 Controllers --lang zh # the Chinese edition of one chapter
python tools/make.py psych17 # both editions, with the checks a long build needs
python -m videos.psychology.labs 17 # the lab: TD, bandits, exploration, two steps, maps
python tools/check_ledger.py psych17 # every study shown has its Ledger row, or a reason
python -m pytest tests/psychology # Psyche's rl 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.