ΨPsychology, Built

Act XIII · The Frontier

Part 59 of 62

Computational Psychiatry

Researchstarts at this level28 min of film17 chaptersprerequisites: Part 3, Part 4, Part 17, Part 39, Part 48

Can a model of the mind tell a clinician something a conversation cannot?

Computational psychiatry plans to give a patient a task, fit a model and read off the parameter that has gone wrong. Its first obstacle is the reliability paradox: tasks with enormous group effects measure individuals poorly. The part sets out the theory-driven and data-driven routes, compulsivity and model-based control, anxiety and volatility, mood as an integral of prediction errors; buys reliability with trials, finds biotypes in data with none and exposes them by stability, scores a prediction model in sample, cross-validated and in a new trial, sizes a trial for choosing treatments, judges stimulation, psychedelics and phones by Part 2's standards, and sets five tests for a computational target. It opens with the care card.

What you need. Part 3's reliability and attenuation, Part 4's winner's curse, Part 17's learning models and Part 48's model fitting; correlation, logistic regression and cross-validation.

Hook
a task score that will not hold still
Ideas, models and mathematics
models as assays, the reliability paradox, biotypes and their replication, treatment selection, prediction that fails to transfer, neuromodulation, psychedelic trials and unblinding
Psyche gains
a precision-psychiatry trial bench
On you
reliable or sensitive: pick one

What you will be able to do

Psych 101 and the major

  • Explain the reliability paradox and why it limits tasks as clinical tests.
  • Explain why a model scored on its own data overstates how it will do in a new clinic.

Graduate

  • Compute the trials needed for a target reliability, and the attenuation of a correlation.
  • Run a clustering pipeline with a stability check, and cross-validate a prediction model properly.

Research

  • Design a study that tests whether a computational parameter is a treatment target.

Practice

  • Evaluate a biomarker or digital-health claim with six questions.

Contents

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

  1. 0Robust effects, unreliable peoplePsych 101 and the major2 min
  2. 1On you: design a task, and four numbersPsych 101 and the major1 min
  3. 2The programmePsych 101 and the major1 min
  4. 3Compulsivity and model-based controlPsych 101 and the major1 min
  5. 4Learning under uncertaintyResearch1 min
  6. 5Mood as computationResearch2 min
  7. 6Fixing measurementPsych 101 and the major2 min
  8. 7BiotypesResearch2 min
  9. 8Prediction that does not travelPsych 101 and the major2 min
  10. 9Choosing a treatmentPractice2 min
  11. 10New interventionsPractice2 min
  12. 11Digital phenotypingPractice2 min
  13. 12What would count as a computational targetResearch1 min
  14. 13The LedgerPsych 101 and the major1 min
  15. 14In practice: evaluating a biomarker claimPractice2 min
  16. 15Frontier: a clinical-grade batteryResearch1 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.

Robust effects, unreliable peoplePsych 101 and the major2 min

Before we start. This part is about psychiatry and mental illness, including depression, anxiety and compulsive disorders. It's education, not diagnosis or treatment. If any of it touches your own life, talk to a doctor, a counsellor, or someone you trust. If you're in danger now, call your local emergency number. In the United States you can call or text nine eight eight. In the UK and Ireland, Samaritans are on one one six, one two three. And find a helpline dot com lists free, confidential lines in other countries.

Here's the plan of computational psychiatry. Give a patient a task from Acts Four and Five, fit the model, and read off the parameter that has gone wrong. Then choose the treatment. But here's the first obstacle. Psyche's four hundred people do a Stroop-like task twice. The group effect is enormous, with a t statistic near fifty. But each person's effect barely repeats: the test-retest correlation is about zero point three. Craig Hedge, Gavin Powell and Petroc Sumner called it the reliability paradox in 2018. The tasks are trusted because everyone shows the effect, and that's exactly why they can't tell people apart. This part is a young field's promise, and the measurement discipline of Part 3 it's having to relearn.

So this part asks: can a model of the mind tell a clinician something a conversation can't? The programme, and two worked cases. Measurement: reliability, biotypes, and prediction that travels. Choosing treatments, and new interventions. And phones, and what would count as a target.

This is Part 59 of Psychology, Built: computational psychiatry. We'll meet the reliability paradox, and count the trials it costs. We'll separate theory-driven and data-driven programmes. We'll look at compulsivity, volatility and mood as computations. We'll find biotypes in data that has none, and learn how to tell. We'll watch prediction fail in a new trial, and size a trial for choosing treatments. And we'll judge stimulation, psychedelics and phones by Part 2's standards.

What it does: The care card; the paradox; the question; objectives

1On you: design a task, and four numbersPsych 101 and the major1 min

Can a task be good for groups and for individuals?

First, a slider. On the course site, you move a task's effect between uniform, where everyone shows it, and variable, where people differ. Uniform gives a huge group effect and useless reliability. Variable gives the reverse. Each curve here is a number of trials, and only more trials buy both. The cost is time with a patient, which is the clinic's real currency.

Now four numbers. One: a task's effect with two hundred trials per condition has reliability zero point five. How many trials for zero point nine? Two: cluster two hundred and twenty patients' brain data that has no subgroups at all. How often do the clusters differ in symptoms? Three: a model predicts treatment outcome with an AUC of zero point seven two in its own trial. What about in a new trial? And four: a trial to show a treatment works needs three hundred and fifty patients. How many to show that a rule for choosing treatments works? Pause here, and write them down.

What it does: The designer's slider; four predictions

2The programmePsych 101 and the major1 min

What is computational psychiatry trying to do? The theory-driven route fits a model of a mechanism, learning, inference or choice, to a task, and treats the parameters as the place where a disorder lives. Quentin Huys, Tiago Maia and Michael Frank set it out in 2016. The data-driven route uses machine learning on many measurements to predict diagnosis, course or treatment response, with or without a mechanism. The bridge fits mechanistic models, then uses their parameters as features for prediction. Both routes need measurements that are reliable in individuals, and predictions that hold in new samples.

What has it delivered so far? Robust group findings: altered learning from punishment in depression, reduced model-based control along a compulsivity dimension, and aberrant salience in psychosis. New tasks and models, and large online samples that make individual differences possible to study. But no validated clinical test yet. No parameter is used to diagnose, or to choose a treatment, in routine care. The reasons are this part's chapters: reliability, replication and generalization.

What it does: Two routes; what has been delivered

3Compulsivity and model-based controlPsych 101 and the major1 min

Is compulsion a habit that planning cannot override?

Is compulsion a habit that planning can't override? Part 17's two-step task separates model-free learning, repeating what was rewarded, from model-based planning, which uses the task's structure. In 2016 Claire Gillan and colleagues had about fourteen hundred online participants do the task and many symptom questionnaires. A factor analysis of the questionnaires found three transdiagnostic dimensions. One, compulsive behaviour and intrusive thought, went with less model-based control. The link was with a dimension that cuts across diagnoses, as in Part 39, not with any one diagnosis.

What limits it? Size: the association is small. It describes a population, not a patient, which is Part 47's point. Reliability: the task's model-based index has modest retest reliability. A true correlation of zero point five, measured with reliabilities of zero point four and zero point eight, shows as about zero point two eight. Replication: the online finding has replicated in further online and clinical samples. And the next step is to show that changing model-based control changes compulsion. That needs an intervention, not a correlation.

What it does: Fourteen hundred people online; what limits it

4Learning under uncertaintyResearch1 min

Does anxiety change how fast people learn? In 2007 Timothy Behrens and colleagues found that people raise their learning rate when the world is volatile, as Part 17's Bayesian learner should. In 2015 Michael Browning and colleagues found that in a task alternating stable and volatile blocks, people high in trait anxiety adjusted their learning rate less. The account: anxiety as a difficulty in using the world's statistics to set how much to learn. Later studies with larger samples found the deficit inconsistently.

A model built for this is the hierarchical Gaussian filter, here in outline. Level one is what happens on each trial, reward or not. Level two is the tendency the outcomes come from, drifting over time. Level three is how fast that tendency drifts: the volatility. The learning rate falls out of the model, higher when volatility is believed to be high, like a Kalman filter's gain. And the parameters, how much a person believes the world changes and how fast they update that belief, are candidate computational targets.

What it does: Volatility and anxiety; the hierarchical Gaussian filter

5Mood as computationResearch2 min

What is a mood, computationally? In 2014 Robb Rutledge and colleagues found that in a gambling task, momentary happiness was predicted by recent expected rewards and reward prediction errors, Part 17's signal, not by total winnings. The same model fitted the ratings of about eighteen thousand smartphone app users. Eran Eldar and Yael Niv proposed mood as momentum: an integral of recent prediction errors that biases how new outcomes are perceived. It's a loop that could tip into mania or depression. The promise is mood disorders as mis-set integrators. The evidence so far is from healthy samples and models, not patients.

How would a computational account of mood be tested? Prediction: does the integrator's time constant, fitted from a week of ratings, predict the next month's course? Reliability: is it stable across weeks in the same person? Intervention: do treatments that help mood change the parameter, and does the change come first? Each step is a separate study, and few have been done.

Here's the idea run forward. Forty gambles, with a run of losses in the middle. The bars are the prediction errors. Two simulated people have the same weights, and differ only in how slowly past errors fade. The slow integrator swings higher in good times, and much lower in the losing run: about zero point one five against zero point three one. One parameter, a time constant, separates a resilient mood from a sticky one. That's the kind of target the programme wants, if it can be measured reliably, which is chapter six's question.

What it does: Happiness moment to moment; how to test it

6Fixing measurementPsych 101 and the major2 min

How many trials does a person need? Spearman and Brown's formula, from Part 3, says trial noise shrinks as one over the number of trials, while true differences don't. Psyche's task at sixty trials has a reliability of about zero point three. To reach zero point nine takes about eleven hundred and fifty trials per condition. That's most of an hour on one task. And your first number: a reliability of zero point five at two hundred trials needs nine times as many for zero point nine. That's eighteen hundred.

What does unreliability do to a correlation? Part 3's attenuation formula: the observed correlation is the true one times the square root of the two reliabilities. A true link of zero point five between a parameter and a symptom shows as zero point two when the task's reliability is zero point two. Put small samples and low reliability together, and links are missed, and the ones that are found are exaggerated: Part 4's winner's curse. Many published correlations between a parameter and a symptom sit between zero point one and zero point three.

What fixes it? Model the trials. Hierarchical models estimate each person's effect along with its noise, instead of taking a difference of two means. That's Jeffrey Rouder and Julia Haaf's point, and Part 48's tools. Skip the difference. Use the model's parameters, or raw speed and accuracy, which are often more reliable than a difference score. Spread the trials. Short sessions on many days, at home on a phone, average out bad days. Report reliability. Every individual-differences study should report its measure's reliability in its own sample. And design for people: choose conditions where people differ, not where everyone shows the effect.

What it does: Reliability bought with trials; attenuation; the fixes

7BiotypesResearch2 min

Are there kinds of depression in the brain? In 2017 Andrew Drysdale and colleagues analysed resting-state scans from about twelve hundred people. They chose the connectivity features most correlated with symptoms, then clustered patients on them. They found four clusters, with different symptom profiles, and different responses to magnetic stimulation in a subset. It was a promise: a scan that tells you which kind of depression a person has, and which treatment to give.

Now run the same pipeline on data with no types. Psyche's two hundred and twenty patients have twenty connectivity features and no subgroups at all. Symptoms depend weakly on three features. The pipeline keeps the six features most correlated with symptoms, clusters patients into four, and tests whether the clusters differ in symptoms. In nine of ten simulated studies, they do, at p below zero point zero five. That's your second number. The features were chosen for their link to symptoms, so any way of cutting them gives groups that differ. It's circular analysis: Part 8's double dipping.

How do you tell real types from fake ones? Split the sample and see if the clusters come back. Cluster two random halves separately, assign everyone by each half's centres, and compare the labels. With no types, the agreement is about zero point one six. The clusters are different every time. With real types planted in Psyche, it's about zero point seven four. The clusters come back. In 2019 Richard Dinga and colleagues re-ran the biotype analysis on a hundred and eighty-seven people. The clusters weren't stable, and data without clusters gave similar results.

What it does: Four biotypes; the pipeline on data with no types; split-half stability

8Prediction that does not travelPsych 101 and the major2 min

Will a model that predicts response work in the next clinic? In 2016 Adam Chekroud and colleagues took twenty-five baseline questions from about nineteen hundred patients in a large antidepressant trial, and trained a machine-learning model of who would remit. Tested in another trial, it was about sixty percent accurate in a similar drug arm, and little better than chance in a different one. In 2024 the same group took five antipsychotic trials, trained in one, and tested in the others. Models were good within the trial they were built in, and close to chance in the others.

Here are three accuracies for one model. Psyche's trials have three hundred patients and forty baseline features, of which three are weakly predictive. The model keeps the ten best features and fits a logistic regression. Scored on the data it was built from, the AUC is zero point seven two. Honest cross-validation, with feature selection inside each fold, gives zero point five nine. In a new trial at another site, where the relations have drifted a little, it's zero point five seven. That's your third number.

Why doesn't prediction travel? Selection on all the data: choosing features before cross-validation leaks the answer into the estimate. Different patients: inclusion criteria, sites and severity shift the features' distribution. Different relations: protocols, doses and raters change how features relate to outcome. A small signal: when the true signal is weak, the noise a model learned is a large share of what it knows. And the standard to ask for: external validation in an independent sample, registered before it's run, as the TRIPOD reporting guideline sets out.

What it does: Predicting response; three accuracies; why

9Choosing a treatmentPractice2 min

Can data say which treatment suits which person? In 2014 Robert DeRubeis and colleagues took a trial of cognitive therapy against antidepressants, and fitted a model of each patient's outcome under each treatment. The index is the predicted outcome under one treatment minus that under the other: a patient's predicted advantage. Most patients had small predicted advantages. For a minority, the predicted difference was clinically meaningful. The test that matters is to randomize patients to treatment chosen by the index, or as usual, and compare.

What does it cost to show that a choice rule works? A rule helps only if treatments work differently for different people. Statistically, that's an interaction between treatment and a moderator. To show a main effect of size zero point three takes about three hundred and fifty patients, at eighty percent power. An interaction of the same size takes four times as many, about fourteen hundred. That's your fourth number. And real interactions are usually smaller than main effects, so few trials are big enough.

What works while we wait? Measurement-based care: measure symptoms every visit, and change treatment when progress stalls. That's Part 57's feedback. Stepped care: start with the least intensive treatment that may work, and step up those who don't respond. Shared decisions: patients' preferences and side effects are information a model doesn't have. And sequential trials, which randomize again at each step, the designs called SMART, to learn which next step is best.

What it does: The personalized advantage index; its sample; what works meanwhile

10New interventionsPractice2 min

What do stimulation and psychedelics show?

What do new interventions show? First, stimulating the brain. Transcranial magnetic stimulation sends magnetic pulses over the prefrontal cortex. It was cleared in the United States for depression in 2008, and meta-analyses find a modest benefit over sham. Accelerated protocols give many sessions a day, aimed by each person's connectivity map. In 2022 Eleanor Cole and colleagues reported a large benefit over sham, in a trial of twenty-nine people. Deep brain stimulation puts electrodes in the subgenual cingulate. It gave striking open results in a few patients in 2005, and then a larger sham-controlled trial was stopped for futility. The lesson: small open studies of devices overestimate. Sham control and size decide.

Second, fast-acting drugs. A single infusion of ketamine lifts depressive symptoms within hours in some patients. A nasal spray of esketamine was approved in 2019. The effects fade over days. Psilocybin: in 2022 Guy Goodwin and colleagues gave two hundred and thirty-three patients a dose of twenty-five milligrams or one milligram. There was a larger fall in symptoms at three weeks, smaller and uncertain by twelve. The problem is blinding. People usually know whether they had a psychedelic, so expectation, Part 57's subject, is part of every result. The proposed mechanisms, relaxed priors and plasticity, are computational, and still to be tested.

So judge them by Part 2's standards. Randomization and a credible control: sham coils, active placebos, or low doses. Blinding checked, not assumed: ask patients and raters what they think was given. Outcomes that last months, not days. Enough patients that the estimate isn't one lucky sample, as in Part 4. And replication by groups without a stake in the treatment.

What it does: Stimulation; fast-acting drugs; Part 2's standards

11Digital phenotypingPractice2 min

Can a phone measure a mood? In 2017 Thomas Insel argued that phones record movement, sleep, typing and talk continuously, so a digital phenotype could track illness between visits. Active data are brief questionnaires several times a day, Part 47's experience sampling. Passive data come from GPS, the accelerometer, screen use and calls, with no effort from the person. Early studies of a few dozen people found strong links between GPS features and depression scores. Larger studies found much weaker ones.

Here's why. Four hundred simulated studies of a phone feature whose true correlation with mood is zero point two. With thirty people, the correlations range widely, and a few percent exceed zero point five. With three hundred, they cluster near the truth. The strong early results were the lucky tail of small samples, selected for publication, as in Part 4.

What can a phone do, and what can't it? Within a person, changes from their own baseline, Part 47's idea, may be more useful than comparisons between people. Missing data: people stop using apps, and the days with no data may be the worst ones. Privacy: location and messages are intimate, so consent, storage, and who sees the data are part of the design. And action: a signal is useful only if someone can act on it in time, with a person in the loop.

What it does: The phone as an instrument; small samples; limits

12What would count as a computational targetResearch1 min

When is a parameter ready for the clinic? Here are five tests. It's reliable: retest reliability high enough to place a person, about zero point eight or more. Its link to symptoms holds out of sample, in a new sample, not just the one it was found in. Effective treatments move it. Its change comes first: the parameter changes before the symptoms do, and carries the effect. And the same results hold in new sites: other clinics, countries and devices.

Here are four candidates from this part, scored against the five tests, as the published record stands. Model-based control: its link to compulsivity has replicated out of sample and across sites; its reliability is mixed, better with hierarchical models. Whether treatment moves it is mixed, and whether its change comes first is untested. The learning rate under volatility: reliability and replication are mixed, and the rest untested. The mood integrator: promising, mostly untested. And connectivity biotypes failed the stability and replication tests. No parameter passes all five yet. That's the honest state of a young field.

What it does: Five tests; four candidates scored

13The LedgerPsych 101 and the major1 min

What the four have in common. The group findings are real. Measuring individuals is the bottleneck. The failures share one cause: an analysis that sees its own answer, in circular clusters and in-sample accuracy. The fixes are old: reliability, held-out data, and independent samples. So here's the answer to this part's question. A model of the mind can tell a clinician something new only after it passes Part 3's and Part 4's tests in individuals, and none has yet.

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

14In practice: evaluating a biomarker claimPractice2 min

A start-up says its test predicts which antidepressant will work. What do you ask?

Where is this a job? In computational psychiatry labs: tasks, models, and large online and clinical samples. In digital health companies: apps, sensing, and prediction models sold to health systems. In health technology assessment, which decides whether a test or device is worth paying for. And at regulators, who clear devices and software as medical devices.

Here's a claim of the kind you'll meet. It's invented for this exercise, and describes no real company. Our twenty-minute game and an AI model predict which of two antidepressants will work for you, with eighty-five percent accuracy, in a study of a hundred and twenty patients. What do you ask?

Six questions. Was the eighty-five percent measured on patients the model never saw, from another site? That's chapter eight. Were the features chosen using all hundred and twenty patients? That's chapter eight's leak. What's the game's retest reliability? That's chapter six. Did each patient get both drugs, or was the right drug inferred? A choice rule needs an interaction, and about fourteen hundred patients to show one. That's chapter nine. Compared with what: the better drug for everyone, or a clinician's choice? And has a randomized trial of choosing by the test, against usual care, been registered?

What it does: Where this is a job; a made-up claim; six questions

15Frontier: a clinical-grade batteryResearch1 min

What would a reliable computational assessment look like? Reliability first: tasks redesigned and selected for retest reliability, with trial-level hierarchical models. Many short sessions: games played at home over weeks, averaging out bad days. Large cohorts: tens of thousands of online participants, and population cohorts with tasks, symptoms and follow-up. And registered validation: models frozen and tested in samples their builders never saw.

And the open problems. Mechanism or marker: is a parameter a cause of illness, or only a sign of it? States and traits: parameters change with mood and sleep, so which part is the person? Treatment by parameter: a trial that assigns treatment by a computational measure, and wins. And lived experience: what patients count as getting better, built into the models.

What it does: What is new; open problems

Recap, problems, and the road aheadAll tracks3 min

First, your four numbers. To go from a reliability of zero point five at two hundred trials to zero point nine takes eighteen hundred. Clusters in data with no types differed in symptoms in nine studies out of ten. A model with an AUC of zero point seven two at home scored zero point five seven in a new trial, in Psyche. And showing that a choice rule works takes about fourteen hundred patients, four times the trial for the treatment itself. The group effects are real. Measuring individuals, and generalizing, are the work that's left.

Part fifty-nine in twelve lines. Robust group effects can be unreliable measures of individuals. The theory-driven and data-driven routes need the same discipline. Compulsivity goes with less model-based control. Anxiety and volatility is an idea with mixed evidence. Mood may be an integral of prediction errors. More trials, hierarchical models and many sessions fix measurement. Circular clusters always differ in symptoms, so check their stability. In-sample accuracy doesn't travel. Choice rules need four times the sample. Stimulation and psychedelics are judged by sham, blinding and size. Phones' strong correlations from small samples shrink. And there are five tests for a target, and none has been passed yet.

Where this comes back. Models of minds, artificial and human, are Part 60. The next psychology, with big teams and registered models, is Part 61. And Part 62's dissertation can take on the measurement of individuals.

Seven problems, with full solutions in this part's README. One buys reliability with trials. One attenuates a correlation. One repairs a leaky pipeline. One reads a stability check. One sizes a trial for a choice rule. One puts an interval on a small study's correlation. And the last, with the star, asks you to design a test of a computational treatment target. Pause here if you'd like to try them.

The books and papers behind this part are listed here and in the README. Peggy Series's primer is the best introduction to the models; Redish and Gordon's volume surveys the field; and Huys, Maia and Frank's review sets out the two routes.

Two parts of the frontier are done. This one asked whether models of the mind can reach the clinic, and found the road runs through measurement. The next asks about a different kind of model: machines that talk. What can large language models tell psychology, and what can psychology tell us about them? Part 60: Minds and Machines.

Where it goes next. Part 60 asks what models of machines can tell psychology; Part 61 takes up big-team science and registered models; Part 62's dissertation can measure individuals properly.

Key results

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

Difference-score reliability\(\displaystyle \rho = \frac{\sigma_b^2}{\sigma_b^2 + 2\sigma_t^2/n}\)
Spearman-Brown\(\displaystyle \rho_k = \frac{k\rho}{1 + (k-1)\rho}\)
Attenuation\(\displaystyle r_{\text{obs}} = r_{\text{true}}\sqrt{\rho_x\rho_y}\)
An interaction's sample\(\displaystyle N_{\text{interaction}} \approx 4\,N_{\text{main}}\)

Try it

Lab 59 · Computational Psychiatry

Measure the reliability of a robust task effect, expose a circular biotype pipeline with a stability check, and score a prediction model in sample, cross-validated and in a new trial.

Figure produced by Lab 59: Computational Psychiatry
Produced by the lab below, seed 0, in 0.4 s.
python -m videos.psychology.labs 59 needs numpy, scipy, matplotlib · download lab59.py · source on GitHub
group t; retest r (expected)                              37; 0.39 (0.32)
trials per condition for reliability 0.9                  1152
no types: studies with p < 0.05; stability                4 of 4; 0.17
real types: stability                                     0.80
AUC: same data; cross-validated; new trial                0.71; 0.59; 0.57
patients for a main effect; for an interaction (d = 0.3)  349; 1395

Group effects are real; measuring individuals takes many trials, and a result found in a sample must be checked in a sample that did not choose it.
The code (53 lines; it asserts its own result)
"""Lab 59: computational psychiatry: the reliability paradox, biotypes that are not there, and prediction that
does not travel."""

import numpy as np

from videos.coursekit import labs
from explainer.psychology.psyche import precision as Pr

TITLE = "Computational Psychiatry"
GOAL = ("Measure the reliability of a robust task effect, expose a circular biotype pipeline with a stability "
        "check, and score a prediction model in sample, cross-validated and in a new trial.")
TASKS = [
    "Raise the trials per condition to 600. What is the retest correlation now?",
    "Plant subgroups (structure 1.5). How stable are the clusters?",
    "Remove the drift between trials. How close does the new-trial AUC come to the cross-validated one?",
]


def run(seed=0):
    out = labs.Lab()
    p = Pr.paradox(n_people=300, seed=seed)
    assert p["t"] > 20 and p["retest_r"] < 0.6
    out.row("group t; retest r (expected)", f"{p['t']:.0f}; {p['retest_r']:.2f} ({p['expected_r']:.2f})")
    need = 0.9 / 0.1 / (p["expected_r"] / (1 - p["expected_r"])) * 60
    out.row("trials per condition for reliability 0.9", f"{need:.0f}")
    none = [Pr.biotypes(structure=0.0, seed=seed + r) for r in range(4)]
    real = [Pr.biotypes(structure=1.5, seed=seed + 50 + r) for r in range(4)]
    a0, a1 = np.mean([b["stability_ari"] for b in none]), np.mean([b["stability_ari"] for b in real])
    assert a1 > a0 + 0.2
    out.row("no types: studies with p < 0.05; stability", f"{sum(b['symptom_p'] < 0.05 for b in none)} of 4; {a0:.2f}")
    out.row("real types: stability", f"{a1:.2f}")
    t = Pr.cross_trial(reps=15, seed=seed)
    assert t["apparent"] > t["cv"]
    out.row("AUC: same data; cross-validated; new trial", f"{t['apparent']:.2f}; {t['cv']:.2f}; {t['new_trial']:.2f}")
    s = Pr.pai_sample(0.3)
    out.row("patients for a main effect; for an interaction (d = 0.3)",
            f"{s['main_total']:.0f}; {s['interaction_total']:.0f}")

    out.note = ("Group effects are real; measuring individuals takes many trials, and a result found in a sample "
                "must be checked in a sample that did not choose it.")

    fig, ax = labs.figure(2, size=(11, 4.0))
    ax[0].scatter(p["s1"], p["s2"], s=8)
    ax[0].set(title="retest of a robust effect", xlabel="session 1 (ms)", ylabel="session 2 (ms)")
    ax[1].bar(["same data", "cross-validated", "new trial"], [t["apparent"], t["cv"], t["new_trial"]],
              color=labs.BLUE)
    ax[1].set(title="one model, three AUCs", ylim=(0.5, 0.8))
    out.fig = fig
    return out


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

Now change it

  1. Raise the trials per condition to 600. What is the retest correlation now?
  2. Plant subgroups (structure 1.5). How stable are the clusters?
  3. Remove the drift between trials. How close does the new-trial AUC come to the cross-validated one?

Problems, with solutions

Try each problem before opening its solution.

  1. Trials for 0.8. A task's retest reliability is 0.3 with 60 trials per condition. How many trials for 0.8?

    Solution

    Spearman-Brown: the factor is (0.8/0.2)/(0.3/0.7) = 9.3, so about 560 trials per condition.

  2. Attenuation. A true correlation of 0.4; reliabilities 0.5 and 0.8. The expected observed correlation?

    Solution

    0.4 x sqrt(0.5 x 0.8) = 0.4 x 0.63 = 0.25.

  3. A leaky pipeline. Features were chosen on all patients, then the model was cross-validated. Why is the estimate too high, and how do you fix the pipeline?

    Solution

    The features were chosen because they correlated with the outcome in every patient, including the ones later held out, so each held-out fold has already been looked at. Put the selection (and any tuning) inside each training fold, and test the final model on an independent sample.

  4. A stability check. Two halves of a sample give clusters that agree with an adjusted Rand index of 0.15. What do you conclude, and what null would you compare against?

    Solution

    An adjusted Rand index of 0.15 means the two halves cut the sample in nearly unrelated ways: the clusters are not reproducible. Compare against the same pipeline run on data with the covariance kept and the clusters removed (for example, draws from a single Gaussian with the sample's covariance); if real data are no more stable than that null, there is no evidence of types.

  5. An interaction of 0.2. A choice rule's benefit is an interaction of size 0.2. About how many patients to detect it?

    Solution

    A main effect of 0.2 needs about 4 x (1.96 + 0.84)^2 / 0.2^2 = 785 patients; an interaction of the same size about four times that, roughly 3,100.

  6. A small study's correlation. A phone feature correlates 0.6 with mood in 25 people. Give a 95% interval for the correlation.

    Solution

    Fisher's z: atanh(0.6) = 0.69, standard error 1/sqrt(22) = 0.21, so 0.69 +/- 0.42, and back-transformed 0.27 to 0.80. The interval is compatible with a modest correlation.

  7. ★ A target, tested. Design a study to test whether model-based control is a treatment target: reliability, intervention, mediation.

    Solution

    Measure model-based control with a reliability-tuned task and a hierarchical model, at several sessions (aim for retest reliability of 0.8); randomize patients with compulsive symptoms to a training or treatment expected to change it, against an active control; measure the parameter and symptoms weekly; pre-register the mediation analysis (does the parameter change before symptoms, and does it carry the effect?); and replicate in a second site.

Notes and sources

Sources

  • Q. J. M. Huys, T. V. Maia and M. J. Frank, Computational psychiatry as a bridge from neuroscience to clinical applications, Nature Neuroscience 19 (2016) 404-413; P. Series (ed.), Computational Psychiatry: A Primer (MIT Press, 2020); A. D. Redish and J. A. Gordon (eds.), Computational Psychiatry: New Perspectives on Mental Illness (MIT Press, 2016).
  • C. Hedge, G. Powell and P. Sumner (2018); A. Z. Enkavi et al. (2019); J. N. Rouder and J. M. Haaf (2019).
  • C. M. Gillan et al. (2016); E. H. Patzelt et al. (2019); C. M. Gillan et al. (2020); N. D. Daw, S. J. Gershman, B. Seymour, P. Dayan and R. J. Dolan, Model-based influences on humans' choices and striatal prediction errors, Neuron 69 (2011) 1204-1215.
  • T. E. J. Behrens, M. W. Woolrich, M. E. Walton and M. F. S. Rushworth, Learning the value of information in an uncertain world, Nature Neuroscience 10 (2007) 1214-1221; M. Browning, T. E. Behrens, G. Jocham, J. X. O'Reilly and S. J. Bishop, Anxious individuals have difficulty learning the causal statistics of aversive environments, Nature Neuroscience 18 (2015) 590-596; C. Mathys, J. Daunizeau, K. J. Friston and K. E. Stephan, A Bayesian foundation for individual learning under uncertainty, Frontiers in Human Neuroscience 5 (2011) 39.
  • R. B. Rutledge, N. Skandali, P. Dayan and R. J. Dolan, A computational and neural model of momentary subjective well-being, PNAS 111 (2014) 12252-12257; E. Eldar, R. B. Rutledge, R. J. Dolan and Y. Niv, Mood as representation of momentum, Trends in Cognitive Sciences 20 (2016) 15-24.
  • A. T. Drysdale et al. (2017); R. Dinga et al. (2019).
  • A. M. Chekroud et al. (2016, 2024); G. S. Collins, J. B. Reitsma, D. G. Altman and K. G. M. Moons, Transparent reporting of a multivariable prediction model for individual prognosis or diagnosis (TRIPOD), Annals of Internal Medicine 162 (2015) 55-63.
  • R. J. DeRubeis et al., The Personalized Advantage Index: translating research on prediction into individualized treatment recommendations, PLoS ONE 9 (2014) e83875.
  • E. J. Cole et al., Stanford neuromodulation therapy (SNT): a double-blind randomized controlled trial, American Journal of Psychiatry 179 (2022) 132-141; H. S. Mayberg et al., Deep brain stimulation for treatment-resistant depression, Neuron 45 (2005) 651-660; P. E. Holtzheimer et al., Subcallosal cingulate deep brain stimulation for treatment-resistant depression: a multisite, randomised, sham-controlled trial, Lancet Psychiatry 4 (2017) 839-849.
  • R. M. Berman et al., Antidepressant effects of ketamine in depressed patients, Biological Psychiatry 47 (2000) 351-354; G. M. Goodwin et al., Single-dose psilocybin for a treatment-resistant episode of major depression, New England Journal of Medicine 387 (2022) 1637-1648.
  • T. R. Insel, Digital phenotyping: technology for a new science of behavior, JAMA 318 (2017) 1215-1216; S. Saeb et al., Mobile phone sensor correlates of depressive symptom severity in daily-life behavior, Journal of Medical Internet Research 17 (2015) e175.
About this partfrom its README

The plan of computational psychiatry is simple to state: give a patient a task from Acts IV and V, fit the model, read off the parameter that has gone wrong, and choose a treatment by it. The first obstacle is the reliability paradox: Psyche's 400 people do a Stroop-like task twice, the group effect has a t statistic near 50, and each person's effect correlates about 0.3 with itself three weeks later. This part is the field's promise and the measurement discipline of Part 3 and Part 4 it is having to relearn. The part opens with the care card (education, not diagnosis or treatment, and where help is found).

The viewer designs a task on a slider (uniform effects against variable ones) and predicts four numbers. Then the two routes (theory-driven and data-driven); compulsivity and model-based control; anxiety and volatility, with the hierarchical Gaussian filter in outline; mood as an integral of prediction errors; buying reliability with trials, attenuation and the fixes; biotypes from a circular pipeline on data with no types, and the split-half stability check that exposes them; a prediction model scored three ways (in sample, cross-validated, in a new trial); the personalized advantage index and the sample a choice rule needs; brain stimulation and psychedelics by Part 2's standards; digital phenotyping and the small samples behind its first strong results; and five tests a parameter must pass to be a clinical target, with four candidates scored.

What is computed and built
  • explainer/psychology/psyche/precision.py: difference-score reliability, the paradox, the design trade-off, attenuation, k-means and the adjusted Rand index, the biotype pipeline with its stability check, a trial simulator, ridge logistic regression, AUC, cross-trial prediction and the choice rule's sample. Tested in tests/psychology/test_precision.py.
  • The Ledger gains four rows.
  • The course's interactive: design a task on a slider and watch group effect and reliability trade off, then buy reliability with trials.
Chapter notes
# Chapter What it does
0 Robust effects, unreliable people The care card; the paradox; the question; objectives
1 On you: design a task, and four numbers The designer's slider; four predictions
2 The programme Two routes; what has been delivered
3 Compulsivity and model-based control Fourteen hundred people online; what limits it
4 Learning under uncertainty Volatility and anxiety; the hierarchical Gaussian filter
5 Mood as computation Happiness moment to moment; how to test it
6 Fixing measurement Reliability bought with trials; attenuation; the fixes
7 Biotypes Four biotypes; the pipeline on data with no types; split-half stability
8 Prediction that does not travel Predicting response; three accuracies; why
9 Choosing a treatment The personalized advantage index; its sample; what works meanwhile
10 New interventions Stimulation; fast-acting drugs; Part 2's standards
11 Digital phenotyping The phone as an instrument; small samples; limits
12 What would count as a computational target Five tests; four candidates scored
13 The Ledger Four rows; what they have in common
14 In practice: evaluating a biomarker claim Where this is a job; a made-up claim; six questions
15 Frontier: a clinical-grade battery What is new; open problems
Recap, problems, and the road ahead Your numbers; twelve lines; payoffs; problems; references; Part 60
NotesWhere the numbers come from
What Source
The reliability paradox: 400 people, 60 trials per condition, a true effect of 60 ms with a between-person SD of 15 and a trial SD of 120; t = 48, retest r = 0.30 (expected 0.32) Psyche (precision.paradox), item paradox
The designer's slider: reliability against the share of the effect that varies between people, for 20 to 800 trials per condition Psyche (precision.design_tradeoff), item tradeoff
Reliability against trials (0.32 at 60 trials; about 1,150 trials for 0.9) Psyche (precision.difference_reliability), in the scene
Attenuation: a true r of 0.5, symptom reliability 0.8, task reliability 0.2 to 1.0; observed 0.20 to 0.45 Psyche (precision.attenuated_r), item attenuate
Biotypes: 220 patients, 20 features, no subgroups; six features chosen by their correlation with symptoms, k-means with four clusters; symptom differences at p < 0.05 in 9 of 10 studies; split-half agreement (adjusted Rand index) about 0.16, against about 0.74 with planted subgroups Psyche (precision.biotypes), item biotypes
Prediction: 300 patients per trial, 40 features, three weakly predictive; ten selected, ridge logistic regression; AUC 0.72 in sample, 0.59 cross-validated with selection inside the folds, 0.57 in a new trial with shifted features and drifted coefficients (60 pairs of trials) Psyche (precision.cross_trial), item travel
A choice rule's sample: about 350 patients for a main effect of 0.3 (two-sided 5%, 80% power), about 1,400 for an interaction of the same size Psyche (precision.pai_sample), item pai
Phones: 400 simulated studies of a true correlation of 0.2, with 30 or 300 people computed in the scene (seed 5904)
Every published number on screen the studies listed under Sources, quoted as reported
Notes
Finding Original Status
Cognitive tasks with robust group effects (Stroop, flanker, stop-signal) measure individual differences poorly: their difference scores have low test-retest reliability. Hedge, Powell and Sumner 2018 replicated
Weaker model-based (goal-directed) control on the two-step task goes with a transdiagnostic dimension of compulsive behaviour and intrusive thought. Gillan and colleagues 2016 replicated
Resting-state connectivity divides depression into four biotypes that differ in symptoms and in response to brain stimulation. Drysdale and colleagues 2017 contested
A machine-learning model trained on one clinical trial predicts which patients will respond to treatment in other trials. Chekroud and colleagues 2016 failed

Shown without a row, with the reason recorded in explainer/psychology/ledger.py: Huys, Maia and Frank; Browning and colleagues; Mathys and colleagues; Rutledge and colleagues; DeRubeis and colleagues; Cole and colleagues; Goodwin and colleagues; Insel.

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: Hedge, Powell and Sumner's samples and reliabilities; Enkavi et al.'s retest sample and results; Rouder and Haaf (2019); Gillan et al.'s sample of about 1,400 and three factors; Patzelt et al. (2019); Gillan et al. (2020) and its journal; Behrens et al. (2007); Browning et al. (2015) and the later inconsistent replications; Mathys et al. (2011); Rutledge et al.'s 18,000 app users; Eldar et al. (2016); Drysdale et al.'s 1,200 scans and four clusters; Dinga et al.'s 187 people and findings; Chekroud et al.'s 25 items, about 1,900 patients and external accuracies; Chekroud et al. (2024)'s five antipsychotic trials; DeRubeis et al.'s trial and findings; TMS's 2008 clearance; Cole et al.'s 29 people; Mayberg et al. (2005) and the stopped BROADEN trial; ketamine and the 2019 esketamine approval; Goodwin et al.'s 233 patients, doses and results; Insel (2017); Saeb et al. (2015) and the later larger studies; 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: the reliability paradox (Hedge, Powell and Sumner 2018). Robust effects, unreliable individual scores.
  2. The programme: theory-driven models (parameters as mechanisms) and data-driven prediction; what each has delivered.
  3. Worked case: compulsivity and reduced model-based control in fourteen hundred online participants (Gillan et al. 2016), with a transdiagnostic factor (Part 39).
  4. Worked case: learning under uncertainty: volatility, learning rates and anxiety; hierarchical Gaussian filters in outline.
  5. Mood as computation: momentum and reward prediction errors (Part 40) at smartphone scale.
  6. On you: design a task. A slider trades reliability against sensitivity to the effect; you cannot have both without more trials (computed).
  7. Fixing measurement: hierarchical models, more trials, task redesign; retest reliability of model parameters.
  8. Biotypes: clustering patients by brain connectivity (2017), and what happened on replication.
  9. Prediction that does not travel: treatment-outcome models that work in the trial they were trained on and fall to chance in the next (2024).
  10. Treatment selection: the personalized advantage index; how large a trial a selection rule needs (computed).
  11. New interventions: targeted brain stimulation; closed-loop stimulation in single patients; psychedelic trials, functional unblinding (Part 2) and a regulator's refusal (verify).
  12. Digital phenotyping: what phone sensors predict, and the ethics.

Psyche: a precision-psychiatry bench on the Pool: task designs scored for reliability and sensitivity; a clustering pipeline that finds "biotypes" in structureless data; a prediction model trained on one simulated trial and tested on another; power for treatment-selection trials. On you: the task-design slider. Ledger: the reliability paradox (replicated); model-based deficits in compulsivity (replicated online); connectivity biotypes of depression (contested, replication failures); cross-trial generalization of outcome prediction (failed so far); accelerated stimulation protocols (verify). In practice: digital mental-health products, trial design, biomarker claims and how to evaluate them. Frontier: the part's subject. Open problems: a task battery with clinical-grade reliability; generalizable prediction; mechanistic validation of a computational target. Reading: Montague et al. 2012; Huys, Maia & Frank 2016; Hedge, Powell & Sumner 2018; Gillan et al. 2016; Browning et al. 2015; Rutledge et al. 2014; Drysdale et al. 2017, with Dinga et al. 2019; Chekroud et al. 2024; DeRubeis et al. 2014; Karvelis, Paulus & Diaconescu 2023.

Build the film

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

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

Build it
python -m videos.psychology.psych59.compute            # every number (a minute)
python tools/qa_scene.py psych59 Biotypes              # one chapter, silent, at 480p, with a contact sheet
EXPLAINER_TTS=silent python tools/build.py psych59 -q l   # the whole part, silent preview
python tools/build.py psych59                          # 1080p30 with narration
python tools/qa_scene.py psych59 Travel --lang zh      # the Chinese edition of one chapter
python tools/make.py psych59                           # both editions, with the checks a long build needs
python -m videos.psychology.labs 59                    # the lab: reliability, biotypes, prediction that travels
python tools/check_ledger.py psych59                   # every study shown has its Ledger row, or a reason
python -m pytest tests/psychology                      # Psyche's precision 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.