Machines that Learn
What does machine learning change in how economics is done?
Judges decide every day who waits for trial in jail; Kleinberg et al. trained an algorithm on 758,027 New York City decisions and estimated large gains, but outcomes are seen only for the released. On the Island's courts, a random forest ranks defendants better than judges who overweight the charge (18% fewer failures at their detention rate), the viewer detains three of ten, and the contraction design checks the gain with observed outcomes while filling in hidden ones flatters it; Meehl's 1954 claim is Called it? (right). Targeting a job programme by risk does worse than at random; double machine learning recovers an effect that linear controls and a plug-in learner miss; causal forests allocate places; prediction-powered inference corrects a classifier's measurement. After an intermission of transistor counts since 1971, a network learns Brock and Mirman's saving rule, Q-learners learn to price near monopoly, language models serve as pilots and assistants, a calibrated score makes unequal errors, a new Dial, and the frontier of when to defer.
What you need. Part 4: instruments and the judge design; Part 13: information; Part 20: the growth model; Part 44: algorithmic pricing; Part 54: estimation by simulation; Statistics, Built: forests, double ML, conformal and prediction-powered inference.
- Hook
- a judge, a defendant and an algorithm
- Ideas, models and mathematics
- prediction policy problems, double machine learning, heterogeneous effects, text and images as data, deep learning as a solution method, reinforcement learners as agents, language models as subjects, fairness
- Agora gains
- deep solvers and learning agents
- Play it
- judge or algorithm?
What you will be able to do
Principles and the major
- Tell a prediction policy problem from a causal one, with examples.
- Explain why outcomes hidden by a decision make algorithms hard to evaluate.
- Explain why a calibrated score can still make unequal errors across groups.
Graduate
- Evaluate a decision rule with the contraction design, and say what it can and cannot claim.
- Derive double machine learning's orthogonal score and explain cross-fitting.
- Do inference on a mean measured by a classifier with prediction-powered inference.
Research
- Train a neural network on Euler-equation errors and check it against a known solution.
- Estimate heterogeneous effects with a causal forest and learn a treatment rule.
- Prove Chouldechova's identity and state the impossibility it implies.
Practice
- Audit a deployed risk score: its label, its selective labels, and its errors by group.
Contents
Each chapter has a home level. Choose a track to see what to read and watch: Principles and the major 19 min · Graduate 24 min · Research 35 min · Practice 24 min.
- 0The judge's deskPrinciples and the major3 min
- 1Prediction policy problemsPrinciples and the major3 min
- 2Play it: ten casesPrinciples and the major2 min
- 3Selective labelsPrinciples and the major3 min
- 4Prediction is not causationPrinciples and the major2 min
- 5Double machine learningResearch3 min
- 6Heterogeneous effects and policy learningResearch2 min
- 7Text and images as dataPractice2 min
- Intermission: transistors, 1971-2021Principles and the major
- 8Deep learning as a solution methodResearch2 min
- 9Learning agentsResearch2 min
- 10Language models as subjectsPrinciples and the major1 min
- 11Language models as research assistantsPractice2 min
- 12FairnessPrinciples and the major3 min
- 13The Dials: algorithms against judgesResearch1 min
- 14In practice: credit, targeting, public servicesPractice1 min
- 15Frontier: foundation models for economic dataResearch2 min
- Recap, problems, and the road aheadAll tracks3 min
Also on this page: Lecture · Key results · Try it · Lab · Problems · Notes and sources · Build the film.
Lecture
The text of each chapter is the film's narration, as it is spoken, so you can read along or revise without the film. The pictures are in the film.
The judge's deskPrinciples and the major3 min
Every day, in courts across the United States, a judge looks at a person who has just been arrested and decides whether they will wait for their trial at home or in jail. The law asks the judge, in effect, to guess: will this person come back to court? Jon Kleinberg, Himabindu Lakkaraju, Jure Leskovec, Jens Ludwig and Sendhil Mullainathan took seven hundred and fifty-eight thousand such decisions in New York City, from 2008 to 2013, and trained an algorithm on the same records the judges had seen, to predict who would fail to appear. Releasing people in the order of its predictions, they estimated, could cut crime by up to a quarter with the same number jailed, or jail up to two fifths fewer people with no more crime.
That sounds like a triumph of prediction, and in part it is. But look at what the data contain. The Island's bail court sees a line of defendants. The judge releases most of them. For the released, we later see whether they came back to court: a tick, or a cross. For the detained, we see nothing. What they would have done is never recorded, and the judge may have detained them for reasons the records do not show. Any algorithm is trained, and judged, on the people the judges let go. The hard part is not the prediction. It is knowing what would have happened.
The question: what does machine learning change in how economics is done? When is a decision a prediction problem, and when a causal one? How can an algorithm be judged on outcomes the decision itself hid? Can machine learning estimate causal effects without fooling us? Can it solve our models, play in our markets, or stand in for the people we study? And what does it owe to fairness?
Economics, Built. Part sixty-four: machines that learn. Part sixty-three followed shocks along networks. This part turns to the machines that learn from data. By the end you will know which decisions are prediction problems, why the labels a decision hides make evaluation hard, and why a good forecast can be a bad policy; how double machine learning and causal forests estimate effects without letting the learner's errors leak in; how text and images become data, and how to do inference when the labels are predicted; how a neural network can solve an economic model, and what happens when learning agents set prices; and what language models can and cannot do for economists, and why no score can be fair in every sense at once.
What it does: Kleinberg et al.'s bail study; the Island's court and its hidden outcomes; the question; objectives
1Prediction policy problemsPrinciples and the major3 min
Most of economics asks causal questions. Jon Kleinberg, Jens Ludwig, Sendhil Mullainathan and Ziad Obermeyer pointed out that many policy decisions do not. A farmer wondering whether a rain dance brings rain needs a causal effect. A person deciding whether to take an umbrella needs only a forecast: the umbrella does not change the weather. Mullainathan and Jann Spiess put it as y-hat problems against beta-hat problems. Bail is an umbrella problem: the judge needs to know whether this person will come back. So is a hip replacement, whose benefit comes over years, for a patient who may not live that long. So are inspections: which restaurant, which building, which tax return. Each is a decision whose value turns on a prediction, and prediction is what machine learning does best.
The Island has bail courts too: 40,000 defendants, fifty judges, each case assigned at random. Split them in half: one half to learn from, the other to test on. The algorithm can learn only from the defendants the judges released, because only their outcomes are seen. It is a random forest: many decision trees, each grown on a resample, each split chosen to separate those who came back from those who did not, using age, prior arrests, missed court dates, the charge and whether the person has a job. On the test half, group defendants by their predicted risk, in tenths, and compare with the truth the simulation knows. The forest ranks them well, but it underestimates the riskiest tenth: it learned from the released, who were the less risky of their kind. Remember that for chapter three.
Called it? In 1954 the psychologist Paul Meehl reviewed every study he could find that pitted clinicians against simple statistical rules applied to the same facts, and concluded that the rules did as well or better. Experts are inconsistent, and they give weight to vivid details. In 2000 William Grove and colleagues pooled 136 such studies. The mechanical rule was about ten percent more accurate on average, much better in a third to nearly half of the studies, and much worse in a few. The verdict: right. With one caveat this part keeps returning to: the expert sometimes sees what the records do not.
What it does: Umbrellas and rain dances; the Island's forest; Called it?: Meehl
2Play it: ten casesPrinciples and the major2 min
Your turn. One morning in the Island's court, ten defendants, and room in the jail for three. You see what the judge's file shows: age, prior arrests, how many court dates they have missed before, the charge, and whether they have a job. The law asks one thing: who is least likely to come back to court? Remember that the charge is about the past, not about coming back. Which three would you detain?
Here is what lay behind the files. Under each defendant, the algorithm's predicted chance of failing to appear, what the judge did, and the true chance the Island knows. The algorithm detains A, C, D: the youngest, with the most missed court dates. On average, detaining them prevents 1.98 failures to appear. The judge detained C, E, J, 3 of them charged with violence, which on the Island says little about coming back: 1.02 failures prevented. The best possible three would prevent 1.98. How did your three do? Add up their true chances. The judge is not foolish: the charge is vivid, and the law cares about it in other ways. But for this one question, the record of missed dates is what predicts.
What it does: Detain three of ten; the algorithm against the judge
3Selective labelsPrinciples and the major3 min
Here is the choice the court faces, on the test half. The blue curve: detain the share of defendants with the highest predicted risk, and count the failures to appear among everyone else. Detain more, fewer failures. The pink points are the judges, grouped by how lenient they are, and the white point is all of them together: 28 percent detained, 8.4 failures per hundred defendants. At the judges' detention rate, the algorithm's ranking has 18 percent fewer failures. Or, for the judges' failure rate, it detains 30 percent fewer people. But this picture cheats. It uses what every detained defendant would have done if released, which the Island knows and no real court ever does.
The way round it is a design, not a model. Because cases go to judges at random, every judge sees the same kind of defendant. Take the most lenient fifth of the judges. Among the defendants they released, let the algorithm detain more, highest predicted risk first, until as many are detained as a stricter group of judges detained. Every failure among those still released was actually observed, because the lenient judges released them. This is the contraction design. Compare: at each stricter group's detention rate, the algorithm's contracted caseload has fewer failures than those judges' own, using no outcome that was never seen.
Why not simply fill in the missing outcomes with the algorithm's own predictions? That shortcut says the algorithm would see 6.3 failures per hundred at the judges' detention rate. The truth is 6.9. The gap comes from what the judges saw in court and the records do not: on the Island, a signal that the judges used and the algorithm cannot. The defendants they detained were riskier than their records suggest: 24 percent in truth, 16 percent by the model. So the shortcut flatters the algorithm. Kleinberg and his coauthors relied instead on the random assignment of judges, the instrument idea of Part four: lenient and strict judges see the same kind of defendant.
What it does: The policy frontier; the contraction design; why filling in flatters
4Prediction is not causationPrinciples and the major2 min
Prediction is the right tool when the decision does not change the outcome. Most policies are meant to change it. The Island has a job programme with places for a fifth of its unemployed. Who should get them? A natural answer: predict who is most likely to stay out of work, and start there. But look at the programme's effect, which the Island knows, by risk. People likely to find work anyway gain little. And people far from any job gain little too: a few weeks of training do not bridge that distance. The effect is largest in the middle. The most at risk are not the most helped.
Now give out the places four ways and count the people kept out of unemployment per hundred places. At random: 14. To the highest predicted risk: 7, worse than at random. To the people with the largest effect, as estimated by a causal forest from a randomized trial: 25. And to the largest true effect, which no one ever knows: 31. A perfect forecast of who will stay unemployed would not help here. Targeting needs effects, and effects need experiments, which chapter six returns to.
Even when prediction is the right tool, what you predict is a choice. Ziad Obermeyer, Brian Powers, Christine Vogeli and Sendhil Mullainathan studied an algorithm used by a large health system to pick patients for extra care. It predicted each patient's future medical costs. Costs are not needs. Less was spent on Black patients with the same illnesses, so at the same score they were sicker. Changing the label from costs to a measure of health would raise the share of Black patients among those flagged from 17.7 percent to 46.5. The algorithm predicted costs very well. It was the wrong target.
What it does: Targeting by risk against by effect; costs are not needs
5Double machine learningResearch3 min
Machine learning predicts; most of economics wants a causal effect. Can the two be combined? Take the partially linear model. The outcome is theta times a treatment, plus some function g of background variables; and the treatment itself depends on those variables through another function, m. Theta, here one, is what we want. g and m are nuisances: we do not care about them, but we must get them right enough. On the Island they are curved, with interactions and thresholds, and they share variables, so the treatment is confounded. Ordinary least squares with the controls entered linearly misses the curves, and the bias stays. Replacing g with a machine-learning fit, and regressing what is left of y on d, sounds like the fix. It is not, because the learner's own errors are correlated with d.
Draw 50 samples of 1,500 from the Island and estimate theta four ways. Each dot is one sample. With no controls: about 1.53, the confounding unchecked. With the controls entered linearly: 1.48, hardly better. With a machine-learning fit plugged in naively: 1.17, closer, and still clearly wrong. With double machine learning: 1.01, centred on the truth, and its ninety percent intervals cover the truth in 86 percent of samples.
Two ideas make it work. First, orthogonality. Partial the controls out of both the outcome and the treatment, then regress residual on residual, as Peter Robinson did for kernel estimators in 1988. The learners' errors then enter only as a product, so modest errors in each become a negligible error in theta. Second, cross-fitting: fit the learners on one part of the sample and use them on another, then swap, so a learner never grades its own homework. What it buys: any reasonably accurate learner for the nuisances, forests, boosting, the lasso or a network, and an ordinary standard error for theta. What it does not buy is a design. If a confounder is missing from X, double machine learning is exactly as biased as least squares.
What it does: Four estimators by Monte Carlo; orthogonality and cross-fitting
6Heterogeneous effects and policy learningResearch2 min
To target by effects, you have to estimate them, person by person, and they are never observed: nobody is both treated and untreated. In gold, the effect the Island knows, by risk. Start from a randomized trial: on the Island, 4,000 unemployed people, half given a place at random. Stefan Wager and Susan Athey's causal forest grows trees that split where the effect differs, not where the outcome does. And it is honest: one half of each tree's sample chooses the splits and the other half estimates the effect in each leaf, so the forest cannot fit its own noise. Averaged by risk, the forest's estimates follow the true hump, flattened at the edges where data are thin.
Now the allocation, for every size of programme. Places at random: the gain grows in proportion. By risk: less than at random until a third of the unemployed have places. By the forest's estimated effect: close to the best possible, which uses the true effects. Choosing a rule this way is policy learning, after Toru Kitagawa and Aleksey Tetenov and after Athey and Wager: pick, from a class of simple rules, the one with the largest estimated gain, and bound how much worse than the best it can be. Simple rules matter: a programme officer has to be able to apply them, and a citizen to understand them.
What it does: A causal forest; allocation curves
7Text and images as dataPractice2 min
Much of what economists care about was never written down as a number. It sits in newspapers, meeting minutes, company filings and reviews; the words can be counted, or turned into vectors that place similar meanings near each other; a model trained on a few hundred documents labelled by hand can then label millions. Matthew Gentzkow, Bryan Kelly and Matt Taddy surveyed the methods: measures of policy uncertainty, of a central bank's tone, of the risks firms say they face, of politicians' slant. Images work the same way. Neal Jean and coauthors trained a network on satellite pictures to predict consumption in villages in five African countries, explaining up to three quarters of its variation, where surveys are rare.
But a predicted label is a measurement with error, and the error does not average away. On the Island, 20,000 news articles, 12 percent about layoffs. A good classifier catches 90 percent of them and wrongly flags 4 percent of the rest. Its estimate of the share is 14.3 percent, every time, with a confident interval that never covers the truth. Labelling a random four hundred by hand is unbiased, but noisy: plus or minus 2.7 points. Prediction-powered inference, from Anastasios Angelopoulos and colleagues, uses both: the classifier's share on everything, corrected by its average error on the hand-labelled four hundred. Unbiased, covering the truth 90 percent of the time, and a third narrower than the hand labels alone. The same idea works for regressions whose outcome is a prediction.
What it does: From documents to measures; prediction-powered inference
Intermission: transistors, 1971-2021Principles and the major
This chapter has no narration to read.
8Deep learning as a solution methodResearch2 min
Machine learning can also solve models. Take Part twenty's growth model in its simplest form: log utility, capital that wears out in a year. Each year output, k to the alpha, is split between consumption and next year's capital, by a saving rate s that may depend on k. The optimal rule satisfies the Euler equation at every k. So represent s by a small neural network, capital in, a saving rate out, and train it to make the Euler equation hold on sixty-four capital stocks, with the series' own automatic differentiation computing the gradients. William Brock and Leonard Mirman found the answer by hand in 1972: save alpha times beta, 0.3135, whatever k is. The network does not know that.
Train it. On the left, the squared Euler error, falling by seven orders of magnitude. On the right, the rule the network has learned, at the start, after fifty steps, after two hundred, and at the end, against Brock and Mirman's answer in gold. The learned rule is flat at alpha times beta, within 0.00003 everywhere on the grid. The network found the closed form without being told it.
Why do this when a grid would do? Because a grid needs a point for every combination of states, and the count explodes: ten state variables with ten points each is ten billion points. A network's cost grows far more slowly. That reaches the economies of Part fifty-two, with many kinds of household, portfolios and several shocks: Marlon Azinovic, Luca Gaegauf and Simon Scheidegger's deep equilibrium nets, and the methods of Lilia and Serguei Maliar and Pablo Winant. The checks are the old ones: Euler errors off the training points, simulated paths, and a case with a known answer, like this one. The risks are new: no guarantee of the global optimum, and errors that hide where the economy rarely goes.
What it does: A network learns Brock and Mirman's rule; why it scales
9Learning agentsResearch2 min
Part forty-four put two learning algorithms in charge of prices. Here they are again, in 8 sessions. Each is a Q-learner: it tries prices, keeps a table of how well each did after each pair of last prices, and slowly stops experimenting. They never communicate. In almost every session they settle well above the competitive price, most of the way to monopoly: a profit gain of 0.78 on average. Emilio Calvano, Giacomo Calzolari, Vincenzo Denicolò and Sergio Pastorello showed why: the learned strategies punish a rival who undercuts, so undercutting does not pay. Nobody programmed collusion; it was learned. Whether the law can reach it is Part forty-four's open question.
Learning agents are also a laboratory. Stephan Zheng and coauthors' AI Economist trains a planner to choose a tax schedule while the simulated workers it taxes learn how much to work, build and trade. No closed form is needed, the agents can be as rich as the simulation allows, and the planner adapts to how they respond. The caution: the agents learn what the simulation rewards. Real people bring habits and rules of thumb, Part forty-five's biases, and politics, that no simulation was trained on. So it is a laboratory for mechanisms, beside theory and experiments, not a replacement for either.
What it does: Q-learning price setters; the AI Economist
10Language models as subjectsPrinciples and the major1 min
Language models answer questions the way people write about them. John Horton asked whether they could serve as simulated subjects, homo silicus. Give the model a persona, a renter, a libertarian, a retiree, put a classic question to it, vary the endowment, the price or the framing, and compare its choices with what people did. The simulated subjects reproduced the direction of several classic results: social preferences in simple games, judgements about whether a price rise is fair, and a preference for the status quo. Used this way, a model is a cheap pilot: which treatments are worth running on people, how a question reads, where effects might be.
And what it cannot replace. It may have read the answer: the classic experiments are in its training text, so reproducing them may be memory rather than behaviour. Nothing is at stake for it: no money, no effort, no embarrassment, which are what make behaviour in a laboratory real. Its average answer reflects the text it learned from, not any population an economist could sample. And small changes in wording, or a new version of the model, can move the answers a lot. So: report the prompts and versions, and check against people before believing anything new.
What it does: Homo silicus; what it cannot replace
11Language models as research assistantsPractice2 min
Machine learning can also help find what to test. Jens Ludwig and Sendhil Mullainathan returned to judges, in Mecklenburg County, North Carolina. They took defendants' mugshots and the judges' decisions, and trained a network to predict the decision from the face alone. It predicted well: something in faces moves judges. But a network's reasons are opaque, so they generated morphed faces that moved its prediction up or down, and asked people what had changed. Two answers stood out: how well-groomed the person looked, and how heavy-faced. Neither was on any list of things judges were thought to respond to; each became a hypothesis, tested on new data. The face predicted the judge, not the defendant: that is a finding about judges. The algorithm proposes, people name the idea, and a fresh sample tests it.
Language models now sit in many research workflows. In measurement: coding open-ended survey answers, job advertisements, minutes and filings into categories, at the scale of chapter seven. In the craft: writing and checking code, cleaning data, reading a literature faster. The rule is chapter seven's: validate against hand-labelled data, correct the estimates with prediction-powered inference, and report the model and the prompts, so others can check. And the limit: a model trained on past text proposes what is likely. What is surprising still needs a research design and data.
What it does: Mugshots and hypotheses; the workflow and its rule
12FairnessPrinciples and the major3 min
In 2016 the newsroom ProPublica studied a commercial risk score used for more than ten thousand defendants in Broward County, Florida. Among defendants who did not go on to reoffend, Black defendants had been labelled higher risk forty-five percent of the time, white defendants twenty-three percent. The company replied that at each score, Black and white defendants reoffended at about the same rate: the score meant the same thing for both. Both were true. When two groups have different rates of the outcome, no score can satisfy both definitions of fairness at once.
The Island shows why with the best score possible: each defendant's true risk. Two groups: in A, 24 percent would fail to appear; in B, 37 percent, perhaps because B's neighbourhoods are policed more heavily, so its records are longer. Detain anyone whose score is above 0.3. The score is perfectly calibrated: at every level, the share who fail is the same in both groups. Now the errors. Of those who would have come back, 22 percent of group A are detained, and 48 percent of group B. Of those who would not, 48 percent of A are released, and 22 percent of B. A perfectly accurate, perfectly calibrated score, and the errors still fall differently on the two groups.
Alexandra Chouldechova wrote the reason in one line. The false positive rate equals the odds of the outcome in the group, times a term in the positive predictive value, times one minus the false negative rate. If two groups differ in their base rates and the score means the same thing in both, the error rates must differ. Jon Kleinberg, Sendhil Mullainathan and Manish Raghavan proved the general version: calibration and equal error rates for both kinds of error cannot hold together, except with equal base rates or perfect prediction. Which errors matter more, a wrongful detention or a missed court date, is a value judgement. Economics can price the trade-off and show who bears it; it cannot settle it. And the base rates themselves may carry the history of how each group was policed.
What it does: COMPAS; the Island's calibrated score; Chouldechova's identity
13The Dials: algorithms against judgesResearch1 min
This part opens one Dial: how much an algorithm's ranking adds to a judge's decision, measured as the fall in the outcome the decision is meant to prevent, at the same detention rate. Kleinberg and his coauthors in New York City: up to 0.25, about a quarter. The Island, where the truth is known: 0.18. And the Island again, by the contraction design, using only outcomes that were seen: 0.15 to 0.17, a little below the truth, because contraction can only detain more of the lenient judges' released, not release anyone they jailed. The status: depends on the setting. Where the decision is a prediction and the records carry most of the signal, the gains are large. Where the judge sees what the records do not, they shrink, and only a design that copes with selective labels can tell.
What it does: What an algorithm adds to a judge (new)
14In practice: credit, targeting, public servicesPractice1 min
Where is this used? In credit: lenders score borrowers with machine learning. Andreas Fuster and coauthors showed that better prediction changes who gets a mortgage and at what price, and not in the same direction for every group. In targeting: proxy means tests that decide who receives a cash transfer, and outreach for programmes, where chapter four's lesson applies: rank by effect, not by risk. In public services: inspections, tax audits, screening of calls to child-welfare agencies, all prediction policy problems, all with selective labels. And on the platforms of Part sixty-one, the largest users of all.
And three cautions this part teaches. Ask what the decision hides: outcomes exist only where the decision allowed them, so evaluate with a design, not by filling in. Ask what is being predicted: costs are not needs, and risk is not benefit; choosing the label is a policy choice. And a prediction is a measurement: it carries its error into whatever is built on it, so correct for it, validate it, and report how it was made.
What it does: Credit, targeting, public services; three cautions
15Frontier: foundation models for economic dataResearch2 min
The frontier begins where this part's hook ended: the judge sees things the records do not. Rerun the Island's courts with the courtroom signal made weaker or stronger. If judges see nothing extra, the algorithm prevents 24 percent of failures at their detention rate; at this part's setting, 18. As the signal grows, the advantage shrinks, and then reverses: when the judge sees enough, ranking by the records alone makes things worse. So the research question is not machine against human but how to combine them: which cases to hand over, when a person should defer, and why, in experiments with doctors and other experts, people often weigh the machine's advice badly.
What remains open? Foundation models for economic data: networks pretrained on millions of firms' accounts, prices or job histories, then tuned to a question, the way language models are tuned to a task. Automated structural estimation: networks that learn, by simulation, the map from data to a model's parameters, as Part fifty-four's amortized estimator did, for models too slow to estimate any other way. Agents in markets: pricing, bidding and negotiating algorithms that learn from each other, and what competition policy owes them. And the old questions, which no amount of data removes: what would have happened otherwise, and who decided what was measured.
What it does: When to defer; foundation models; automated estimation
Recap, problems, and the road aheadAll tracks3 min
So: what does machine learning change in how economics is done? It makes prediction cheap, and so separates the questions that need only a forecast from those that need a cause. For the first, it can beat experts, if the outcomes the decision hid are handled by design. For the second, it helps only inside a design: double machine learning, causal forests, corrected measurements. It can solve our models, act in our markets and propose hypotheses. It cannot tell us what would have happened, or which errors matter more.
Part sixty-four in twelve lines. Some decisions need only a forecast. Judges weigh vivid facts; algorithms weigh predictive ones. Ranking by a model can prevent more failures, or jail fewer people. The outcomes a decision hides need a design, not a guess. The most at risk are not always the most helped. Double machine learning keeps the learner's errors out of the effect. Causal forests find who gains, and policy learning allocates. A predicted label is a measurement, and can be corrected. Networks can solve models. Learning agents can learn to collude. Language models are pilots and assistants, not people. And no score is fair in every sense at once.
The problems: when ranking by risk is optimal; why filling in hidden outcomes misleads; double machine learning's product of errors; the variance of prediction-powered inference; Brock and Mirman's saving rate; and a starred problem deriving Chouldechova's identity. Full solutions are in the part's notes.
The reading: Susan Athey and Guido Imbens on the machine-learning methods economists should know; Mullainathan and Spiess's applied econometric approach; and Hastie, Tibshirani and Friedman's Elements of Statistical Learning. Then the papers, from Meehl to the language models.
Next time, from machines that help economists to machines that change the economy. In 1930, in the first year of the Depression, John Maynard Keynes wrote an essay for his grandchildren. In a hundred years, he said, the standard of living would be four to eight times higher, and the working week fifteen hours. He was right about the first. The hundred years are up in 2030. The task model, the experiments with AI at work, wages and the labour share, and growth when ideas can be automated. Part sixty-five: the economics of AI.
Where it goes next. Part 65 turns from machines that help economists to machines that change the economy: automation, work and growth.
Key results
The part's results in one place, for revision.
Try it
Lab 64 · Machines that learn
Train a model on the decisions of the Island's judges, evaluate it without the outcomes they hid, and use machine learning for causal effects, measurement, model solving and markets, with the truth known.
python -m videos.economics.labs 64
needs numpy, scipy, matplotlib · download lab64.py ·
source on GitHubthe courts: judges' detention and failures per 100; the forest's failures at the same detention 28%, 8.4; 6.9 (18% fewer)
contraction: the algorithm against stricter judges (failures per 100) 5.1 vs 6.1, 5.8 vs 6.9, 7.0 vs 8.3, 8.1 vs 9.5
filling in the detained's outcomes: naive against true failures per 100 6.3 against 6.9
a job programme, unemployment averted per 100 places: random, by risk, by estimated effect, best 13.7, 6.6, 24.8, 31.3
double ML over 8 samples: no controls, linear controls, plug-in, double ML (truth 1) 1.55, 1.50, 1.19, 1.02
the share of layoff news (truth 12%): classifier; hand labels and PPI with their interval widths 14.3%; 5.3 and 3.6 points
the Euler network's saving rate against alpha beta largest gap 0.00003
Q-learning price setters: profit gain in three sessions (0 Nash, 1 monopoly) 0.82, 0.87, 0.81
a calibrated score, two groups: false positive and false negative rates A 22% and 48%, B 48% and 22%
the algorithm's advantage as the judges see more (signal 0, 0.9, 1.8) +26%, -0%, -46%
transistors per microprocessor: doubling time, 1971-2021 1.98 years
The forest predicts; the designs (random judges, contraction, trials, cross-fitting, a hand-labelled sample) are what make its predictions answer questions.
The code (78 lines; it asserts its own result)
"""Lab 64: machines that learn: the Island's bail courts with a random forest, the policy frontier, contraction and
selective labels, targeting by risk against by effect, double machine learning, prediction-powered inference, a neural
network trained on Euler errors, pricing agents, fairness by group, and the value of what the judge can see."""
import numpy as np
from videos.coursekit import labs
from explainer.economics import data
from explainer.economics.agora import learn as L
TITLE = "Machines that learn"
GOAL = ("Train a model on the decisions of the Island's judges, evaluate it without the outcomes they hid, and use "
"machine learning for causal effects, measurement, model solving and markets, with the truth known.")
TASKS = [
"Make the judges see more in court (L.courts(signal=1.2)). Does the algorithm still beat them, and does the "
"contraction design notice?",
"Use a weaker classifier (L.text_measure(sens=0.7, spec=0.9)). How much narrower is prediction-powered inference "
"than the hand labels now?",
"Raise the discount factor in the Euler network (L.euler_net(beta=0.99)). Does it still find alpha beta?",
]
def run(seed=0):
lab = labs.Lab()
C = L.courts(seed=64 + seed)
P = L.policy_curves(C)
lab.row("the courts: judges' detention and failures per 100; the forest's failures at the same detention",
f"{100 * P['judges']['detain']:.0f}%, {100 * P['judges']['crime']:.1f}; {100 * P['alg_at_judges']:.1f} "
f"({100 * P['crime_cut']:.0f}% fewer)")
K = L.contraction(C)
lab.row("contraction: the algorithm against stricter judges (failures per 100)",
", ".join(f"{100 * r['algorithm']:.1f} vs {100 * r['judges']:.1f}" for r in K["rows"]))
lab.row("filling in the detained's outcomes: naive against true failures per 100",
f"{100 * K['naive']:.1f} against {100 * K['truth']:.1f}")
T = L.targeting(seed=64 + seed)
lab.row("a job programme, unemployment averted per 100 places: random, by risk, by estimated effect, best",
", ".join(f"{T['per100'][k]:.1f}" for k in ("at random", "highest risk", "largest effect (estimated)",
"largest effect (truth)")))
D = L.dml_study(reps=8, seed=64 + seed)
lab.row("double ML over 8 samples: no controls, linear controls, plug-in, double ML (truth 1)",
", ".join(f"{D[k]['mean']:.2f}" for k in ("no controls", "linear controls", "plug-in ML", "double ML")))
X = L.text_measure(reps=200, seed=64 + seed)
lab.row("the share of layoff news (truth 12%): classifier; hand labels and PPI with their interval widths",
f"{100 * X['classifier']['mean']:.1f}%; {100 * X['hand-labelled']['width']:.1f} and "
f"{100 * X['prediction-powered']['width']:.1f} points")
E = L.euler_net(seed=64 + seed)
assert E["max_err"] < 0.01 # Brock and Mirman's closed form, found
lab.row("the Euler network's saving rate against alpha beta", f"largest gap {E['max_err']:.5f}")
A = L.pricing_agents(sessions=3, seed=seed)
lab.row("Q-learning price setters: profit gain in three sessions (0 Nash, 1 monopoly)",
", ".join(f"{r['gain']:.2f}" for r in A["rows"]))
F = L.fairness()
lab.row("a calibrated score, two groups: false positive and false negative rates",
f"A {100 * F['A']['fpr']:.0f}% and {100 * F['A']['fnr']:.0f}%, B {100 * F['B']['fpr']:.0f}% and "
f"{100 * F['B']['fnr']:.0f}%")
S = L.signal_sweep(signals=(0.0, 0.9, 1.8), n=20000, trees=40, seed=64 + seed)
lab.row("the algorithm's advantage as the judges see more (signal 0, 0.9, 1.8)",
", ".join(f"{100 * r['crime_cut']:+.0f}%" for r in S["rows"]))
t = data.transistors()
b = np.polyfit(t["year"], np.log2(t["transistors"]), 1)[0]
lab.row("transistors per microprocessor: doubling time, 1971-2021", f"{1 / b:.2f} years")
lab.note = ("The forest predicts; the designs (random judges, contraction, trials, cross-fitting, a hand-labelled "
"sample) are what make its predictions answer questions.")
fig, ax = labs.figure(2, size=(11, 4.4))
ax[0].plot(100 * np.array(P["grid"]), 100 * np.array(P["crime"]), color="tab:blue", label="algorithm")
ax[0].scatter([100 * q["detain"] for q in P["quintiles"]], [100 * q["crime"] for q in P["quintiles"]],
color=labs.ORANGE, label="judges by leniency")
ax[0].set(title="the bail frontier", xlabel="share detained, %", ylabel="failures per 100")
ax[0].legend(fontsize=8)
for k, col in (("linear controls", labs.ORANGE), ("double ML", "tab:green")):
ax[1].hist(D[k]["draws"], bins=8, alpha=0.7, color=col, label=k)
ax[1].axvline(1.0, color="k", ls="--", lw=1)
ax[1].set(title="double machine learning", xlabel="estimate of theta (truth 1)", ylabel="samples")
ax[1].legend(fontsize=8)
lab.fig = fig
return lab
Now change it
- Make the judges see more in court (L.courts(signal=1.2)). Does the algorithm still beat them, and does the contraction design notice?
- Use a weaker classifier (L.text_measure(sens=0.7, spec=0.9)). How much narrower is prediction-powered inference than the hand labels now?
- Raise the discount factor in the Euler network (L.euler_net(beta=0.99)). Does it still find alpha beta?
Problems, with solutions
Try each problem before opening its solution.
1. Prediction policy: a programme helps only people who would otherwise fail, by a fixed amount; show that ranking by the chance of failing is then optimal, and give an example where it is not.
Solution
If the benefit to person i is b times the chance p_i that they would fail without the programme, the total benefit of treating a set S is b times the sum of p_i over S, which a fixed number of places maximizes by taking the largest p_i. Ranking by risk is optimal. It fails whenever the benefit is not proportional to risk: in this part's job programme the effect is small for those who would find work anyway and for those far from any job, so the highest risks gain least, and ranking by risk does worse than at random for small programmes.
2. Selective labels: if judges detain on a signal s that raises risk and the model omits it, show that filling in the detained's outcomes with the model's prediction understates their failures.
Solution
The model estimates E[y | x] from the released, among whom s is lower than average for each x, because judges release those with low s: E[y | x, released] < E[y | x]. Among the detained s is higher than average, so their true rate E[y | x, detained] exceeds E[y | x], which exceeds what the model learned. Filling in with the model's prediction therefore understates the detained's failures, and any policy that would release some of them looks better than it is.
3. Double ML: in y = theta d + g(X) + e, d = m(X) + v, show that the residual-on-residual estimator's error depends on (m-hat - m)(l-hat - l) to first order, where l(X) = E[y | X].
Solution
Write y - l(X) = theta v + e and d - m(X) = v. With estimates, y - l-hat = theta v + e + (l - l-hat) and d - m-hat = v + (m - m-hat). The estimator's numerator is the sum of (v + dm)(theta v + e + dl), with dm = m - m-hat and dl = l - l-hat; its denominator the sum of (v + dm)^2. Expanding, the terms linear in dm or dl are multiplied by v or e, which have mean zero given X and (with cross-fitting) are independent of the errors, so they vanish in expectation and average out at rate 1/sqrt(n); what remains is the sum of dm dl, the product of the two errors, plus theta times the sum of dm^2 in the denominator's correction, both second order. So errors of order n^(-1/4) in each learner are enough.
4. Prediction-powered inference: show that f-bar_N + mean(y - f)_n is unbiased for the mean of y, and find its variance.
Solution
With the n labelled items a random sample, E[mean(y - f)_n] = E[y] - E[f], and E[f-bar_N] = E[f], so the sum has expectation E[y]. Its variance is Var(f)/N + Var(y - f)/n (the two samples are independent when the labelled items are excluded from the N). When the classifier is good, Var(y - f) is much smaller than Var(y), so the estimator beats the hand labels' Var(y)/n; when it is poor, it can do worse, which PPI++'s tuned weight on f avoids.
5. Brock and Mirman: with log utility and full depreciation, guess k' = s k^alpha and verify that s = alpha beta solves the Euler equation.
Solution
With c = (1 - s) k^alpha and k' = s k^alpha, next period c' = (1 - s) k'^alpha. The Euler equation 1/c = beta alpha k'^(alpha - 1)/c' becomes 1/((1 - s) k^alpha) = beta alpha k'^(alpha - 1)/((1 - s) k'^alpha) = beta alpha/((1 - s) k'), so k' = beta alpha k^alpha, that is s = alpha beta, whatever k.
6. Chouldechova: derive FPR = p/(1 - p) (1 - PPV)/PPV (1 - FNR), and show that equal PPV and unequal base rates force unequal error rates.
Solution
Let N be the group's size, p its base rate. True positives are TP = (1 - FNR) p N; false positives FP = FPR (1 - p) N. PPV = TP/(TP + FP), so FP = TP (1 - PPV)/PPV. Substituting, FPR (1 - p) N = (1 - FNR) p N (1 - PPV)/PPV, which is the identity. If two groups have the same PPV and the same FNR but different p, the factor p/(1 - p) differs, so their FPRs differ; to equalize the FPRs, the FNRs or the PPVs must differ instead.
Notes and sources
Sources
The studies the film states are listed with what each shows in dials.SHOWN[64]; the new Dial (what an algorithm
adds to a judge's decision) is in explainer/economics/dials.py, and the Called it? record of Meehl's clinical
against statistical prediction in explainer/economics/calls.py. The methods are stated from the works cited in the
chapters (Meehl 1954, Brock and Mirman 1972, Robinson 1988, Grove et al. 2000, Kleinberg, Ludwig, Mullainathan and
Obermeyer 2015, Jean et al. 2016, Angwin et al. 2016, Lakkaraju et al. 2017, Mullainathan and Spiess 2017,
Chouldechova 2017, Kleinberg, Mullainathan and Raghavan 2017, Kleinberg et al. 2018, Chernozhukov et al. 2018, Wager
and Athey 2018, Kitagawa and Tetenov 2018, Gentzkow, Kelly and Taddy 2019, Obermeyer et al. 2019, Calvano et al. 2020,
Athey and Wager 2021, Maliar, Maliar and Winant 2021, Azinovic, Gaegauf and Scheidegger 2022, Fuster et al. 2022, Zheng
et al. 2022, Angelopoulos et al. 2023, Horton 2023, Ludwig and Mullainathan 2024) and computed here.
About this partfrom its README
Part 64 of a sixty-eight-part course in economics (see the series plan and the syllabus), the second of Act XII, The Frontier. It asks what machine learning changes in how economics is done. Its answer: it makes prediction cheap, and so separates the questions that need only a forecast from those that need a cause. For the first it can beat experts, if the outcomes a decision hid are handled by design; for the second it helps only inside a design (double machine learning, causal forests, corrected measurements). It can solve models, act in markets and propose hypotheses; it cannot say what would have happened, or which errors matter more.
It opens at the judge's desk: Kleinberg, Lakkaraju, Leskovec, Ludwig and Mullainathan trained boosted trees on 758,027 New York City bail decisions (2008-13) and estimated that releasing in the algorithm's order could cut crime by up to a quarter with the same number jailed, or jail up to two fifths fewer with no more crime; the hard part is that outcomes are seen only for the released. The Island's bail court shows the same in miniature. From there it covers:
- prediction policy problems (the umbrella and the rain dance; Kleinberg, Ludwig, Mullainathan and Obermeyer; Mullainathan and Spiess); the Island's 40,000 defendants, fifty judges and a random forest trained on the released; Called it?: Meehl's clinical against statistical prediction (right; Grove et al.'s 136 studies);
- Play it: ten defendants and three cells (the algorithm detains the young with missed court dates, preventing 1.98 failures on average; the judge detained the three violent charges, 1.02; the best possible, 1.98);
- selective labels: on the test half, ranking by the forest gives 18% fewer failures at the judges' detention rate, or 30% fewer detained at their failure rate (with outcomes only the simulation knows); the contraction design recovers a 15-16% gain from observed outcomes alone; filling in the detained's outcomes with predictions says 6.3 failures per hundred against a truth of 6.9, because judges saw a courtroom signal the records lack;
- prediction is not causation: a job programme whose effect peaks in the middle of the risk range; per 100 places, 6.6 kept out of unemployment by risk, 13.7 at random, 24.8 by a causal forest's estimated effect, 31.3 at best; Obermeyer et al.'s algorithm that predicted costs rather than needs (17.7% to 46.5%);
- double machine learning (Chernozhukov et al.; Robinson): fifty samples of 1,500 with nonlinear confounding; no controls 1.53, linear controls 1.48, a plug-in learner 1.17, cross-fitted double ML 1.01 against a truth of 1, its 90% intervals covering 86% of the time;
- heterogeneous effects and policy learning: a causal forest on a trial of 4,000 (Wager and Athey; Athey and Wager; Kitagawa and Tetenov);
- text and images as data (Gentzkow, Kelly and Taddy; Jean et al.'s satellites); a classifier's estimate of the share of layoff news is 14.3% against 12%, and prediction-powered inference (Angelopoulos et al.) is unbiased and a third narrower than 400 hand labels;
- an intermission: transistors on the largest microprocessor, 1971-2021, doubling about every two years;
- deep learning as a solution method: a network trained on Euler errors learns Brock and Mirman's saving rate alpha beta to within 0.0001; deep equilibrium nets;
- learning agents: Part 44's Q-learners settle 78% of the way from competition to monopoly (Calvano et al.); the AI Economist;
- language models as subjects (Horton's homo silicus) and as research assistants (Ludwig and Mullainathan's mugshots; validation by prediction-powered inference);
- fairness: ProPublica's 45% and 23%, the vendor's calibration reply; on the Island, a perfectly calibrated score wrongly detains 22% of group A and 48% of group B; Chouldechova's identity and Kleinberg, Mullainathan and Raghavan's impossibility;
- the Dial (what an algorithm adds to a judge's decision, new), the jobs that use these methods, and the frontier: the algorithm's advantage falls from 24% to minus 52% as the judge's private signal grows; foundation models for economic data and automated structural estimation.
What is computed and built
Everything plotted is computed by compute.py with Agora's learn module (explainer.economics.agora.learn), over
statkit's forests, boosting, causal forest and PPI and the series' automatic differentiation; the narration states the
cached numbers.
- The courts. 40,000 defendants: age 18-60, prior arrests Poisson with a mean falling with age, past missed dates binomial on priors, four charges, a job; a courtroom signal s ~ N(0, 1); the chance of failing to appear is logistic in log(1 + priors), missed dates, youth and its interaction with priors, a job, the charge (drugs up, violence down) and 0.45 s. Fifty judges with release rates 55-88%, cases assigned at random; each ranks by priors, missed dates, the charge (overweighted), a job, 0.45 s and noise of s.d. 0.7. A random forest (80 trees, leaves of 40) is trained on the released half of the training half and scores the test half.
- Contraction. The most lenient fifth of judges' test cases; the forest detains more of their released until each stricter fifth's detention rate; failures counted only among the observed.
- Targeting. 20,000 unemployed with five characteristics; the chance of staying unemployed logistic in three of them; the programme's effect 0.3 exp(-((p0 - 0.5)/0.25)^2) (1 + 0.4 tanh x4); a trial of 4,000 with a causal forest (100 honest trees).
- Double ML. n = 1,500, five covariates, m and g with tanh, sine, an interaction and thresholds; gradient boosting (250 trees of depth 3) for the nuisances; three folds; fifty samples.
- Text. 20,000 articles, 12% about layoffs; a classifier with sensitivity 0.90 and specificity 0.96; 400 hand labels; 500 corpora.
- The Euler net. alpha = 0.33, beta = 0.95; one hidden layer of 12 tanh units, a sigmoid output; 64 capital stocks from 0.2 to 2.5 times the steady state; Adam, 3,000 steps.
- Agents. Part 44's logit Bertrand game, 15 prices, exploration decaying at 2e-5 a period, eight sessions.
- Fairness. Two groups of 200,000 with normal risk indices centred 0.7 apart; the score is the true risk; detention above 0.3.
- The sweep. The courts with the signal's weight in both risk and the judges' index from 0 to 1.8.
- The intermission. Rupp's transistor counts, 1971-2021; the doubling time by least squares on log2.
Chapter notes
| # | Chapter | What it does |
|---|---|---|
| 0 | The judge's desk | Kleinberg et al.'s bail study; the Island's court and its hidden outcomes; the question; objectives |
| 1 | Prediction policy problems | Umbrellas and rain dances; the Island's forest; Called it?: Meehl |
| 2 | Play it: ten cases | Detain three of ten; the algorithm against the judge |
| 3 | Selective labels | The policy frontier; the contraction design; why filling in flatters |
| 4 | Prediction is not causation | Targeting by risk against by effect; costs are not needs |
| 5 | Double machine learning | Four estimators by Monte Carlo; orthogonality and cross-fitting |
| 6 | Heterogeneous effects and policy learning | A causal forest; allocation curves |
| 7 | Text and images as data | From documents to measures; prediction-powered inference |
| — | Intermission | Transistors per microprocessor since 1971, as a line and a tune |
| 8 | Deep learning as a solution method | A network learns Brock and Mirman's rule; why it scales |
| 9 | Learning agents | Q-learning price setters; the AI Economist |
| 10 | Language models as subjects | Homo silicus; what it cannot replace |
| 11 | Language models as research assistants | Mugshots and hypotheses; the workflow and its rule |
| 12 | Fairness | COMPAS; the Island's calibrated score; Chouldechova's identity |
| 13 | The Dials | What an algorithm adds to a judge (new) |
| 14 | In practice | Credit, targeting, public services; three cautions |
| 15 | Frontier | When to defer; foundation models; automated estimation |
| — | Outro | The answer; twelve lines; problems; reading; next, Part 65, The Economics of AI |
Notes
python -m videos.economics.labs 64: the courts and their frontier; contraction and the naive evaluation; targeting by risk and by effect; double ML against OLS; PPI; the Euler network; pricing agents; fairness by group; the signal sweep; Moore's law on the Data Room's data.- The interactive (course site): bail. The reader sets how much the judges see that the records do not, how much they overweight the charge, and how strict they are, and compares their failures with the algorithm's along the whole frontier.
Companion material in this repository
The syllabus's plan for this partfrom SYLLABUS.md, the plan of record
- Hook: the judge's desk; the question; objectives.
- Prediction policy problems (Kleinberg et al. 2015): rain dances against umbrellas.
- Play it: ten cases, the same facts the judge saw: detain or release? Then the algorithm's ranking.
- The selective-labels problem and the judge-leniency design; what the comparison can claim.
- Prediction is not causation: where a good forecast gives a bad policy.
- Double machine learning (Chernozhukov et al. 2018): nuisance functions, orthogonal scores, cross-fitting (Statistics, Built 36, 49).
- Heterogeneous effects: causal forests (Wager and Athey 2018); policy learning (Athey and Wager 2021).
- Text and images as data: embeddings as covariates and as outcomes (Gentzkow, Kelly and Taddy 2019); satellite poverty maps (Jean et al. 2016).
- Deep learning as a solution method: the policy function as a network, trained on Euler errors (Maliar, Maliar and Winant 2021; Azinovic, Gaegauf and Scheidegger 2022). Part 52 solved again.
- Learning agents in models: reinforcement learners that set prices (Part 44), taxes (the AI Economist, Zheng et al. 2022) and bids.
- Language models as subjects: homo silicus (Horton 2023); what simulated respondents can and cannot replace.
- Language models as research assistants: measurement, coding, hypothesis generation (Ludwig and Mullainathan 2024); the validity questions.
- Fairness (Part 39): impossibility results; discrimination by proxies; what regulators can audit.
- Dials. 14. In practice: Part 61; credit scoring, public-sector targeting. 15. Frontier: foundation models for economic data; automated structural estimation.
Agora: learn: deep solvers for the Part 22 and Part 52 economies on explainer.ai.autodiff; Q-learning and
policy-gradient agents; a double-ML wrapper over statkit; a language-model subject harness (optional, cached).
Called it? the algorithm against the judges, and against later deployments.
Reading: Kleinberg et al. 2015, 2018; Mullainathan & Spiess 2017; Athey & Imbens 2019; Chernozhukov et al.
2018; Wager & Athey 2018; Gentzkow, Kelly & Taddy 2019; Maliar, Maliar & Winant 2021; Horton 2023; Ludwig &
Mullainathan 2024.
Build the film
python -m videos.economics.econ64.compute # the part's numbers, into .cache/econ64
python tools/build.py econ64 # render and assemble the film
EXPLAINER_TTS=silent python tools/qa_scene.py econ64 Hook # one chapter, silent, with a contact sheet
Scenes: videos/economics/econ64. Setup: see the course page. Source of these notes: the README and the scenes' narration.
Build it
python -m videos.economics.econ64.compute # every number (about five minutes), into .cache/econ64/
python tools/qa_scene.py econ64 Labels # one chapter, silent, at 480p, with a contact sheet
EXPLAINER_TTS=silent python tools/build.py econ64 -q l # the whole part, silent preview
python tools/build.py econ64 # 1080p30 with narration and the series' computed score
python -m videos.economics.labs 64 # the lab
The data are Rupp's microprocessor trend data via Our World in Data, registered in
SOURCES.md. Everything else is computed on the Island, or stated
from the papers listed in dials.SHOWN[64].