ΨPsychology, Built

Act XI · The Graduate Toolkit

Part 48 of 62

Modelling Behaviour

Graduatestarts at this level28 min of film17 chaptersprerequisites: Part 17, Part 25, Part 47

When is a computational model of the mind more than a curve fit?

In 1956 William Estes showed that a smooth learning curve can be the average of learners who each learned in one jump. The part opens the fitting harness the whole series has used: four generative models of a reversal bandit, maximum likelihood with restarts, parameter recovery and the ridge where learning rate and inverse temperature trade off, model comparison and model recovery, a posterior predictive check that catches a missing mechanism, people fitted as a population, and the power law of practice unmasked as an average; then rational analysis, connectionism and language models given the Battery.

What you need. Part 17's Q-learner and Part 25's diffusion model; likelihood, AIC and BIC, and shrinkage.

Hook
learning curves that no one has
Ideas, models and mathematics
likelihoods for behaviour, fitting, parameter and model recovery, model comparison, hierarchical Bayes, falsification by simulation, rational and resource-rational analysis, networks and language models as cognitive models
Psyche gains
psyche.fit: the modelling harness
On you
fit a model to your own bandit data

What you will be able to do

Psych 101 and the major

  • Explain what a cognitive model is: a program that turns parameters into trial-by-trial behaviour.
  • Explain why an average curve can misdescribe every individual in it.

Graduate

  • Fit a learning model by maximum likelihood with several starting points, and show parameter recovery for the number of trials collected.
  • Compare models by BIC or cross-validation, and check the comparison by model recovery.
  • Run a posterior predictive check on a qualitative effect such as staying after a loss.

Research

  • Design the full set of checks for a new model of a new task before collecting data.

Practice

  • Judge whether a parameter fitted to users or patients is reliable enough to act on.

Contents

Each chapter has a home level. Choose a track to see what to read and watch: Psych 101 and the major 10 min · Graduate 27 min · Research 28 min · Practice 11 min.

  1. 0A curve no animal hadPsych 101 and the major2 min
  2. 1On you: your learning rate, and four numbersPsych 101 and the major1 min
  3. 2What a cognitive model isPsych 101 and the major2 min
  4. 3FittingGraduate2 min
  5. 4Parameter recoveryGraduate1 min
  6. 5Parameters that trade offGraduate1 min
  7. 6Model comparisonGraduate2 min
  8. 7A good fit can be badGraduate2 min
  9. 8People as a populationGraduate1 min
  10. 9A law that was an averagePsych 101 and the major1 min
  11. 10Rational and resource-rationalGraduate2 min
  12. 11ConnectionismGraduate2 min
  13. 12Language models as models of mindsGraduate2 min
  14. 13The LedgerGraduate1 min
  15. 14In practice: phenotypes, users and tutorsPractice2 min
  16. 15Frontier: amortized inference and discovered modelsResearch1 min
  17. 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 curve no animal hadPsych 101 and the major2 min

In 1956 the psychologist William Estes asked what a smooth learning curve means. Here are some of Psyche's learners. Each jumps from guessing to knowing on a single trial, so every curve is a step. Average two hundred of them, and a smooth, gradual curve appears. It's the shape of no learner at all. A model fitted to that average would describe a mind that doesn't exist. This part is the craft of not fooling yourself with models.

The series has fitted models all along. Part 17 fitted learning rates. Part 25 fitted diffusion models, and Part 40 a model of mood. Each time, a program that turns parameters into behaviour, and a search for the parameters that make the data most likely. This part opens that harness. Can the parameters be recovered? Can the models be told apart? Does the winner reproduce the data's signature? A model is more than a curve fit when it could have failed, and didn't.

So this part asks when a computational model of the mind is more than a curve fit. Generative models, likelihoods and fitting. Recovery, trade-offs and model comparison. Posterior prediction, hierarchy, and the danger of averages. And rational analysis, neural networks, and language models offered as models of minds.

This is Part 48 of Psychology, Built: modelling behaviour. We'll treat a cognitive model as a program that generates behaviour. We'll fit it by maximum likelihood, with restarts, and meet the traps. We'll check whether parameters can be recovered, and see two that trade off. We'll compare models, and check that comparison can tell them apart. We'll ask whether a winning model reproduces the data, and fit people as a population. And we'll see averages that describe no one, then neural networks and language models offered as models of minds.

What it does: Estes's jumping learners; every part has fitted models; the question; objectives

1On you: your learning rate, and four numbersPsych 101 and the major1 min

First, Part 17's bandit again. Psyche plays two arms; one pays seventy percent of the time, and halfway through they swap. Each dot is a choice, green when it paid. Fit the Q-learner, and the learning rate comes out at about zero point four, with an inverse temperature near five. The truth was zero point three and five. On the course site you can play it yourself, see your own learning rate fitted, and beside it how well a rate like yours can be recovered from two hundred choices.

Now four numbers. One: a learner's true learning rate is zero point four. From two hundred choices, how close will a fit come, typically? Two: data from a learner who also tends to repeat choices. How often does model comparison pick the right model? Three: each of sixty people improves exponentially with practice. What curve fits their average best? And four: thirty people, sixty trials each. By how much does fitting them as a population cut the error in each person's learning rate? Pause here, and write them down.

What it does: Four predictions

2What a cognitive model isPsych 101 and the major2 min

What is a cognitive model? A program that generates behaviour: parameters in, choices out, trial by trial. Here's Part 17's learner in eight lines. Run forward, it simulates people. Run backward, its likelihood says how probable each observed choice was. The likelihood of the data is the product, over trials, of the probability the model gave to what the person actually did. Robert Wilson and Anne Collins wrote ten simple rules for this craft in 2019. The first is: simulate before you fit.

Here are four models of the same bandit. A biased coin, with one parameter. Win-stay, lose-shift, with some noise. The Q-learner, with a learning rate and an inverse temperature. And the Q-learner with perseveration, a pull toward repeating the last choice. Each is a hypothesis about how the choices were made. The rest of this part asks how to tell them apart, and how far to trust the winner.

Before fitting anything, simulate. Run each model and look at what it does: forty simulated players each. A simple signature is how often a player repeats a choice after a win, and after a loss. Win-stay lose-shift almost never stays after a loss. Q-learning stays about three times in five, and with perseveration added, nearly nine times in ten. The models disagree where it can be seen, and that's what makes them testable. Simulating first is among Wilson and Collins's ten rules for a reason.

What it does: A program that makes behaviour; four models of one task; simulate before you fit

3FittingGraduate2 min

Fitting is a search. For each model, find the parameters that make Psyche's two hundred choices most likely. The Bayesian information criterion adds a penalty for every parameter, so an extra parameter must earn its place. The Q-learner wins. Adding perseveration fits a little better, but not enough to pay for itself. And a win is relative. The best of four models may still be wrong.

Four traps in the search. Local optima: the likelihood surface can have several peaks, so start from several places and keep the best. Bounds: a learning rate must lie between zero and one, and an estimate that lands on a bound is a warning. No likelihood: some models can only be simulated. Then fit by comparing simulated and real summaries, or train a network to invert the simulator. And too few trials: a few dozen choices may barely constrain two parameters. That's the next two chapters.

Here's why restarts matter. Psyche makes a slow, decisive learner who tends to repeat choices, and fits the three-parameter model to eighty trials, from forty random starting points. Seven in ten end at the best fit: a very low learning rate and a high inverse temperature. The rest stop three log-likelihood units short, at a different story: a faster learner who chooses more randomly and perseverates more. One start can land anywhere. Use many, keep the best, and report how many agreed.

What it does: Maximum likelihood and a scorecard; traps in the search; two answers from one learner

4Parameter recoveryGraduate1 min

The first check on any model. Choose true parameters across a grid. Simulate two hundred choices from each, fit, and plot what the fit found against the truth. The learning rate is recovered well. The inverse temperature less so, and worst when it's high, because a nearly deterministic chooser gives little information about how deterministic it is. If a parameter can't be recovered from simulated data, its value in real data means nothing. Every modelling paper should show this plot, for its own task and its own number of trials.

So how many trials does a fit need? Run the same recovery study at fifty, a hundred, two hundred and four hundred trials per learner. At fifty trials, the fitted learning rate correlates only about zero point six with the truth, and the inverse temperature less. At four hundred, both are above zero point nine. The number of trials is a design decision, made by recovery before the data are collected, just like power.

What it does: Simulate, fit, compare; how many trials?

5Parameters that trade offGraduate1 min

Why is one parameter recovered better than another? Look at the whole likelihood. Here is the log-likelihood of Psyche's two hundred choices at every combination of learning rate and inverse temperature. Bright is likely. The bright region is a curved ridge, not a peak. A lower learning rate with a higher temperature explains the data almost as well. The two trade off: fast learning with noisy choice, or slower learning with sharper choice. So a difference between groups in one parameter can really be a difference in the other. Compare people on both, or pin one down by design.

The ridge shows up in repeated fits too. Take one learner, simulate it forty times, and fit it each time. The two estimates are negatively correlated: when one comes out high, the other tends to come out low. A fast learner who chooses noisily and a slow one who chooses sharply produce similar choices. So report the two together, compare people on what's well determined, or design tasks, with more reversals, that pull them apart.

What it does: The likelihood surface and its ridge; the ridge in repeated fits

6Model comparisonGraduate2 min

How to choose among models. For nested models, a likelihood ratio test. AIC and BIC penalize each parameter, AIC for the sake of prediction, BIC for finding the true model if it's among the candidates. Cross-validation fits on some trials or people and predicts the rest, the most direct test of generalization. Bayes factors weigh the evidence for each model averaged over its prior: honest about flexibility, sensitive to the prior. And over a group: different people may use different models, so estimate how common each model is, not just which wins on the pooled data.

And the comparison itself must be checked. Psyche simulates learners from each of the four models, fits all four to every dataset, and picks by BIC. The diagonal is recovery; off it, confusion. Here recovery is good: more than nine in ten of each model's learners are identified. A few perseverating learners still look like plain Q-learners, because their pull is too weak for two hundred choices to pay for a third parameter. With fewer trials, or more similar models, the matrix blurs. So a model that wins on real data must be checked the same way, for its own task and trial count. Could the comparison have found the alternatives?

Another way to compare: predict data the model hasn't seen. Thirty perseverating learners each play two sessions. Every model is fitted to the first and scored on the second. Held-out prediction rewards a model only for what generalizes, so extra parameters that fit noise are punished automatically. The true model predicts the new session best, and BIC on the first session chose it for more than nine learners in ten. When the two disagree, trust the one that answers the question you're asking: prediction, or which model is true.

What it does: Four ways to compare; model recovery; predict the next session

7A good fit can be badGraduate2 min

A model that fits well isn't therefore a good model. In 2000 Seth Roberts and Harold Pashler argued that a fit is persuasive only if the model could have failed. Ask what data the model can't produce. A model that fits every possible outcome explains none of them. Ask how variable the data are. A fit inside the noise says little. Ask whether a plausible alternative fits as well. And the strongest evidence is a prediction made before the data, of an effect the model must produce.

Roberts and Pashler's question can be drawn. Take sixty random parameter settings for each model, and simulate. Each dot is one possible player, placed by how often it stays after a loss and after a win. Win-stay lose-shift lives in one corner. It can never stay after a loss more than its error rate allows. Q-learning covers a band, and with perseveration added, almost the whole square. A model that can produce anything isn't confirmed by producing this. Ask what it rules out.

Here's the check in practice. Psyche's learners have a pull toward repeating themselves. Fit both models, then simulate new data from each fit. After a loss, the learners stay with the same arm about eighty-five percent of the time. The plain Q-learner's simulations stay only seventy percent. Whatever its score, it can't make the effect. With perseveration, the simulations match. Stefano Palminteri, Valentin Wyart and Etienne Koechlin made this the rule in 2017: check that the winning model produces the data's signature, not only that it scores best.

What it does: Roberts and Pashler; what each model can produce; does the model make the effect?

8People as a populationGraduate1 min

Real studies rarely give each person two hundred trials. Psyche makes thirty people, sixty trials each, whose learning rates differ around a population average. Fitted alone, each estimate is noisy, and some run off to the bounds. Fitted as draws from a population, each estimate is pulled toward the group, more when it's uncertain. The error falls by almost half. A full Bayesian hierarchy does the same for every parameter at once, and estimates how much people really differ, as Michael Lee and Eric-Jan Wagenmakers teach.

When does fitting people as a population pay? Forty people, four simulated groups at each length. With thirty trials each, fitting people alone misses by about one unit on the logit scale. As a population, about half that. With two hundred and forty trials, the two are close: each person's data speak for themselves. Pooling helps most where data are fewest: short tasks, patients, and children.

What it does: Hierarchical fitting and shrinkage; when pooling pays

9A law that was an averagePsych 101 and the major1 min

Estes's warning has a famous case. In 1981 Allen Newell and Paul Rosenbloom showed that across many skills, practice curves follow a power law. It became the law of practice. Psyche's sixty learners each speed up exponentially, at very different rates, and an exponential fits almost all of them better than a power law. But their average is better fitted by a power law. Andrew Heathcote, Scott Brown and Douglas Mewhort fitted real practice data person by person in 2000, and found the exponential favoured. The law described the average, not the learner.

How many learners does it take to make a law? Average k of Psyche's exponential learners, sixty times for each k, and ask which curve fits the average better. With one learner, the power law wins only about one time in twelve, by noise. With thirty learners it wins eighty-eight percent of the time. Averaging different rates manufactures the power law. That's the lesson of Part 47 and of this part: fit the person, then describe the population, never the reverse.

What it does: The power law of practice

10Rational and resource-rationalGraduate2 min

Fitting asks how; another tradition asks why. John Anderson's rational analysis starts from the goal the mind is trying to achieve, describes the environment it works in, with its statistics, makes minimal assumptions about its limits, derives the optimal behaviour, and compares it with people. If they differ, revise the goal, the environment or the limits, not the optimality. With Lael Schooler, in 1991, Anderson showed that memory's forgetting curve matches how often information is needed again in the world. It's Marr's computational level, made a method.

Real minds have limits. People aren't optimal for the problem; they may be optimal for the problem plus their limits. Falk Lieder and Tom Griffiths call this resource-rational analysis: thinking itself is costly, so ask for the best use of a limited budget. Heuristics and biases, from Part 24, become sensible strategies for a mind that can't compute everything. The danger: with enough freedom to choose the costs, any behaviour can be called rational. The costs must be measured, not chosen to fit.

Resource-rational analysis can be computed. Choose between two options by sampling evidence about their difference, each sample weak. Accuracy rises with samples, but more and more slowly. Now charge for each sample. The best number falls fast: about thirty-six samples when thinking is cheap, and five when it costs ten times as much. A mind that decides on a few samples may be using its time well. That's the resource-rational reading of deciding on one or two samples, which is what people often seem to do.

What it does: Anderson's rational analysis; optimal use of limited computation; how long to think

11ConnectionismGraduate2 min

A different kind of model came with the 1980s. In 1986 David Rumelhart, James McClelland and the PDP group modelled cognition as many simple units, with knowledge stored in the weights between them, learned from examples. What networks added: graded, learned representations, rules that emerge without being written, and damage that degrades gracefully. What they cost: a fitted network can be as hard to understand as the mind it models, and learning something new can erase the old, Part 21's catastrophic interference. The debate over rules and networks, starting with the English past tense, ran for decades. Today's language models are its heirs.

So what is a network model tested against? The past tense. Rumelhart and McClelland's network learned English past tenses with a dip, saying goed after it had said went, as children do. Steven Pinker and Alan Prince argued that the dip came from how the training was staged. Reading aloud. Mark Seidenberg and McClelland's triangle model read regular and irregular words with one set of weights, and predicted their naming times. Damage. Lesioned networks lose specific knowledge first and general knowledge last, as people with semantic dementia do. The standard is the same as for any model in this part. A network earns its place by predicting the pattern of errors and times, not by being accurate.

What it does: Parallel distributed processing: what it added and what it cost

12Language models as models of mindsGraduate2 min

A new kind of candidate model. A language model can be given a psychology experiment as text, and its answers scored like a participant's. In 2023 Marcel Binz and Eric Schulz gave classic judgment tasks to such a model. On some it answered much like people, biases included, and it failed in other places. Later, models fine-tuned on trial-level data from many experiments were offered as general models of human choice, predicting held-out participants well. The same checks apply as to any model: recovery, comparison against simple models, and whether it produces the effects for the right reasons.

How should a language model be tested as a model of mind? Watch for contamination. Classic tasks are on the web, and a model may have read the answers, so use new items and new stories. Test process. Do its errors, and the difficulty it finds in each item, match people's? Surprisal predicting reading times, from Part 23, is one such test. Remember it's people, not a person. A model's answers form a distribution that isn't one person's, so compare it with the spread across people, not just the mean. And beat the baseline: the simple fitted model of each task, before claiming more.

Which raises an old question in a new form. For prediction: if a model predicts what people do in new situations, it has learned something real about behaviour. Against: a model as complex as the mind leaves the explaining still to do. We understand it no better than the people it imitates. A middle way: use the large model as a benchmark. How much of the predictable behaviour does a small, interpretable model capture? Part 60 asks what such systems are, and Part 61 what they change about the science.

What it does: Giving a model the Battery; prediction against explanation

13The LedgerGraduate1 min

What the two have in common. Both are claims about individuals made from fits. The first fitted an average and called it a learner. The second fitted learners and called the fit a trait. Both were caught by the checks of this part: fit person by person, and test recovery and reliability before interpreting a parameter. A parameter is a measurement, and Part 3's questions apply to it.

What it does: Two rows; what they have in common

14In practice: phenotypes, users and tutorsPractice2 min

Where fitted models of behaviour run. Computational phenotyping fits task models to patients, to describe what differs. Recovery and reliability come first, as Part 59 will show. User modelling fits learning and exploration to how people use a product, with the same trade-offs between parameters. Simulated users test a design before real ones: cheap, and only as good as the model's recovery and predictions. Tutoring systems run Part 45's knowledge tracing, a fitted model of each learner updated after every answer. And one checklist for all of them: simulate, recover, compare, check predictions, fit hierarchically, and never fit an average and call it a person.

Here's a computational phenotype, worked. A clinic wants to know whether patients with anxiety learn from losses differently. It uses a bandit task, two hundred choices each. First, simulate the task with the candidate models, and check that the learning rate for losses is recoverable from two hundred choices. Fit hierarchically, compare models by cross-validation, and check that the winner reproduces stay-after-loss. Then test the group difference on the parameter, with its uncertainty, preregistered, and retest some patients to see whether the parameter is stable. A parameter that isn't recoverable, or isn't stable, isn't a phenotype, however good the story.

What it does: Where fitted models run

15Frontier: amortized inference and discovered modelsResearch1 min

Three frontiers. Amortized inference trains a network once, on millions of simulations, to map data to parameters. Then fitting a new person is instant, even for models without a likelihood. Model discovery searches over programs, or lets a network propose equations, for the model that best predicts held-out people, and then checks it's still interpretable. And a foundation model of behaviour. To count as a model of the mind, it would need to predict new tasks, reproduce the classic effects for the right reasons, and be checked like any other model.

Open questions. How many trials does a parameter need before it can be a trait? Can a model be both a strong predictor and an explanation? How should model comparison work when every candidate is wrong? And what would a discovered model have to show to be believed?

What it does: Three frontiers; open questions

Recap, problems, and the road aheadAll tracks3 min

First, your four numbers. A learning rate of zero point four, from two hundred choices, is typically recovered within a few hundredths. Model comparison identified more than nine in ten perseverating learners. The average of exponential learners is best fitted by a power law. And fitting thirty people as a population cut the error in each learning rate by almost half. A model earns trust by the checks it passes, not by its fit.

Part forty-eight in twelve lines. An average can describe no one. A cognitive model is a program from parameters to behaviour, fitted by maximum likelihood with restarts and bounds. Recover parameters from simulations before trusting them, and watch for parameters that trade off along a ridge. Compare models by penalized fit or by prediction, and check that the comparison can recover the true model. A good fit can be bad, so ask what the model rules out, and whether it makes the effect. Hierarchical fits borrow strength across people. Rational analysis asks why, networks ask how. And prediction is not yet explanation.

Kant's wager. The first objection met likelihoods, recovery, model comparison and hierarchy, all run in the open. Green. The second met models tested by the effects they must produce, on data they didn't see. Green. And the third, about introspection: these are models of choices, not of reports, so the objection doesn't arise. Green.

Where this comes back. Models of the brain's data are next, in Part 49. The weight of evidence across studies is Part 50. Computational psychiatry, with recovery first, is Part 59. And language models as minds are Part 60.

Seven problems, with full solutions in this part's README. One computes a softmax choice. One updates a value. One computes a log-likelihood. One compares two models by BIC. One averages jumping learners. One shrinks a learning rate. And the last, with the star, asks you to plan every check for a new model of a new task. Pause here if you'd like to try them.

The books and papers behind this part are listed here and in the README. Farrell and Lewandowsky's book teaches the craft; Lee and Wagenmakers teach the Bayesian version; and Wilson and Collins's ten rules fit on a page and should be read before any fit.

Five parts of the graduate toolkit done. This one opened the fitting harness the whole series has used. Next, the brain. Seventy teams were given one brain-imaging dataset and reached different answers. What must be true for a brain map to be evidence? Part 49: modelling the brain's data.

Where it goes next. The brain's data, with subjects and voxels, are Part 49; the weight of evidence Part 50; computational psychiatry and its parameters Part 59; whether a language model is a model of a mind Part 60.

Key results

The part's results in one place, for revision.

Softmax choice\(\displaystyle P(a) = e^{\beta Q_a} / \sum_b e^{\beta Q_b}\)
Q-learning\(\displaystyle Q_a \leftarrow Q_a + \alpha (r - Q_a)\)
BIC\(\displaystyle \mathrm{BIC} = -2 \ln \hat L + k \ln n\)
Shrinkage\(\displaystyle \hat\theta_p = \frac{\hat\theta_p^{\text{own}} / v_p + \mu / \tau^2}{1 / v_p + 1 / \tau^2}\)

Try it

Lab 48 · Modelling Behaviour

Simulate learners, fit four models to their choices, check that the fits recover what was planted, and check that the winning model makes the effect it should.

Figure produced by Lab 48: Modelling Behaviour
Produced by the lab below, seed 0, in 8.1 s.
python -m videos.psychology.labs 48 needs numpy, scipy, matplotlib · download lab48.py · source on GitHub
jumping learners: average correct on trials 1, 5, 20                0.18, 0.47, 0.90
BIC: random; win-stay lose-shift; Q; Q with perseveration           282.1; 260.9; 204.2; 207.9
Q-learner fitted (planted 0.3, 5)                                   alpha 0.21, beta 6.44
recovery: correlation of true and fitted alpha; beta                0.95; 0.83
stay after a loss: data; Q predicts; Q with perseveration predicts  0.86; 0.74; 0.83
learning rates (logit): RMSE alone; shrunk                          0.67; 0.54

A smooth average can hide steps; a fit is only as good as its recovery; and the model that wins on BIC must still make the effect the data show.
The code (56 lines; it asserts its own result)
"""Lab 48: modelling behaviour: jumping learners and their average, four models of a reversal bandit fitted by
maximum likelihood, parameter and model recovery, a posterior predictive check, and shrinkage across people."""

import numpy as np

from videos.coursekit import labs
from explainer.psychology.psyche import fit as F

TITLE = "Modelling Behaviour"
GOAL = ("Simulate learners, fit four models to their choices, check that the fits recover what was planted, and "
        "check that the winning model makes the effect it should.")
TASKS = [
    "Cut the trials from 200 to 60. How far do the recovered learning rates spread?",
    "Simulate a learner with negative perseveration (kappa = -1.5). Does the posterior predictive check still work?",
    "Give the group 200 trials each. How much does shrinkage still help?",
]


def run(seed=0):
    out = labs.Lab()
    j = F.jump_learners(seed=seed + 1)
    out.row("jumping learners: average correct on trials 1, 5, 20", ", ".join(f"{j['mean'][t - 1]:.2f}" for t in (1, 5, 20)))
    C, R = F.simulate("q", (0.3, 5.0), seed=seed + 2)
    fits = {m: F.fit(m, C, R) for m in F.MODELS}
    best = min(fits, key=lambda m: fits[m]["bic"])
    assert best in ("q", "q_persev")
    out.row("BIC: random; win-stay lose-shift; Q; Q with perseveration",
            "; ".join(f"{fits[m]['bic']:.1f}" for m in F.MODELS))
    out.row("Q-learner fitted (planted 0.3, 5)", f"alpha {fits['q']['params'][0]:.2f}, beta {fits['q']['params'][1]:.2f}")
    rec = F.recovery([0.2, 0.5, 0.8], [2.0, 5.0, 10.0], reps=2, seed=seed + 3)
    assert rec["r_alpha"] > 0.5
    out.row("recovery: correlation of true and fitted alpha; beta", f"{rec['r_alpha']:.2f}; {rec['r_beta']:.2f}")
    a = F.posterior_predictive("q_persev", (0.3, 5.0, 1.5), "q", n=10, seed=seed + 4)
    b = F.posterior_predictive("q_persev", (0.3, 5.0, 1.5), "q_persev", n=10, seed=seed + 4)
    out.row("stay after a loss: data; Q predicts; Q with perseveration predicts",
            f"{a['obs'][1]:.2f}; {a['pred'][1]:.2f}; {b['pred'][1]:.2f}")
    g = F.group_fit(n_people=20, seed=seed + 5)
    out.row("learning rates (logit): RMSE alone; shrunk", f"{g['rmse_ml']:.2f}; {g['rmse_eb']:.2f}")

    out.note = ("A smooth average can hide steps; a fit is only as good as its recovery; and the model that wins on "
                "BIC must still make the effect the data show.")

    fig, ax = labs.figure(2, size=(11, 4.0))
    for row in j["each"][:6]:
        ax[0].step(j["t"], row, where="post", lw=1, alpha=0.6)
    ax[0].plot(j["t"], j["mean"], color="k", lw=2.5)
    ax[0].set(title="each learner jumps; the average glides", xlabel="trial", ylabel="P(correct)")
    ax[1].scatter(rec["true_alpha"], rec["est_alpha"], color=labs.BLUE)
    ax[1].plot([0, 1], [0, 1], color="grey", ls=":")
    ax[1].set(title="parameter recovery", xlabel="true alpha", ylabel="fitted alpha")
    out.fig = fig
    return out


if __name__ == "__main__":
    print(run())

Now change it

  1. Cut the trials from 200 to 60. How far do the recovered learning rates spread?
  2. Simulate a learner with negative perseveration (kappa = -1.5). Does the posterior predictive check still work?
  3. Give the group 200 trials each. How much does shrinkage still help?

Problems, with solutions

Try each problem before opening its solution.

  1. Softmax. A softmax chooser with \(\beta = 5\) values two arms at 0.6 and 0.4. Find the probability of choosing the first.

    Solution

    1/(1 + e^(-5 × 0.2)) = 1/(1 + e^(-1)) = 0.73.

  2. A Q-learning update. A Q-learner with \(\alpha = 0.3\) values an arm at 0.5, chooses it, and is rewarded. Find the new value.

    Solution

    0.5 + 0.3 × (1 - 0.5) = 0.65.

  3. A log-likelihood. A model gave a person's three choices probabilities 0.7, 0.6 and 0.8. Find the log-likelihood.

    Solution

    ln 0.7 + ln 0.6 + ln 0.8 = -0.357 - 0.511 - 0.223 = -1.09.

  4. BIC. Two models of 200 choices: log-likelihood \(-60\) with 2 parameters, \(-58\) with 3. Which does BIC prefer?

    Solution

    With n = 200, ln n = 5.30: 120 + 2 × 5.30 = 130.6 against 116 + 3 × 5.30 = 131.9; BIC prefers the two-parameter model, by a hair.

  5. Jumping learners. Learners jump from 10% to 90% correct with probability 0.1 per trial. What does the average curve show on trial 10?

    Solution

    If a learner can jump after each of the first nine trials, 1 - 0.9⁹ = 0.61 have jumped by trial 10, so the average is 0.1 + 0.8 × 0.61 = 0.59: a value no learner shows, since each is at 0.1 or 0.9.

  6. Shrinkage. A person's log-odds learning rate is \(-1.5\) with variance 0.5; the population's mean is \(-0.7\) with variance 0.25. Find the hierarchical estimate.

    Solution

    Weight the two by their precisions, 2 and 4: (2 × (-1.5) + 4 × (-0.7))/6 = -0.97.

  7. ★ A plan. Plan the checks for a new model of a new task: simulations, recovery, model recovery, a posterior predictive check, and the number of trials.

    Solution

    Simulate the model across its plausible parameters and check it produces the effects it is meant to; fit simulated data and show recovery for the number of trials you will collect; simulate from every candidate model and show the confusion matrix; after fitting, simulate from the winner and compare its stay-after-win and stay-after-loss (or the task's key effect) with the data; fix the trial count by recovery, not by habit.

Notes and sources

Sources

  • W. K. Estes, The problem of inference from curves based on group data, Psychological Bulletin 53 (1956) 134-140.
  • R. C. Wilson and A. G. E. Collins, Ten simple rules for the computational modeling of behavioral data, eLife 8 (2019) e49547.
  • S. Roberts and H. Pashler, How persuasive is a good fit? A comment on theory testing, Psychological Review 107 (2000) 358-367.
  • A. Newell and P. S. Rosenbloom (1981); A. Heathcote, S. Brown and D. J. K. Mewhort (2000).
  • P. R. Montague, R. J. Dolan, K. J. Friston and P. Dayan (2012); M. K. Eckstein et al. (2022); A. Mkrtchian, V. Valton and J. P. Roiser (2023).
  • J. R. Anderson, The Adaptive Character of Thought (Erlbaum, 1990); F. Lieder and T. L. Griffiths, Resource-rational analysis, Behavioral and Brain Sciences 43 (2020) e1.
  • D. E. Rumelhart, J. L. McClelland and the PDP Research Group, Parallel Distributed Processing (MIT Press, 1986).
  • M. Binz and E. Schulz, Using cognitive psychology to understand GPT-3, Proceedings of the National Academy of Sciences 120 (2023) e2218523120.
  • G. Schwarz, Estimating the dimension of a model, Annals of Statistics 6 (1978) 461-464; K. E. Stephan et al., Bayesian model selection for group studies, NeuroImage 46 (2009) 1004-1017.
About this partfrom its README

In the 1950s William Estes pointed out that a smooth, gradual learning curve can be the average of learners who each learned in a single jump. The average describes no one. Every earlier part of the series fitted a model to behaviour; this part opens the fitting harness and asks when a computational model of the mind is more than a curve fit.

The viewer sees Part 17's bandit fitted again and predicts four numbers: how well a learning rate is recovered from 200 choices, how often model comparison finds a perseverating learner, what curve fits the average of exponential learners, and how much fitting people as a population cuts the error in each learning rate. Then what a cognitive model is (a program from parameters to trial-level data) and four models of one bandit task; maximum likelihood with restarts, and the traps in the search; parameter recovery; the ridge along which learning rate and inverse temperature trade off; model comparison by likelihood ratio, AIC, BIC and cross-validation, and model recovery with its confusion matrix; Roberts and Pashler's question of how persuasive a good fit is, and a posterior predictive check that catches a model missing perseveration; people as a population, with empirical-Bayes shrinkage of learning rates; the power law of practice as an artefact of averaging; rational and resource-rational analysis; connectionism; and language models given the Battery.

What is computed and built
  • explainer/psychology/psyche/fit.py: jumping learners and their average; exponential learners and the power law of their average; four generative models of a reversal bandit with their likelihoods; maximum likelihood with restarts, AIC and BIC; parameter recovery; the likelihood surface; model recovery (the confusion matrix and its inversion); empirical-Bayes shrinkage of learning rates; stay-after-win and stay-after-loss, and a posterior predictive check. Tested in tests/psychology/test_fit.py.
  • The Ledger gains two rows.
  • The course's interactive: the reader plays a reversal bandit, and the page fits a Q-learner to their choices and shows how far a learning rate from that few choices can be trusted.
Chapter notes
# Chapter What it does
0 A curve no animal had Estes's jumping learners; every part has fitted models; the question; objectives
1 On you: your learning rate, and four numbers Four predictions
2 What a cognitive model is A program that makes behaviour; four models of one task; simulate before you fit
3 Fitting Maximum likelihood and a scorecard; traps in the search; two answers from one learner
4 Parameter recovery Simulate, fit, compare; how many trials?
5 Parameters that trade off The likelihood surface and its ridge; the ridge in repeated fits
6 Model comparison Four ways to compare; model recovery; predict the next session
7 A good fit can be bad Roberts and Pashler; what each model can produce; does the model make the effect?
8 People as a population Hierarchical fitting and shrinkage; when pooling pays
9 A law that was an average The power law of practice
10 Rational and resource-rational Anderson's rational analysis; optimal use of limited computation; how long to think
11 Connectionism Parallel distributed processing: what it added and what it cost
12 Language models as models of minds Giving a model the Battery; prediction against explanation
13 The Ledger Two rows; what they have in common
14 In practice: phenotypes, users and tutors Where fitted models run
15 Frontier: amortized inference and discovered models Three frontiers; open questions
Recap, problems, and the road ahead Your numbers; twelve lines; Kant's three objections; payoffs; problems; references; Part 49
NotesWhere the numbers come from
What Source
Estes's curves: 200 simulated learners, each at 10% correct until a jump (probability 0.12 per trial) and 95% after; the average rises smoothly, 19% on trial 1 and 50% by trial 5, matching 0.1 + 0.85(1 - 0.88^t) Psyche (fit.jump_learners), item jump
Practice: 60 simulated people whose response times fall exponentially at their own rates (log rate SD 2.0); an exponential fits 95% of them better than a power function; for the average, the power function wins (residual sum of squares 19,113 against 29,178) Psyche (fit.practice_curves), item practice
One simulated learner (a Q-learner with α = 0.3, β = 5, 200 trials, the arms swapping at trial 100) fitted by four models: BIC 281.6 (random), 235.3 (win-stay lose-shift), 135.4 (Q-learning, α̂ = 0.42, β̂ = 4.9) and 139.7 (with perseveration) Psyche (fit.simulate, fit.fit), item example
Parameter recovery: 75 simulated learners over 5 learning rates × 5 inverse temperatures, 200 trials each; correlation of true and recovered 0.92 for α and 0.90 for β Psyche (fit.recovery), item recovery
The likelihood surface over a 40 × 40 grid of (α, β) for the example learner Psyche (fit.tradeoff_surface), item surface
Model recovery: 25 data sets from each of four models, the model chosen by BIC; right 92%, 100%, 100% and 92% of the time; perseveration taken for plain Q-learning 8% of the time Psyche (fit.model_confusion), item confusion
A posterior predictive check: 30 learners who perseverate; stay after a win 0.97 and after a loss 0.85; plain Q-learning fitted and simulated predicts 0.96 and 0.70; the model with perseveration 0.97 and 0.84 Psyche (fit.posterior_predictive, fit.stay_after), item ppc
People as a population: 30 learners, 60 trials each, logit learning rates drawn around logit 0.3 (SD 0.6), β = 5 known; individual estimates miss by 0.69 (RMSE, logit scale), empirical-Bayes estimates by 0.36; population mean -0.70, SD 0.52 Psyche (fit.group_fit), item group
Signatures before fitting: 40 simulated players per model; stay after a win 0.51, 0.95, 0.89, 0.98 and after a loss 0.50, 0.05, 0.62, 0.87 (random, win-stay lose-shift, Q-learning, Q with perseveration) Psyche (fit.simulate, fit.stay_after), item signatures
Two optima: a learner with alpha 0.05, beta 15, kappa 0.5 over 80 trials, the three-parameter model fitted from 40 random starts; 70% reach the best fit (alpha 0.05, beta 18, kappa 0.36), 30% stop 3.1 log-likelihood units short (alpha 0.27, beta 5.2, kappa 0.74) Psyche (fit.loglik, L-BFGS-B), item starts
Recovery by trials: 72 learners at each of 50, 100, 200, 400 trials; correlation of true and fitted alpha 0.63, 0.77, 0.90, 0.95 and beta 0.58, 0.87, 0.90, 0.93 Psyche (fit.recovery), item trials
The ridge in repeated fits: one learner (0.3, 5) simulated 40 times; fitted alpha and beta correlate -0.52 Psyche (fit.fit), item tradeoff
Held-out prediction: 30 perseverating learners, two sessions each; log-likelihood per choice on the second session -0.71, -0.63, -0.27, -0.21 for the four models fitted on the first; BIC chose the true model for 93% Psyche (fit.fit, fit.loglik), item crossval
What each model can produce: stay after a win and after a loss for 60 random parameter settings of win-stay lose-shift, Q-learning and Q with perseveration Psyche (fit.simulate), item flex
Pooling by trials: 40 people, four groups at each length; logit learning-rate error alone 1.00, 0.57, 0.35, 0.27 and pooled 0.50, 0.41, 0.31, 0.25 at 30, 60, 120, 240 trials Psyche (fit.group_fit), item shrinktrials
How long to think: accuracy Phi(0.3 sqrt k) after k samples; the best k for a cost per sample of 0.002, 0.005, 0.01, 0.02 is 36, 21, 12, 5 arithmetic, item samples
Every published number on screen the studies listed under Sources, quoted as reported

The four models are the random chooser (one bias), win-stay lose-shift (one error rate), the Q-learner of Part 17 (α, β) and the Q-learner with a perseveration bonus (α, β, κ); every fit starts from up to three points within bounds and keeps the best.

Notes
Finding Original Status
Response time falls with practice as a power function of the number of trials, for each learner. Newell and Rosenbloom 1981 failed
Parameters of fitted cognitive models, such as a learning rate, are stable traits of a person that generalize across tasks and can serve as clinical markers. Montague, Dolan, Friston and Dayan 2012 contested

Shown without a row, with the reason recorded in explainer/psychology/ledger.py: Wilson and Collins; Roberts and Pashler; Anderson; Lieder and Griffiths; Rumelhart, McClelland and the PDP Group; Binz and Schulz.

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: Estes (1956) and the year and form of his argument; Wilson and Collins (2019) and their ten rules; Roberts and Pashler (2000); Newell and Rosenbloom (1981); Heathcote, Brown and Mewhort (2000); Montague et al. (2012); Eckstein et al. (2022); Mkrtchian, Valton and Roiser (2023); Anderson (1990); Lieder and Griffiths (2020); the PDP volumes (1986); Binz and Schulz (2023); the fine-tuned "foundation models of cognition" mentioned in the frontier chapter; Schwarz (1978); Stephan et al. (2009); and every page range in Sources.

Companion material in this repository

The syllabus's plan for this partfrom SYLLABUS.md, the plan of record
  1. Hook: Estes's curves. The power law of practice as an averaging artefact.
  2. What a cognitive model is: a generative program from parameters to trial-level data. The series' models, listed with their likelihoods.
  3. Fitting: maximum likelihood; local minima; when to simulate instead (likelihood-free methods).
  4. Parameter recovery: simulate, fit, compare. The heat map every modelling paper should show (done here for Parts 16, 17, 25 and 26's models).
  5. On you: your bandit data from Part 17, fitted, with the recovery plot beside it. How much should you trust your learning rate?
  6. Identifiability and sloppiness: parameters that trade off (learning rate and inverse temperature).
  7. Model comparison: likelihood ratios, AIC and BIC, cross-validation, Bayes factors, random-effects model selection over a group; model recovery and the confusion matrix (link to Statistics, Built Part 28).
  8. A good fit can be bad: flexibility and what a model rules out (Roberts and Pashler 2000); falsification by posterior prediction: does the winning model produce the qualitative effect?
  9. Hierarchical Bayes: people as draws from a population; shrinkage of individual parameters; a hierarchical diffusion model fitted with the series' own sampler (statkit.ppl).
  10. Levels again: rational analysis (Anderson 1990: derive behaviour from the problem) and resource-rational analysis (optimal use of limited computation).
  11. Connectionism: PDP (1986); what networks added (graded, learned representations) and what they cost (interpretability; catastrophic interference, Part 21).
  12. Language models as cognitive models: giving a model the Battery; fine-tuned "foundation models of cognition" (verify) and the argument over whether prediction is explanation (to Parts 60 and 61).

Psyche: psyche.fit: likelihoods for the series' models; optimizers with restarts; parameter- and model- recovery harnesses; hierarchical Bayesian fits; posterior predictive checks; the model zoo's confusion matrix. On you: the fit to your own data. Ledger: model-based parameters as stable traits (contested: low retest reliability, parameters that do not generalize across tasks); the power law of practice at the individual level (failed: exponential fits better). In practice: computational phenotyping, user modelling, simulation-based product testing, cognitive models inside tutoring systems. Frontier: amortized inference; automated model discovery; what a foundation model of behaviour would need to show. Reading: Estes 1956; Heathcote, Brown & Mewhort 2000; Farrell & Lewandowsky 2018; Wilson & Collins 2019; Lee & Wagenmakers 2013; Roberts & Pashler 2000; Pitt & Myung 2002; Palminteri, Wyart & Koechlin 2017; Anderson 1990; Lieder & Griffiths 2020; Rumelhart, McClelland & the PDP Group 1986.

Build the film

python -m videos.psychology.psych48.compute        # the part's numbers, into .cache/psych48
python tools/build.py psych48                  # render and assemble the film
EXPLAINER_TTS=silent python tools/qa_scene.py psych48 Hook   # one chapter, silent, with a contact sheet

Scenes: videos/psychology/psych48. Setup: see the course page. Source of these notes: the README and the scenes' narration.

Build it
python -m videos.psychology.psych48.compute            # every number (several minutes)
python tools/qa_scene.py psych48 Recovery              # one chapter, silent, at 480p, with a contact sheet
EXPLAINER_TTS=silent python tools/build.py psych48 -q l   # the whole part, silent preview
python tools/build.py psych48                          # 1080p30 with narration
python tools/qa_scene.py psych48 Compare --lang zh     # the Chinese edition of one chapter
python tools/make.py psych48                           # both editions, with the checks a long build needs
python -m videos.psychology.labs 48                    # the lab: simulate, fit, recover, compare
python tools/check_ledger.py psych48                   # every study shown has its Ledger row, or a reason
python -m pytest tests/psychology                      # Psyche's fit 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.