Each day's miss is divided by the noise expected on that day, so big days don't drown small ones.
Epidemic ModelingData and inference
Module 8Parameter estimation and calibration
Fitting models to data, and knowing when you can't. On one simulated outbreak with a known truth, we fit by least squares (and see why cumulative fits give false confidence), compare grid, Bayesian, genetic and swarm searches, refine with gradients, curvature and Nelder-Mead, fit models without a likelihood with approximate Bayesian computation and a particle filter, calibrate for a purpose with targets, observation mappings and losses, and diagnose identifiability and misspecification.
Key ideas, one per episode
- Ep. 32Least squares recovers R0 2.5, but a fit on cumulative counts claimed ±0.004 when the real spread was ±0.15.
- Ep. 33Global searches find the valley fast; none reliably polishes the last percent: hand over to a local method.
- Ep. 34Curvature-aware methods reached the best fit in about 20 model runs; plain gradient descent was still 48% off after 1,500.
- Ep. 35ABC recovered R0 from simulations alone; a particle filter saw R fall below 1 six days after a lockdown.
- Ep. 36Same model, same data: four calibration targets gave 476 to 800 peak beds; the truth was 681.
- Ep. 37Early data measure growth, not R0; a good fit is not proof: check parameters, profiles and unseen data.
Textbook: Chapter 8 of T. Lazebnik, Epidemic Modeling: Principles, Algorithms, and Applications (Academic Press, 2026). The episodes and slides follow the chapter’s topics in our own words, figures and simulations; nothing is copied from the book.
Watch
6 short episodes for this module. Pick one from the list, and open the transcript to read along: each timestamp plays the episode from there. The narration is generated with a voice clone of Teddy, used with his permission.
Episode 32 · 2:53
Fitting by least squares
Fitting an epidemic model by least squares on a simulated outbreak with a known truth: the loss, weights and the log scale, and why fitting cumulative counts makes error bars far too small.
Least squares recovers R0 2.5, but a fit on cumulative counts claimed ±0.004 when the real spread was ±0.15.
TranscriptEpisode 32
Model meets data. We have a model, and we have data. Which parameter values make the model match the data? Welcome to Module eight: parameter estimation and calibration.
One outbreak, known truth. All module long we use one simulated outbreak with a known truth. A town of one hundred thousand, R naught 2.5: a transmission rate beta of 0.25 per day, and ten infectious days on average. Forty percent of infections are reported, with extra noise. Over a hundred days, thirty four thousand eight hundred fifty one cases were reported. Now we pretend we don't know beta or gamma.
Least squares. Least squares: for any beta and gamma, run the model, subtract its curve from the data, square each difference, and add them up. The best parameters make that sum as small as possible. Squaring punishes big misses and keeps the sum smooth, so a solver can slide downhill. And when the noise is normal with a known size, least squares is exactly maximum likelihood. Our fit gives beta 0.249. Gamma comes out at 0.099, so R naught is 2.51, against a true 2.5. A least squares solver finds this in a fraction of a second.
Weights and the log scale. But counts are noisier when they are big. A day with a thousand cases wobbles far more than a day with ten, so plain least squares lets the peak dominate. Weights fix that: divide each difference by the size of noise you expect on that day. Or fit on the log scale, where a ten percent miss counts the same at any size.
The cumulative trap. Now a trap. Fitting the cumulative curve looks beautiful: smooth, with tiny residuals. But each day's total carries all the earlier days' errors, so the errors are not independent. We repeated the fit on two hundred new noisy datasets from the same truth. The cumulative fit claimed its R naught was good to plus or minus 0.005. The estimates actually spread by 0.15, and its ninety five percent intervals held the truth only five percent of the time. Fitting daily counts was more honest, but still too confident: its intervals held the truth seventy four percent of the time, because the noise model behind the error bars was too simple.
Next. Least squares is the baseline: simple, fast, and often enough. Next: how to search when the landscape is rough. Grids, Bayesian optimization, genetic algorithms and swarms.
Searching a landscape. Least squares tells you what to minimize. It doesn't tell you how to search. When the landscape is rough, or each model run is expensive, the search strategy matters.
Grid search. The simplest search is a grid: try every combination. With forty one values for each parameter, that is one thousand six hundred eighty one model runs. The best grid point was still seven percent worse than the best fit, because the optimum fell between grid lines. Zooming in three times, coarse to fine, got within one percent with three hundred sixty three runs. A grid is also a map. It shows the valley, the flat directions and any second minimum at a glance. That makes it a great diagnostic, even when it isn't the final method.
The curse of dimensionality. But grids explode. One of our model runs takes 8.7 milliseconds. Ten values for each of two parameters is a hundred runs. With six parameters it's a million runs: two and a half hours. With eight, a hundred million runs: ten days.
Bayesian, genetic, swarm. Bayesian optimization spends runs carefully. It fits a statistical stand-in for the loss to the runs so far, with its uncertainty, and runs the model next where an improvement looks most likely. Genetic algorithms keep a population: the better candidates are selected, crossed and mutated. Particle swarms move a flock of candidates, each pulled toward its own best spot and toward the flock's best.
A race on one outbreak. We gave each method twenty independent tries on our outbreak. Getting within ten percent of the best fit took Bayesian optimization a median of forty seven runs, the genetic algorithm one hundred eighty two, and the swarm two hundred nine. Random guessing didn't get there in six hundred. Polishing the last percent was slow for all of them: only a third to a half of the tries got within one percent of the best fit inside their budgets. So global searches are best at finding the right valley. To reach the bottom, hand over to a local method.
Next. Next: gradients and derivative-free refinement, the methods that finish the job.
Into the valley. Global search finds the valley. Local refinement walks to the bottom of it. There are two families: methods that use gradients, and methods that don't.
Getting a gradient. A gradient says which way is downhill. You can get one by nudging each parameter and re-running the model, from sensitivity equations solved alongside the model, or by automatic differentiation. Nudging needs care. Too big a step, and you measure the slope of a whole stretch of curve: with a step of 0.01 in beta, the error was ten percent. Too small, and rounding takes over. Here the best step was about ten to the minus eight.
Descent and curvature. Plain gradient descent steps straight downhill. In a long, curved valley that's slow: it keeps crossing the valley instead of following it. From our starting point, after three hundred steps and one thousand five hundred model runs, it was still forty eight percent above the best fit. Methods that use curvature do far better. Gauss Newton, in its Levenberg Marquardt form, uses the structure of least squares, and reached the best fit in twenty one model runs. BFGS, which learns the curvature as it goes, got within one percent in twenty two.
Nelder–Mead. When gradients are unreliable, use a derivative-free method. Nelder Mead moves a triangle of three points: reflect the worst point through the others, expand if that helped, contract or shrink if it didn't. It got within one percent in fifty runs.
Noisy objectives. Stochastic models make every method's life harder. We ran the same parameters twenty times with new random numbers: the loss swung with a standard deviation of about four thousand eight hundred. Raising beta by five percent changed its average by only about three hundred. Along a slice of beta, the noisy loss had ten local minima. With the same random numbers at every run, it had two, and a local method could follow it. So average over repeated runs, reuse the same random numbers, or use a method built for noise.
Next. Next: when there's no likelihood at all. Simulation-based inference, and state-space models that track hidden states.
No likelihood. Some models are easy to simulate, but impossible to write a likelihood for: agent-based towns, network epidemics, branching processes. You can still fit them.
Approximate Bayesian computation. Approximate Bayesian computation: draw parameters from a prior, simulate an outbreak, compare it with the real one, and keep the draws whose outbreaks look close enough. Our test: a random outbreak in a town of two thousand, with five first cases and R naught three. It produced one thousand eight hundred eighty six cases, with a peak of eighty three on day thirty.
What ABC learned. We drew fifty thousand random parameter pairs. Beta could be as low as 0.1, or as high as 0.6. Gamma could be as low as 0.05, or as high as 0.3. Seventeen percent of the simulated outbreaks fizzled out. We compared total cases, peak day and peak height, and kept the closest one percent: five hundred draws. Their R naught had a median of 2.7. Ninety percent of them sat between 2.2 and 3.9. The truth was three. Beta and gamma on their own stayed wide, and moved together, with a correlation of 0.93. The data pinned down their ratio, not each one.
Tolerance and summaries. The tolerance is a trade-off. Keep ten percent of the draws, and the interval is wide: it spans 1.7 up to 4. Keep only the closest fifty, and it shrinks to between 2.6 and 3.6. But then you need far more simulations to get enough draws. And the summaries decide what can be learned. A summary that ignores timing can't tell a fast epidemic from a slow one.
A particle filter. State-space models take another route. The epidemic is a hidden state that moves day by day, and the data are noisy readings of it. Unknown parameters can join the hidden state. A particle filter tracks it with thousands of guesses, called particles. Each day it moves every particle forward with the model, weights it by how well it explains today's count, and resamples. Our test: the reproduction number drops from 2.5 to 0.8 on day thirty five. With three thousand particles, the filter's ninety percent band fell entirely below one on day forty one, six days later. Its bands held the truth on eighty eight percent of days.
Next. Next: calibration. Choosing targets, linking the model to the data, and designing the loss.
Fit for a purpose. Estimation asks which parameters the data support. Calibration asks a more practical question: how do we tune this model so it's fit for a purpose?
A richer truth. This time the truth is richer than the model. The outbreak follows an SEIR model with four latent days and R naught 2.5. Testing ramps up from twenty to fifty percent of infections over forty days, and three percent of infections need a hospital bed for eight days. The analyst uses a simple SIR model and the first sixty days of data. The question: how many hospital beds will be needed at the peak?
Calibration targets. Choose the calibration target, and the answer moves. Fitting the whole case curve gave seven hundred twenty six beds. Only the first thirty days: eight hundred. Peak timing, peak height and the total: four hundred seventy six. Bed occupancy itself: five hundred eighty four. The truth was six hundred eighty one. Same model, same data, four answers. Choose targets that match the purpose, and check the result on the quantity that matters.
The observation mapping. The observation mapping links model states to what is measured. Here testing ramped up, so part of the early growth in cases was just more testing. Assuming a constant reporting share, the fitted growth rate was 0.149 per day. With the ramp in the mapping, 0.130. The truth was 0.126.
Loss design. The loss decides which errors you accept. With plain squared errors the peak dominates, and the early days were off by a hundred and seven percent on average. Weighting by the expected noise brought that to seventy five percent, and the log scale to fifty eight, at the cost of a worse peak. And because the model is wrong, each loss gave a different R naught. Plain squares said 2.35. The weighted loss said 3.5, and the log scale 7.4. None of them is the truth, which was 2.5. Constraints and penalties help: keep rates in plausible ranges, and treat a parameter that runs into its bound as a warning. Some of our fits pushed the infectious period to the fifty day limit we allowed.
Next. Next: identifiability, misspecification, and the diagnostics that tell you whether to trust a calibration.
Fits that say nothing. A fit can look perfect and still say nothing about a parameter. That's identifiability, and checking it belongs in every calibration.
The valley and the profile. Fit our outbreak using only its first twenty five days. The loss map shows a long, flat valley: many pairs of beta and gamma fit almost equally well. A profile makes it precise: fix gamma, refit beta, and see how much worse the fit gets. With twenty five days, gamma could be anywhere from 0.04, the edge of what we tried, to 0.22, and R naught anywhere from 1.6 to 5.1. But the growth rate, beta minus gamma, was pinned between 0.136 and 0.163. Early data measure growth, not R naught. With all hundred days, R naught narrowed to 2.2 to 2.6.
Breaking ties. Outside information breaks the tie. A prior saying people stay infectious for about ten days, give or take two, gave R naught 2.3 from the same twenty five days. Some pairs never separate. Fit the reporting share and the population size together, and their estimates were correlated at almost exactly minus one (−0.997). Only their product, the number of cases that could ever be reported, is identified.
Misspecification. Misspecification is subtler. We fitted an SIR model to data from an SEIR outbreak. The fit looked fine, and its residuals showed no pattern. But it pushed the infectious period to the fifty day limit, and gave R naught 8.1. The truth was 2.5. The right model fitted only a little better. So a good fit is not proof: check whether the parameters make sense, and test on data the fit didn't see.
Stress tests and trade-offs. Stress tests help. We refitted on windows from thirty to seventy days: R naught moved between 1.8 and 2.6, and the forecast peak between nine hundred twenty one and one thousand one hundred ninety three cases a day. The truth was one thousand one hundred seventy four. And when targets conflict, show the trade-off. Fitting cases alone and fitting bed occupancy alone gave very different parameters. The weightings in between trace a curve of compromises, and picking a point on it is a decision, not a fit.
Module recap. That closes Module eight: least squares, search, refinement, simulation-based inference, calibration and its diagnostics. Next, in Module nine: the data streams themselves, from surveillance to genomes.
2:53Episode 32 · 8.1Fitting by least squaresLeast squares recovers R0 2.5, but a fit on cumulative counts claimed ±0.004 when the real spread was ±0.15.
2:31Episode 33 · 8.2Search strategiesGlobal searches find the valley fast; none reliably polishes the last percent: hand over to a local method.
2:32Episode 34 · 8.3Gradients and derivative-free refinementCurvature-aware methods reached the best fit in about 20 model runs; plain gradient descent was still 48% off after 1,500.
2:51Episode 35 · 8.4Simulation-based and state-space inferenceABC recovered R0 from simulations alone; a particle filter saw R fall below 1 six days after a lockdown.
2:36Episode 36 · 8.5Targets, observations and loss designSame model, same data: four calibration targets gave 476 to 800 peak beds; the truth was 681.
2:48Episode 37 · 8.6Identifiability and diagnosticsEarly data measure growth, not R0; a good fit is not proof: check parameters, profiles and unseen data.
Interactive lab
Fitting an outbreak
Fit the module's simulated outbreak by weighted least squares with a grid, Nelder–Mead, gradient descent or a swarm, shorten the data to see the beta–gamma valley, and fit a stochastic town with ABC rejection.
The first panel fits the module's SIR outbreak and draws the loss over beta and gamma with each search's path; the second runs approximate Bayesian computation on a random outbreak in a town of 2,000. Everything runs in your browser.
One outbreak with a known truth
The module's SIR outbreak: a town of 100,000, beta 0.25 and gamma 0.1 (R0 2.5), 40% of infections reported with negative binomial noise. Everything runs in your browser.
Each counts its model runs; the yellow dot is the best fit found by a careful reference search.
Draw beta and gamma from a box, simulate a random outbreak, keep the closest draws.
Running…
Loss map
Dark: small loss. Orange: the search's path and result; yellow: the best fit; white ring: the truth.
Data and fit
Grey: reported cases; orange: the fitted model over all 100 days.
Challenges
Each one is checked on your current settings, here or in the ABC panel below.
- Fit all 100 days with Nelder–Mead and get within 1% of the best fit.
- Find a start point from which gradient descent gets within 5% of the best fit.
- With 30 days of data or fewer, find a valley: fits within 5% of the best whose gamma values are more than 0.1 apart.
- In ABC, get the 90% interval of R0 narrower than 1.0 with at least 50 kept draws.
Running…
Kept draws
Blue: kept (beta, gamma); dashed box: the prior; dashed lines: the 90% range of R0; ring: the truth.
