Specialized Distributions

Fit a bell curve to robot torques that cannot leave ±1, and it puts 15% of its mass on torques the motor cannot make. Fit it to 50 years of river levels, and its 100-year flood is 4.2 m. The simulated truth is 9.3 m.

Pick a world, then switch between the bell (yellow outline, red where it fails) and the specialized model (purple). Then we build, piece by piece, the distributions that respect bounds, circles, rotations, extremes, sums, corners and bursts.

You need the bell curve, what a density is and basic Python. The four earlier lessons help; each idea is rebuilt here.

Fit the bell, then fit the structure

Your browser simulates all four data sets with fixed seeds, so we know the truth. Illustrative: the torques, river, prices and alerts are toys that show each structure.

Chapter 0

Two Numbers Do Not Fix a Shape

Match the mean and the spread, and still miss the tail by a factor of 55

A bell curve has two knobs: the mean and the standard deviation. Set them from the data, and everything else follows: how often a value lands 4 standard deviations out, whether the curve leans, where it stops. The data have no vote on those.

Real data carry more structure. A torque cannot pass the motor limit, and a heading of 359° sits next to 1°. A flood can be ten times the usual level. Two stocks crash together more often than their correlation says, and one alert brings more. Each breaks the bell in its own way.

First we need a judge. Call the data x1 to xn, and a candidate density f. The average log-likelihood, written ℓ ("ell"), scores how much density f gives to the values that came:

Say it aloud

Ell equals one over n, times the sum over i of the natural log of f of x-i.

ℓ
ell the average log-likelihood, in nats per value. Higher is better.
1/n
one over n divide by the number of values, so data sets of any size compare.
Σi
the sum over i add one term for each value, from the first to the n-th.
ln f(xi)
the log of f of x-i the log of the density the model gives to value i. A value it calls nearly impossible costs a lot.
In plain words

Read the model's density f at each value x-i and take its log. Average the n logs. The larger ℓ explains the data better.

With numbers

With made-up numbers: three values get densities 0.30, 0.20 and 0.05 from model A, and 0.25, 0.25 and 0.15 from model B. A scores (−1.20 − 1.61 − 3.00)/3 = −1.94. B scores (−1.39 − 1.39 − 1.90)/3 = −1.56. B wins by 0.38 nats per value, because A nearly ruled out the third value.

Match two moments, miss the tail

Three shapes, all with mean 0 and standard deviation 1. Warm is the true shape, blue is 2,000 draws, the yellow outline is the bell. Pick a shape, then drag t.

4.0

Tail shares are exact. The 2,000 draws come from a seeded generator, so their ℓ is illustrative and moves a little with the seed.

At 4 standard deviations, the bell gives 1 chance in 31,600. A Laplace with the same mean and spread gives 1 in 570, 55 times more. A skew-normal leaning right gives 1 in 940 on the right and almost nothing on the left. On the device's 2,000 Laplace draws, the true shape beats the bell by 0.09 nats per value.

Failure: a risk model fitted by two moments.

Symptom: days beyond 4 standard deviations come about once in 600 days, not once in 31,600.

Measure: count the days beyond 4 sd against the bell's 0.0032%, and compare ℓ on held-out days.

Fix: choose the shape from the data's structure, then check it on the tail you care about, not only on the mean and spread.

The hero's four worlds are Chapters 1, 5, 7 and 8.

  1. Squash and flow: bounded actions with tanh, then many invertible steps (the hero's torques).
  2. Skew and tails: two dials on the bell, for a lean and for tail weight.
  3. Circle: wrap a heavy-tailed line around a circle.
  4. Rotations: spread over 3-D orientations without gimbal lock.
  5. Extremes: the law of the values above a high threshold (the hero's floods).
  6. Stable sums: sums of heavy-tailed steps that never become a bell.
  7. Copulas: how two variables crash together, apart from each one's shape (the hero's crashes).
  8. Hawkes: events that make more events (the hero's alerts).
  9. Showcase: name the structure behind five data sets, and score your pick.
  10. The field guide: this lesson and the four before it, in one map.
Two models fit the same 500 held-out values. Model A has ℓ = −1.42; model B has ℓ = −1.35. What follows?

Chapter 1

Squash a Bell, Then Stack the Squashes

Push a Gaussian through tanh to respect a bound, and correct the density by how much each step stretches

A robot policy outputs a torque between −1 and +1; a Gaussian policy puts 15% of its mass beyond. The squashed Gaussian draws u from a Gaussian and outputs a = tanh(u), which always lies in (−1, 1).

The density needs the continuous lesson's correction: divide by the axis stretch, da/du = 1 − a2. Near ±1, tanh squeezes a wide range of u into a thin strip, so density piles up.

Call the Gaussian's mean μ and spread σ, and the pre-squash value u = atanh(a). In log form:

Say it aloud

Log pi of a equals the log of the normal density at u, with mean mu and spread sigma, minus the log of one minus a squared.

ln π(a)
log pi of a the log density of the action a.
ln N(u; μ, σ2)
log N of u, mu, sigma squared the Gaussian log density at u = atanh(a).
ln(1 − a2)
log of one minus a squared the log slope of tanh at u. It is negative, so subtracting it raises the density.
In plain words

Undo the squash: u = atanh(a). Score u under the Gaussian. Subtract ln(1 − a2), so the score goes up near the edges.

With numbers

μ = 0, σ = 1, a = 0.9: u = atanh 0.9 = 1.472, where the Gaussian log density is −2.003. ln(1 − a2) = ln 0.19 = −1.661. So ln π(0.9) = −2.003 + 1.661 = −0.342, a density of 0.710.

A normalizing flow applies invertible layers f1 to fK to z drawn from N(0, 1). Call the stretch of layer k at its input Jk: its slope, or in many dimensions the determinant of its Jacobian.

Say it aloud

Log p of x equals log p-Z of z, minus the sum over k of the log of the absolute value of J-k.

ln p(x)
log p of x the log density of the output x.
ln pZ(z)
log p-Z of z the log density of the start z under N(0, 1).
Σk
the sum over k one term per layer.
ln |Jk|
log of the absolute value of J-k how much layer k stretches space at its input point.
In plain words

Follow z through every layer. Subtract each log stretch J-k from ln p-Z(z). The result is ln p(x) where z lands.

With numbers

The device's layers, with z = 0.5: ln pZ(0.5) = −1.044. The stretches are 2.052, 1.904 and 0.800, with logs that total 1.139. z lands at x = 1.956, where ln p(x) = −1.044 − 1.139 = −2.183.

Push a bell through invertible steps

Blue: 4,000 pushed samples. Warm: the formula. "Forget the slope" drops the correction (red).

0.0
1.0

Exact densities; seeded samples, illustrative. The three flow layers are a made-up toy.

Soft Actor-Critic uses this policy (Haarnoja et al., 2018, appendix C). A coupling layer keeps half the inputs and scales the other half by es, with s computed from the kept half. Its log determinant is the sum of the s values (RealNVP, Dinh et al., 2017).

Failure: the missing slope term.

Symptom: a SAC agent's torques slam to ±1.

Measure: without the term, the "entropy" at σ = 3 is the Gaussian's 2.52 nats. The actions' true entropy is −1.10 nats; it peaks at 0.684, at σ = 0.87.

Fix: subtract ln(1 − a2) per dimension, as 2(ln 2 − u − softplus(−2u)). It stays finite where float32 rounds tanh(10) to 1.

A squashed Gaussian action is a = 0.99. How does the correction term change its log density?

Chapter 2

Two Dials on the Bell

Add one parameter that makes the bell lean, and another that sets how fast its tails fall

Returns lean: losses come larger and faster than gains. Sensor residuals have sharper peaks and longer tails than a bell. Each needs one extra knob that keeps the bell as a special case.

The skew-normal adds a lean. Call the standard normal density φ and its CDF Φ, and a lean knob α. Then:

Say it aloud

f of x equals two, times phi of x, times capital Phi of alpha x.

f(x)
f of x the skew-normal density, in standard units.
2
two restores the area to 1; the other two factors keep half of it.
φ(x)
phi of x the standard bell's height at x.
Φ(αx)
capital Phi of alpha x the bell's CDF at αx: near 1 on one side of 0, near 0 on the other.
In plain words

Multiply the bell's height φ(x) by Φ(αx), a smooth switch that keeps one side and fades the other. Double it. At α = 0 the bell returns.

With numbers

α = 4, x = 1: φ(1) = 0.242 and Φ(4) = 0.99997, so f(1) = 0.484, twice the bell. At x = −1: Φ(−4) = 0.0000317, so f(−1) = 0.0000153. The mean moves from 0 to 0.774.

Why is the area 1? Keep a standard normal X only when an independent standard normal Y is below αX. That happens half the time, so the kept X has density φ(x)Φ(αx)/(1/2). A million simulated pairs keep 0.500, with mean 0.774 (Azzalini, 1985).

The generalized normal sets the tail weight. Call its centre μ, its scale s and its shape β; Γ is the gamma function:

Say it aloud

f of x equals beta over two s gamma of one over beta, times e to the minus, the absolute value of x minus mu over s, to the beta.

f(x)
f of x the generalized normal density.
β / (2sΓ(1/β))
beta over two s gamma of one over beta the constant that makes the area 1.
e−(|x − μ|/s)β
e to the minus the scaled distance to the beta the penalty for distance from μ. β = 1 gives the Laplace, β = 2 the bell, large β a flat box.
In plain words

Measure the distance of x from μ in units of s, and raise it to the power β. The density falls as e to minus that. Small β makes it fall slowly, so far values keep real probability.

With numbers

β = 1.5, s = 1, x = 1 from μ: Γ(2/3) = 1.354, so the constant is 1.5/(2 × 1.354) = 0.554, and f = 0.554 × e−1 = 0.204.

Turn one dial at a time

Warm: the shape. Yellow outline: the bell with the same mean and spread. Pick a dial, then drag it.

4.0

Exact densities and moments. In tail mode both curves have standard deviation 1, so only the shape differs.

Kurtosis measures tail weight; a bell has 3. A Laplace (β = 1) has 6 and puts 1.44% of its mass beyond 3 standard deviations, against the bell's 0.27%. At β = 4 that share is 0.0005%. A Laplace prior on weights is L1 regularization; a Gaussian prior is L2.

Failure: more lean than the skew-normal can make.

Symptom: a skew-normal fit to returns with sample skewness −1.5 drives α toward minus infinity and still misses the tail.

Measure: the skew-normal's skewness can never exceed 0.995 in size; that is the half-normal limit as |α| grows.

Fix: use a family with a lean and heavy tails together, such as the skew-t, or model log losses.

Which setting of the generalized normal gives the standard bell?

Chapter 3

Wrap a Line Around a Circle

Wind a heavy-tailed density onto the circle, and get headings that mostly agree but sometimes swing all the way round

A weather vane mostly points north, but now and then a gust spins it round. The continuous lesson fitted the von Mises, the circle's bell, with density proportional to eκ cos(θ − μ). Its tails are light. This vane needs heavy ones.

One recipe makes a circle distribution from any line distribution: wrap it. Wind the real line around a circle of circumference 2π, so the values θ, θ + 2π, θ − 2π and so on land on the same point. Add their densities:

fwrapped(θ) = the sum over every whole number k of f(θ + 2πk)

Wrap a Cauchy, the line's heaviest common tail, with scale γ. The sum has a closed form, with a concentration ρ = e−γ and a mean direction μ. This is the wrapped Cauchy:

Say it aloud

f of theta equals one over two pi, times one minus rho squared, over one plus rho squared minus two rho cos of theta minus mu.

f(θ)
f of theta the density at the angle θ, per radian.
1/(2π)
one over two pi the flat density on the circle; the rest of the formula bends it.
1 − ρ2
one minus rho squared ρ is the concentration, from 0 (flat) toward 1 (a spike). It is also the mean resultant length: the length of the average unit vector.
1 + ρ2 − 2ρ cos(θ − μ)
one plus rho squared minus two rho cos of theta minus mu smallest, (1 − ρ)2, at the mean μ; largest, (1 + ρ)2, opposite it.
In plain words

Take the angle between θ and the mean μ. The closer it is, the smaller the bottom line, and the higher the density. The top line and 1/(2π) make the area 1. At ρ = 0 the bottom line is 1, and the circle is flat.

With numbers

ρ = 0.7. At the mean: 0.51/(2π × 0.09) = 0.902. At 90° away: 0.51/(2π × 1.49) = 0.054. Opposite the mean: 0.51/(2π × 2.89) = 0.028, three times the von Mises value, 0.0092.

Wind a Cauchy onto the circle

Left: unrolled from −180° to 180°; faint warm curves are the wrapped copies that add up. Right: the circle, with 300 headings (blue). The yellow outline is the von Mises with the same ρ. Drag ρ.

0.70

Exact densities and shares. Headings come from a seeded generator that wraps Cauchy draws, illustrative.

Both curves have the same mean resultant length, the same "average agreement", but spend it differently. At ρ = 0.7 the wrapped Cauchy puts 29% of headings within 10° of the mean, against 18% for the von Mises, and 11.1% beyond 90°, against 7.4%.

To fit it, average the unit vectors (cos θ, sin θ). The direction of the average estimates μ. Its length estimates ρ, because for the wrapped Cauchy the average of cos(θ − μ) is exactly ρ. 400 headings drawn with ρ = 0.7 gave a length of 0.686.

Failure: a light-tailed circle model for a vane that spins.

Symptom: a von Mises fit says reversals of more than 90° almost never happen, but the log shows one every few days.

Measure: at a mean resultant length of 0.9, the von Mises puts 0.18% beyond 90°; the wrapped Cauchy puts 3.35%, nineteen times more.

Fix: compare ℓ for both on held-out headings, and count the reversals. Fit the wrapped Cauchy when the swings are real.

You wrap a line density around a circle. What is the density at angle θ?

Chapter 4

Spread Over Rotations

Put uncertainty on 3-D orientations with quaternions, so that the spread does not depend on where you stand

A robot estimates a mug's orientation, give or take 10°. Orientations form SO(3), the rotations of 3-D space; add a position and you get a pose in SE(3) (see Rotations and Transforms). Turn 360° about any axis and you are back.

The quick fix puts a Gaussian on the three Euler angles, yaw, pitch and roll, each with σ = 10°. Near pitch 90°, yaw and roll turn about almost the same axis: gimbal lock. Then the three spreads give 14° of doubt about one axis and almost none about another.

A unit quaternion q is four numbers with length 1. A turn by angle ω about axis n is q = (cos(ω/2), sin(ω/2) n). The catch: q and −q are the same rotation, so they need the same density. A quadratic form does that.

Call a symmetric 4 × 4 matrix M, and the normalising constant c. The Bingham distribution (Bingham, 1974) is:

Say it aloud

p of q equals one over c, times e to the q-transpose M q.

p(q)
p of q the density of the rotation q. p(q) = p(−q).
1/c
one over c the normalising constant; libraries compute it numerically.
eqTMq
e to the q-transpose M q a quadratic score. With M = diag(0, −κ, −κ, −κ) it is −κ sin2(ω/2): ω is the angle from the mean rotation, κ ("kappa") the concentration.
In plain words

Write the rotation as q and compute q-transpose M q. Raise e to it. Flipping q to −q changes no square, so both get the same density.

With numbers

κ = 20, and a 30° turn about z from the mean: q = (0.966, 0, 0, 0.259). Then qTMq = −20 × 0.2592 = −1.340. The density is e−1.340 = 0.262 times the peak, and −q gives the same.

Measure the spread in every direction

Left: where sampled rotations send the mug's handle and up axes (blue), around the mean axes (yellow). Right: the spread about each principal axis. Pick a model, then drag σ.

10°

Seeded samples, illustrative. The Bingham uses κ = 2/σ2 (σ in radians): a spread of σ about every axis for small angles. Euler order: yaw, pitch, roll (Z-Y-X).

With σ = 10°, the Bingham spreads 10.3°, 10.2° and 9.9° about its principal axes, in any pose. The Euler Gaussian gives about 10° each at pitch 0°, but 14.2°, 9.9° and 1.4° at pitch 85°.

The matrix Fisher density etr(FTR) on rotation matrices R equals this Bingham when F = κFI and κ = 4κF. For small spreads both match the tangent-space Gaussian of Lie groups and SLAM.

Failure: averaging quaternions.

Symptom: the average of 40 orientation estimates, each 10° off, lands 19° from the truth; one run in ten misses by 85°.

Measure: a tracker may report q or −q, so the plain mean nearly cancels, to a length near 0.15.

Fix: take the top eigenvector of the sum of q qT, the Bingham's maximum-likelihood mode (Markley et al., 2007). It misses by 2.7° in the same runs.

Why does the Bingham density use a quadratic form qTMq?

Chapter 5

Only the Tail Counts

Throw away the ordinary days, fit the amounts above a high threshold, and read off the 100-year level

A town wants a flood wall for the 100-year river level: the level a day exceeds with chance 1 in 36,525. We have 50 years of daily levels. A bell fitted to all 18,262 days says 4.2 m. Ordinary days set the bell, and they say little about the worst ones.

Extreme value theory looks only at the tail. Pick a high threshold u, and keep the amounts above it, the exceedances. The Balkema–de Haan (1974) and Pickands (1975) theorem says: for most continuous distributions, as u rises, the exceedances approach one family. Call the exceedance y = x − u, the scale σ and the shape ξ ("xi"). This is the Generalized Pareto (GPD) tail:

Say it aloud

The chance that X minus u exceeds y, given that X exceeds u, equals one plus xi y over sigma, to the power minus one over xi.

P(X − u > y | X > u)
the chance X minus u exceeds y, given X exceeds u among days above the threshold u, the share that go at least y further.
1 + ξy/σ
one plus xi y over sigma grows with the exceedance y; σ is its scale, in metres.
−1/ξ
minus one over xi the power. ξ > 0: a power-law tail. ξ = 0: the limit e−y/σ, exponential. ξ < 0: a hard top at u − σ/ξ.
In plain words

Go y beyond the threshold. Divide y by σ, multiply by ξ and add 1. Raise that to minus 1/ξ. That is the share of threshold days that go at least that far.

With numbers

With made-up numbers: ξ = 0.2, σ = 0.4 m, y = 1 m. 1 + 0.2 × 1/0.4 = 1.5, and 1.5−5 = 0.132. An exponential tail with the same σ gives e−2.5 = 0.082, only 62% as much.

To get the m-day level, call the share of all days above u ζ ("zeta"). Set ζ times the tail chance equal to 1/m and solve for x:

xm = u + (σ/ξ) · ((ζm)ξ − 1) u = 3.67 m, ζ = 366/18,262 = 0.0200, m = 36,525 days, ξ = 0.194, σ = 0.374 m ζm = 732; 7320.194 = 3.60; xm = 3.67 + 1.92 × 2.60 = 8.67 m

Fit only the tail

Top: 50 years of daily levels (blue) and the pink threshold. Bottom: the exceedances (blue) and the fitted GPD (purple). Drag the threshold and watch the 100-year level.

98%

Simulated, illustrative: each day is 2 + 0.5 |T| m, with T an independent Student-t with 5 degrees of freedom. The true tail has ξ = 0.2, and the true 100-year level is 9.29 m. Fits use probability-weighted moments (Hosking and Wallis, 1987).

At the 98th percentile the fit gives ξ = 0.19 and a 100-year level of 8.67 m; the truth is 9.29 m. The bell says 4.20 m, and it gives a 9.29 m day a chance near 10−57. The 50-year record in this run is 7.64 m, which the bell calls a 1-in-1033 day.

Failure: the threshold sets the answer.

Symptom: the 100-year level reads 7.06 m at the 90th percentile and 7.45 m at the 99.5th, against 8.67 m at the 98th.

Measure: plot ξ against the threshold. Too low, the body leaks in and ξ drops to 0.05. Too high, 92 points leave ξ at −0.04, a false hard top.

Fix: pick the threshold where ξ settles, and report a range, not one number.

A GPD fit to exceedances gives ξ = −0.2 and σ = 1 m above u = 5 m. What does that say?

Chapter 6

Sums That Never Turn Into Bells

Add up steps with infinite variance, and watch single jumps rule a total that outgrows the square root

The central limit theorem says a sum of many independent steps looks like a bell, and its spread grows like √n. It needs one thing: a finite variance. The continuous lesson showed the Cauchy, whose average of 1,000 draws is as wide as one draw. The Cauchy is one member of a family.

A distribution is stable if a sum of copies has the same shape as one copy, only wider. Call the number of copies n, the copies X1 to Xn, and the tail index α ("alpha"), between 0 and 2. For the symmetric stable laws:

Say it aloud

X-one plus up to X-n has the same distribution as n to the one over alpha, times X.

X1 + … + Xn
X-one plus up to X-n the sum of n independent copies.
=d
has the same distribution as equal in distribution, not value by value.
n1/α
n to the one over alpha how much wider the sum is. α = 2 is the bell, with √n. α = 1 is the Cauchy, with n.
X
X one more copy of the same stable variable.
In plain words

Add n copies. Divide the total by n to the 1/α. What is left has the same distribution as a single copy. The smaller α, the faster the total spreads.

With numbers

n = 100 steps. A bell (α = 2) spreads 1001/2 = 10 times one step. α = 1.5 spreads 1002/3 = 21.5 times. The Cauchy (α = 1) spreads 100 times, so its average never narrows.

Only the bell, the Cauchy and the one-sided Lévy (α = 1/2) have a closed-form density. For α < 2 the variance is infinite; for α ≤ 1 the mean does not exist. At α = 1.5, 1.33% of draws land beyond 10; the bell of the same scale gives 1.5 × 10−12. The generalized central limit theorem says sums of steps with power tails x−α, α < 2, approach a stable law (Gnedenko and Kolmogorov, 1954).

Walk with heavy steps

The blue line is a walk of 1,000 steps; the teal mark is its largest single step. The yellow lines are ±n1/α. Drag α from 2 down toward 1.

1.50

Steps from the Chambers, Mallows and Stuck (1976) formula with a seeded generator, illustrative. The ±n1/α lines mark the growth rate, not a 95% band.

Compare the largest single step with the widest swing of the walk. Over 300 seeded walks of 1,000 steps, the median share is 9% for α = 2, 53% for α = 1.5 and 68% for α = 1.1. A heavy-tailed walk sits still, then jumps; one step can be most of the story. That is a Lévy flight.

Failure: a standard deviation that never settles.

Symptom: the error bar on a heavy-tailed quantity grows each time you collect more data.

Measure: for α = 1.5 the median sample standard deviation is 2.5 at n = 100, 3.9 at 1,000 and 5.5 at 10,000. The interquartile range stays at 1.94.

Fix: describe the spread with quantiles, estimate the tail index, and use medians or a stable fit instead of mean ± sd.

Steps follow a symmetric stable law with α = 1.5. How much wider is the sum of 1,000 steps than one step?

Chapter 7

Shape the Corners, Keep the Margins

Split a joint distribution into each variable's own law and a copula that says how they move together

Two stocks each have a known, heavy-tailed daily return. On calm days they move loosely together; on the worst days they crash together. One correlation cannot hold both facts, and a two-dimensional bell keeps the corners quiet.

The trick is ranks. Push each variable through its own CDF: U = FX(X), V = FY(Y). Both are uniform on (0, 1), and their joint law is the copula C. Call the joint CDF F. Sklar's theorem (Sklar, 1959) says every joint CDF splits this way; with continuous margins, C is unique:

Say it aloud

F of x and y equals C of F-X of x and F-Y of y.

F(x, y)
F of x and y the chance that X is at most x and Y is at most y, both at once.
C
C the copula: a joint CDF on the unit square with uniform margins. It holds all the dependence and nothing else.
FX(x)
F-X of x X's own CDF: the rank of x as a share between 0 and 1.
FY(y)
F-Y of y Y's own CDF, the rank of y.
In plain words

Turn x into its rank F-X(x) and y into its rank F-Y(y). Feed both ranks to the copula C. The answer is the joint chance. Swap the margins and keep C, or swap C and keep the margins.

With numbers

Both stocks at their worst-5% level: FX(x) = FY(y) = 0.05. Independence gives C = 0.05 × 0.05 = 0.25%. A Clayton copula with θ = 2 has C(u, v) = (u−2 + v−2 − 1)−1/2 = 799−1/2 = 3.54%, fourteen times more.

Same rank correlation, different corners

Each blue dot is one day's pair of ranks. Teal dots fall in the pink corner: both in their worst 5%. All four copulas share one Kendall's τ. Pick a copula, then drag τ.

0.50

1,500 seeded pairs per setting, illustrative. Corner shares marked exact come from each copula's formula (the t by numerical integration).

Kendall's τ is a rank correlation: the share of agreeing pairs minus disagreeing ones. At τ = 0.5 the joint worst-5% share is 1.99% for the Gaussian copula, 2.52% for the t and 3.54% for the Clayton. The Gumbel gives 1.45%; its cluster sits in the upper corner. The limit of P(V ≤ q | U ≤ q) as q shrinks is the lower tail dependence. It is 0 for the Gaussian, 0.45 for the t and 0.71 for the Clayton.

Before 2008, a Gaussian copula (Li, 2000) was the standard way to price bundles of loans. With zero tail dependence, it makes joint defaults in a crash rare by design.

Failure: a Gaussian copula in a crash.

Symptom: joint worst-1% days come about 2.6 times as often as the model says.

Measure: track P(V ≤ q | U ≤ q) as q shrinks. For the Gaussian at τ = 0.5 it falls from 40% at q = 5% to 27% at 1% and 17% at 0.1%. A Clayton stays near 71%.

Fix: choose a copula with tail dependence where the corner matters, and check the corner counts on held-out days.

You keep each stock's heavy-tailed margin and swap a Gaussian copula for a Clayton copula with the same τ. What changes?

Chapter 8

Events That Cause Events

Let each event raise the rate of the next ones for a while, and get bursts a constant rate cannot make

An earthquake brings aftershocks; a failing server sets off alerts that set off more. A Poisson process, the steady-rate model of the discrete lesson, ignores the past. The hero's 733 alerts in 500 hours include an hour with 14. At the same rate, a Poisson gives an hour that busy a chance of 6 in 10 billion.

A Hawkes process (Hawkes, 1971) lets the past push the rate up. Call the background rate μ ("mu"), the branching ratio η ("eta"), the decay rate β ("beta"), and the times of past events ti. The rate at time t, the intensity, is:

Say it aloud

Lambda of t equals mu, plus the sum over past events t-i, of eta beta e to the minus beta, t minus t-i.

λ(t)
lambda of t the intensity: the expected events per hour right now, given the past.
μ
mu the background rate, events per hour that arrive on their own.
Σti < t
the sum over past events one term for each event that already happened.
ηβ e−β(t − ti)
eta beta e to the minus beta, t minus t-i the boost from one past event: a jump of ηβ that halves every ln 2/β hours. Its total area is η, the expected number of direct children.
In plain words

Start from the background rate μ. Each past event adds a bump of height ηβ that fades with rate β. Add the bumps that are still alive. The total is the chance per hour of the next event.

With numbers

With made-up numbers: μ = 0.5 per hour, η = 0.6, β = 2 per hour, events at 1.0 h and 1.5 h. At t = 2.0 h: 0.5 + 1.2e−2 + 1.2e−1 = 0.5 + 0.162 + 0.441 = 1.10 per hour, more than twice the background.

Each event has, on average, η children, each child η more, and so on. One background event leads to 1 + η + η2 + … = 1/(1 − η) events, and the long-run rate is μ/(1 − η). With η = 0.6 that is 2.5 events per cluster and 1.25 events per hour. If η ≥ 1, each event replaces itself or more, and the process explodes.

Watch events breed

Blue ticks are events; the warm curve is the intensity λ(t); the yellow line is the background μ. Drag η toward 1, then press simulate.

0.5
0.60
2.0

Simulated with Ogata's (1981) thinning method and a seeded generator, illustrative. The long-run rate μ/(1 − η) is exact; one 50-hour run scatters around it.

Bursts also inflate the spread of counts. Over long windows the variance of a Hawkes count is 1/(1 − η)2 times its mean: 6.25 at η = 0.6, against 1 for a Poisson. 100-hour windows of a seeded run gave 6.7. The same model fits aftershocks (Ogata's ETAS, 1988) and spike trains; see point-process models of spikes.

Failure: Poisson alarm limits on bursty alerts.

Symptom: a "more than 10 in an hour" alarm, set to fire once in two million hours, fires 6 times in the hero's 500 hours.

Measure: in the hero's alerts, the variance of hourly counts is 3.2 times the mean, and 47% of hours are empty against the Poisson's 23%.

Fix: fit a Hawkes process and alarm on its intensity, or at least model the counts as overdispersed (the negative binomial).

A Hawkes process has μ = 1 per hour and η = 0.8. What is its long-run rate?

Chapter 9

Name the Structure Behind the Data

Read the story, rule out the models that cannot have made the data, and score the rest on values they never saw

Five data sets, 400 values each, and a story for each. Seven candidates. Three questions narrow the choice:

  1. What values can it take? A bound, a circle or a floor rules out models that put mass beyond it.
  2. What structure does the story name? A lean, heavy tails, swings round a circle, amounts above a line.
  3. Which model scores best on held-out values? Fit on the first 200, and compute ℓ on the last 200.

Fit, then score on unseen values

Pick a data set and read its story. Then pick a candidate. Blue: the 200 held-out values. Purple: the fit from the other 200. Red: mass the fit puts where no value can be.

We simulated each data set with a fixed seed from one of the seven families, so we know the right answer. Fits are maximum likelihood, except the squashed Gaussian (moments of atanh), the circle models (the mean unit vector) and the GPD (probability-weighted moments).

Every story has one winner, and it beats the bell by a lot or a little. On torques the squashed Gaussian scores −0.42 against the bell's −0.90, and the bell puts 15% of its mass beyond ±1. On headings the wrapped Cauchy scores −1.05; the von Mises comes second at −1.16, and the bell, fitted to raw degrees, scores −2.33. On residuals the generalized normal wins by 0.09 nats per value with β = 1.29.

The skew-normal shows a trap. On flood peaks and torques its likelihood keeps rising as α grows without end, until the curve has a hard edge at the smallest value it saw. One held-out value below that edge gets almost no density, and the score falls to −3.79.

Failure: scoring on the values you fitted.

Symptom: on flood peaks the skew-normal looks like the second-best model, at −0.47 nats per value.

Measure: score the same fit on the 200 held-out peaks: −3.79, the worst of all. The GPD scores −0.28 on the fitted half and −0.23 on the held-out half.

Fix: always score on held-out values, and read the story before you trust a fit that sits on the edge of its parameters.

A model fits the training half well but gives one held-out value a density near 0. What happens to its held-out ℓ?

Chapter 10

The Field Guide to the Family

Find the right lesson from the object you hold, then the right distribution from its structure

Each distribution here keeps one piece of structure that the bell throws away. The table lists them.

DistributionStructureKey formulaFit byLibrary
Squashed Gaussianbounded to (−1, 1)ln N(atanh a) − ln(1 − a2)moments of atanh a; policy gradienttorch TanhTransform
Normalizing flowany learned shapeln pZ(z) − Σ ln |Jk|maximum likelihood, SGDtorch.distributions
Skew-normal(α)a lean, skewness under 0.9952φ(x)Φ(αx)maximum likelihoodstats.skewnorm
Generalized normal(β)tail weighte−(|x − μ|/s)βmaximum likelihoodstats.gennorm
Wrapped Cauchy(ρ)a circle with swings(1 − ρ2)/(2π(1 + ρ2 − 2ρ cos(θ − μ)))mean unit vectorstats.wrapcauchy
Bingham(M)rotations, q and −qeqTMq/ceigenvectors of Σ q qTnumpy.linalg.eigh
Generalized Pareto(ξ, σ)amounts above a threshold(1 + ξy/σ)−1/ξPWM or maximum likelihoodstats.genpareto
Stable(α)sums of heavy stepsX1 + … + Xn =d n1/αXquantiles or maximum likelihoodstats.levy_stable
Copula Cjoint cornersF(x, y) = C(FX(x), FY(y))ranks, then Kendall's τstats.kendalltau
Hawkes(μ, η, β)events that breedμ + Σ ηβe−β(t − ti)maximum likelihoodhand-written, see below

Two topics of the old page live elsewhere. The discrete lesson builds the softmax, or Gibbs, distribution with its temperature. Diffusion builds the forward noising process.

The family in one map

Start from the object you hold. It names the lesson.

You holdLessonThe first questionTypical answers
A count: 0, 1, 2, …DiscreteWhat does the story count?binomial, Poisson, geometric, negative binomial, categorical
One real amountContinuousWhat range, and what made it?Gaussian, exponential, Gamma, Beta, log-normal, Student-t
Several values at onceMultivariateHow do they move together?multivariate Gaussian, Dirichlet, Wishart, LKJ, von Mises-Fisher
A belief about a parameterBayesianWhat is the prior's job?conjugate priors, mixtures, spike-and-slab, horseshoe
Structure the four ignoreThis lessonWhich structure breaks the bell?squash, wrap, Bingham, GPD, stable, copula, Hawkes

How the five lessons connect

Five questions for any data

  1. What values can it take: a bound, a floor, a circle, a rotation?
  2. Does the story name a lean or heavy tails?
  3. Do you need the middle or the tail? For the tail, fit the tail.
  4. Do values depend on each other, in the corners or in time?
  5. Which candidate wins on held-out values, without putting mass where no value can be?

Corrections to the old version of this page

The core as code

pythonimport numpy as np
from scipy import stats

def squashed_logprob(u, mu, sigma):
    """log pi(a) for a = tanh(u), with the stable form of ln(1 - tanh(u)^2)."""
    corr = 2 * (np.log(2) - u - np.logaddexp(0, -2 * u))
    return stats.norm.logpdf(u, mu, sigma) - corr      # u = 1.472: -0.342

def fit_wrapped_cauchy(theta):
    c, s = np.cos(theta).mean(), np.sin(theta).mean()
    return np.arctan2(s, c), np.hypot(c, s)             # mean direction mu, rho

def average_quaternions(q):
    """Bingham mode: top eigenvector of sum q q^T. Ignores the sign of each q."""
    return np.linalg.eigh(q.T @ q)[1][:, -1]

def return_level(x, pct, years, per_year=365.25):
    u = np.percentile(x, pct); y = x[x > u] - u
    xi, _, sig = stats.genpareto.fit(y, floc=0)
    zm = len(y) / len(x) * years * per_year
    return u + sig / xi * (zm ** xi - 1)

def clayton(n, theta, rng):
    v = rng.gamma(1 / theta, size=(n, 1))               # Marshall-Olkin
    return (1 + rng.exponential(size=(n, 2)) / v) ** (-1 / theta)

def hawkes(mu, eta, beta, T, rng):
    """Ogata thinning: propose at the current upper bound, keep with lambda(t)/bound."""
    t, ex, ev = 0.0, 0.0, []                              # ex: the sum of live bumps
    while True:
        bound = mu + ex
        w = rng.exponential(1 / bound)
        if t + w >= T: return np.array(ev)
        t += w; ex *= np.exp(-beta * w)                  # bumps only fade between events
        if rng.uniform() * bound <= mu + ex:
            ev.append(t); ex += eta * beta

stats.levy_stable.rvs(1.5, 0, size=1000)                # alpha = 1.5, symmetric
stats.skewnorm(4).mean()                                 # 0.774
stats.gennorm(1).stats(moments='k')                       # excess kurtosis 3.0 (Laplace)

Keep going

The takeaway. Name the structure before you name the distribution. A bound, a circle, a rotation, a tail, a sum, a corner or a burst each has its own law, and the bell is the right answer only when none of them is there.

Now press Present or Teach and explain four things from memory. Explain why the squashed Gaussian subtracts ln(1 − a2), with a = 0.9. Explain why a quaternion distribution must give q and −q the same density. Explain how a GPD fit above the 98th percentile finds a 100-year level of 8.67 m where the bell says 4.20 m. Explain why a branching ratio of 0.6 gives clusters of 2.5 events. Then go back to the hero, pick the floods and switch between the two models.

Specialized Distributions
Back to the start: Discrete Distributions · Back to Gleams