3. Classification and generalization

Probabilities, evaluation, and regularization

Vadim Sokolov

George Mason University

The line can predict outside zero and one

Plus and minus marks. The line is beta zero plus beta one x one plus beta two x two equals zero. The perpendiculars equal z when the coefficients on x have length one.

z=β0+β1x1+β2x2,p=σ(z)=11+e−zz=\beta_0+\beta_1x_1+\beta_2x_2,\qquad p=\sigma(z)=\frac1{1+e^{-z}}

The line is β0+β1x1+β2x2=0\beta_0+\beta_1x_1+\beta_2x_2=0. In the picture, (β1,β2)(\beta_1,\beta_2) has length 1, so the perpendicular is zz. In general, zz equals that distance times the length of (β1,β2)(\beta_1,\beta_2).

  • On the line, zz is zero and the probability is one half.
  • The sign says which side. A larger |z||z| is a point farther from the line.
  • The sigmoid turns zz into a probability.
[0.119 0.5 0.881]

A negative logit is a probability below one half. A logit of zero is one half.

NBA favorite win spread

The bookmaker’s spread, split by whether the favorite won. Turquoise is a win. Purple is a loss. The losses sit on the smaller spreads.

Point spread when the favorite won, turquoise, and when the favorite lost, purple

Example: NBA Point Spread

Predicting whether the favorite wins from the point spread. No intercept: a spread of zero is a probability of one half.

  • Every 1-point increase in spread raises the log-odds by 0.156.
  • 4-point spread: about 65 percent. 8-point spread: about 78 percent.
  • Doubling the spread does not double the probability. That is the curve on the next slide.

What a coefficient changes

Win probability as a function of the spread in the original basketball model

p=σ(0.156s)p=\sigma(0.156s)

  • At 4 points: about 65 percent.
  • At 8 points: about 78 percent.
  • The coefficient changes the log-odds. The probability does not double when the spread does.

Why doesn’t doubling the spread double the probability?

[0.5 0.651 0.777]

LinkedIn: who becomes an executive

  • About 459,000 members who worked at a top-10 consultancy between 1990 and 2010.
  • About 64,000 later reached VP, CXO, or partner at a company of at least 200 people.
  • Base rate about 14 percent, among people who made it into the database.
  • One logit, eight features: metro region, gender, graduate school, undergraduate school, number of companies, number of job functions, number of industries, and years of experience.
  • Irwin, New York Times, 11 September 2016.
  • Berger, Gan, and Fritzler, LinkedIn, 9 September 2016.

A coefficient is a change in log-odds

Feature Coefficient
Metro region 0.28
Gender (male) 0.31
Graduate education 1.16
Undergraduate education 0.22
Company count 0.14
Function count 0.26
Industry count −0.22
Years of experience 0.09
  • One extra job function, 0.26, is about three years of experience.
  • The graduate-school coefficient, 1.16, is about thirteen years.
  • Switching industries lowers the log-odds. The writeup suggests a learning curve, or relationships left behind.

Apply the model to three people

  • Person A, about 6 percent. Male in Tulsa, undergraduate degree, one job function, three companies, three industries, fifteen years.
  • Person B, about 15 percent. Male in London, top international undergraduate school, non-MBA master’s, two functions, two companies, two industries, fifteen years.
  • Person C, about 63 percent. Female in New York, top undergraduate program, top MBA, four functions, four companies, one industry, fifteen years.

All three have fifteen years.

Redesign person B

Start from person B at 15 percent. Each line is one change, holding the rest fixed.

  • One industry instead of two: about 3 points.
  • Top-10 U.S. undergraduate school instead of a top international school: about 3 points.
  • Four companies instead of two: about 4 points.
  • London to New York: about 4 points.
  • Four job functions instead of two: about 8 points.
  • Ten more years: about 15 points.

Taken together, the probability goes to about 81 percent. Adding the separate lifts does not give that number. The sigmoid is not linear.

Choices and impact, starting from person B

The loss of one observation

For an outcome y∈{0,1}y\in\{0,1\} and a predicted probability pp,

P(Y=y∣p)=py(1−p)1−y.P(Y=y\mid p)=p^y(1-p)^{1-y}.

The loss is the negative log of that probability.

Ji=−ylogp−(1−y)log(1−p).J_i=-y\log p-(1-y)\log(1-p).

  • When y=0y=0, the loss is −log(1−p)-\log(1-p).
  • When y=1y=1, the loss is −logp-\log p.

Training minimizes the average of these losses.

The logistic function and the two Bernoulli loss curves

At z=0z=0, p=0.5p=0.5. The loss grows as pp moves toward the wrong outcome.

Compare the loss at 0.60 and at 0.99

  • Two models both predict that the event will happen.
  • One assigns probability 0.60. The other assigns 0.99.

The event does not happen. Should they receive the same loss?

5 minutes. Paper or calculator.

  • The outcome is y=0y=0. The loss is −log(1−p)-\log(1-p).

  • Calculate it for p=0.60p=0.60 and for p=0.99p=0.99.

  • Now the outcome is y=1y=1. The loss is −logp-\log p. Which probability is cheaper?

A sure mistake costs more

The more confident wrong prediction incurs much larger log loss

The event did not happen, so y=0y=0 and the loss is −log(1−p)-\log(1-p).

  • p=0.60p=0.60 still leaves a 40 percent chance of this outcome. Loss −log(0.40)=0.92-\log(0.40)=0.92.
  • p=0.99p=0.99 said the outcome was almost impossible. Loss −log(0.01)=4.61-\log(0.01)=4.61.

The event did happen, so y=1y=1 and the loss is −logp-\log p.

  • p=0.60p=0.60: loss −log(0.60)=0.51-\log(0.60)=0.51.
  • p=0.99p=0.99: loss −log(0.99)=0.01-\log(0.99)=0.01.

Both numbers are above one half, so a yes-or-no score calls both predictions right, or both wrong. The loss does not. It charges the model that was sure and wrong.

Fit the coefficients by maximum likelihood

The sample likelihood is the product of the Bernoulli probabilities, with pi=σ(xi⊤β)p_i=\sigma(x_i^\top\beta).

Maximizing that likelihood is the same as minimizing the sum of the losses.

β̂=argminβ∑i=1n[−yilogpi−(1−yi)log(1−pi)].\hat\beta=\arg\min_\beta\sum_{i=1}^n\bigl[-y_i\log p_i-(1-y_i)\log(1-p_i)\bigr].

  • The sum is the cross-entropy. Its minimizer is the maximum likelihood estimate.
  • With only an intercept, the fitted probability is the sample mean, p̂=y‾\hat p=\bar y. The coefficient is logit(y‾)\operatorname{logit}(\bar y).
  • With inputs, setting the derivative to zero does not give a linear system. The fit is iterative.
  • The objective is convex, so that minimum is unique.

This loss is cross-entropy

The binary loss is the cross-entropy between the observed label and the predicted probability.

Ji=−ylogp−(1−y)log(1−p).J_i=-y\log p-(1-y)\log(1-p).

With more than two labels, the observation is one class. Cross-entropy is then −logpy-\log p_y, the negative log probability of the class that occurred.

  • For class scores z1,…,zKz_1,\ldots,z_K,

pk=ezk∑jezj,∑kpk=1.p_k=\frac{e^{z_k}}{\sum_j e^{z_j}},\qquad \sum_k p_k=1.

  • For observed class yy, the loss is −logpy-\log p_y.

  • Subtracting the largest score before exponentiating leaves the probabilities unchanged and avoids overflow.

Normalization and numerical stability

The three categorical probabilities after softmax
  • Scores: log3,log2,0\log3,\log2,0.
  • Probabilities: 1/2,1/3,1/61/2,1/3,1/6.
  • First class observed: loss log2\log2.

Does adding 1,000 change the answer mathematically?

Show Python: stable probabilities and stable loss
import numpy as np
from scipy.special import softmax, logsumexp
z = np.log([3., 2., 1.]) + 1000
p = softmax(z)
loss = logsumexp(z) - z[0]
print(p, loss)
assert np.allclose(p, [0.5, 1/3, 1/6])
assert np.isclose(loss, np.log(2))

The next token is the same classifier

Two classes used the sigmoid of one logit, and the loss −ylogp−(1−y)log(1−p)-y\log p-(1-y)\log(1-p).

Many classes used the softmax of the logits, and the loss −logpy-\log p_y. A language model repeats that step.

  • The classes are the vocabulary. The scores ziz_i are the logits. Softmax turns them into a distribution over the next token.
  • A sentence factors as a product of those one-token probabilities: P(w1,…,wn∣θ)=∏i=1nP(wi∣w1,…,wi−1,θ). P(w_1,\ldots,w_n\mid\theta)=\prod_{i=1}^n P(w_i\mid w_1,\ldots,w_{i-1},\theta).
  • Training maximizes that likelihood. The loss is the average of −logp-\log p for the token that actually came next.

What is different at that scale

  • The vocabulary is tens of thousands of classes, so the softmax, not the sigmoid, is the expensive step.
  • The training text is the sample. Maximum likelihood fits the text you gave it.
  • A masked model hides a token and still pays −logp-\log p for the hidden one. The loss does not change.
  • Later training from human preferences is no longer this likelihood.
  • A number between zero and one is not yet a calibrated probability. Among cases assigned 0.8, check how often the event happens, on new observations.

The representation limits the boundary

The linear logistic fit cannot enclose the inner cluster

At threshold 0.5: β0+β1x1+β2x2=0.\beta_0+\beta_1x_1+\beta_2x_2=0.

  • Changing a threshold moves a line.
  • It cannot make the line enclose a circle.
  • A hidden layer can change the features.

Which points would a straight boundary always struggle with?

A probability becomes an action

  • The model supplies pp. Act when p≥tp\geq t.
  • The threshold tt depends on the cost of each error.
  • A probability and an action are different outputs.
Outcome 1 Outcome 0
Act True positive False positive
Do not act False negative True negative

realized cost=cFPFP+cFNFN\text{realized cost}=c_{FP}\,FP+c_{FN}\,FN

Expected action costs with unequal error consequences

At p=0.3p=0.3, acting costs 1(1−p)=0.71(1-p)=0.7 and not acting costs 5p=1.55p=1.5.

Why act when the event is less likely than not?

The fitted model stayed fixed

Error counts at three thresholds for the same eight probabilities and outcomes
  • Same eight probabilities.
  • Same eight outcomes.
  • Different actions.

With cFP=1c_{FP}=1, cFN=5c_{FN}=5, the costs are 3, 6, and 16.

Which threshold wins under equal costs?

Supervised Learning Framework

Original code uses its source lesson’s setup and data. Saved outputs, where shown, were not rerun for this edition.

The Prediction Problem:

y=f(x)y = f(x)

Notation:

  • yy: output variable (response)
  • xx: input variable (predictor/feature)
  • f(x)f(x): predictive rule
  • ŷ\hat{y}: predicted output value

Training Dataset: D=(yi,xi)i=1nD = (y_i,x_i)_{i=1}^n

Goal: Design rule to predict yy for new xx

Show original mermaid code 1
%%| fig-width: 6.5
%%| fig-align: center
graph LR
    x --> f((f))
    f --> y

Logistic Function Properties

Original code uses its source lesson’s setup and data. Saved outputs, where shown, were not rerun for this edition.

Key properties:

  • Maps any real number to (0,1)(0,1)
  • σ(0)=0.5\sigma(0) = 0.5
  • Symmetric around 0
  • Smooth S-shaped curve

Original saved output: Logistic Function Properties

Probit vs Logistic Models

Original code uses its source lesson’s setup and data. Saved outputs, where shown, were not rerun for this edition.

Probit model uses normal CDF: Φ−1(pi)=βTxi\Phi^{-1}(p_i) = \beta^Tx_i

Comparison:

  • Both give similar results in practice
  • Logistic more popular (easier computation, multi-class extension)
  • Probit common in economics/psychology

Prediction and Thresholding

Predicted probabilities: p̂i=σ(β̂Txi)\hat{p}_i = \sigma(\hat{\beta}^Tx_i)

Binary prediction: ŷi={1if p̂i>α0if p̂i≤α\hat{y}_i = \begin{cases} 1 & \text{if } \hat{p}_i > \alpha \\ 0 & \text{if } \hat{p}_i \leq \alpha \end{cases}

Common choice: α=0.5\alpha = 0.5

Accuracy: Proportion of correct predictions

Data Overview

Original code uses its source lesson’s setup and data. Saved outputs, where shown, were not rerun for this edition.

Let’s start by loading and exploring the tennis match data:

Code
d = read.csv("data/tennis.csv")
dim(d)

Let’s look at a few columns of randomly selected five rows:

Code
d[sample(1:943,size = 5),c("Player1","Player2","Round","Result","gender","surf")]
  • 943 matches with 44 columns of data
  • Player names, gender, surface type, and match statistics
  • Focus on Break Points Won (BPW) as predictor
  • Result: Binary outcome (Player 1 wins/loses)

Break Points Won vs Match Outcome

Final match statistics are unavailable before the match. Distinguish post-match association from pre-match forecasting. Confirm the data dictionary before interpreting BPW units.

Original code uses its source lesson’s setup and data. Saved outputs, where shown, were not rerun for this edition.

Code
n = dim(d)[1]
plot(d$BPW.1+rnorm(n),d$BPW.2+rnorm(n), pch=21, col=d$Result+2, cex=0.6, bg="yellow", lwd=0.8,
     xlab="BPW by Player 1", ylab="BPW by Player 2")
legend("bottomright", c("P1 won", "P2 won"), col=c(3,2), pch=21, bg="yellow", bty='n')

Original saved output: Break Points Won vs Match Outcome
  • Clear pattern: Number of break points won strongly predicts match outcome
  • This makes intuitive sense: winning break points is fundamental to winning tennis matches
  • Green dots (Player 1 wins) cluster where Player 1 has more break points
  • Red dots (Player 1 loses) cluster where Player 2 has more break points

Data Preparation and Model Fitting

Original code uses its source lesson’s setup and data. Saved outputs, where shown, were not rerun for this edition.

Code
# Remove missing values
which(is.na(d$BPW.1)) # Check for NA values
d = d[-171,]; n = dim(d)[1]  # Remove row with NA

# Fit logistic regression model
library(broom)
library(knitr)
m = glm(Result ~ BPW.1 + BPW.2-1, data=d, family = "binomial")
m %>% tidy() %>% kable()

Model Interpretation

The logistic regression model: log(p1−p)=β1⋅BPW.1+β2⋅BPW.2\log\left(\dfrac{p}{1-p}\right) = \beta_1 \cdot \text{BPW.1} + \beta_2 \cdot \text{BPW.2}

Where:

  • pp = probability of Player 1 winning
  • β1\beta_1 ≈ 0.40 (positive effect of Player 1’s break points)
  • β2\beta_2 ≈ -0.40 (negative effect of Player 2’s break points)
  • Symmetric effects: Winning/losing break points have equal but opposite impacts

Predictions and Confusion Matrix

Final match statistics are unavailable before the match. Distinguish post-match association from pre-match forecasting. Confirm the data dictionary before interpreting BPW units.

Original code uses its source lesson’s setup and data. Saved outputs, where shown, were not rerun for this edition.

Code
pred <- as.integer(m$fitted.values > 0.5)
tab <- table(d$Result, pred, dnn = c("Actual", "Predicted"))
tab
cat("Model accuracy:", round(100 * sum(diag(tab)) / nrow(d), 1), "%\n")

Confusion Matrix Interpretation

Final match statistics are unavailable before the match. Distinguish post-match association from pre-match forecasting. Confirm the data dictionary before interpreting BPW units.

Predicted: YES Predicted: NO
Actual: YES TPR (True Pos) FNR (False Neg)
Actual: NO FPR (False Pos) TNR (True Neg)
  • TPR: True Positive Rate
  • FPR: False Positive Rate
  • TNR: True Negative Rate
  • FNR: False Negative Rate

Visualizing the Classification Line

Original code uses its source lesson’s setup and data. Saved outputs, where shown, were not rerun for this edition.

Code
plot(d$BPW.1+rnorm(n),d$BPW.2+rnorm(n), pch=21, col=d$Result+2, cex=0.6, bg="yellow", lwd=0.8,
     xlab="BPW by Player 1", ylab="BPW by Player 2")
legend("bottomright", c("P1 won", "P2 won"), col=c(3,2), pch=21, bg="yellow", bty='n')

# Add decision boundary
x = seq(0,30,length.out = 200)
y = -m$coefficients[1]*x/m$coefficients[2]
lines(x,y, lwd=2, col="red") 

Original saved output: Visualizing the Classification Line

Decision Boundary Mathematics

The decision boundary occurs where p=0.5p = 0.5, meaning log-odds = 0:

β1x1+β2x2=0\beta_1 x_1 + \beta_2 x_2 = 0

Therefore: x2=−β1β2x1x_2 = \dfrac{-\beta_1}{\beta_2}x_1

Points above the line: Player 2 more likely to win
Points below the line: Player 1 more likely to win

Impact of Winning Break Points

Final match statistics are unavailable before the match. Distinguish post-match association from pre-match forecasting. Confirm the data dictionary before interpreting BPW units.

Original code uses its source lesson’s setup and data. Saved outputs, where shown, were not rerun for this edition.

What happens when Player 1 wins one additional break point?

Code
# Baseline probability (both players at 0 break points)
predict.glm(m, newdata = data.frame(BPW.1 = c(0), BPW.2 = c(0)), type="response")

# After Player 1 wins 1 break point
predict.glm(m, newdata = data.frame(BPW.1 = c(1), BPW.2 = c(0)), type="response")

Effect: Probability increases from 50% to 60%

Odds Ratio Calculation

Final match statistics are unavailable before the match. Distinguish post-match association from pre-match forecasting. Confirm the data dictionary before interpreting BPW units.

Original code uses its source lesson’s setup and data. Saved outputs, where shown, were not rerun for this edition.

Code
# Odds ratio for one additional break point
exp(0.4019)

Interpretation: Each additional break point won increases the odds of winning by a factor of 1.5

Mathematical derivation: p1−p=1.5⇒p=0.6\dfrac{p}{1-p} = 1.5 \Rightarrow p = 0.6

Cumulative Effect

Final match statistics are unavailable before the match. Distinguish post-match association from pre-match forecasting. Confirm the data dictionary before interpreting BPW units.

Original code uses its source lesson’s setup and data. Saved outputs, where shown, were not rerun for this edition.

What about winning 3 more break points than the opponent?

Code
predict.glm(m, newdata = data.frame(BPW.1 = c(0), BPW.2 = c(0)), type="response")
predict.glm(m, newdata = data.frame(BPW.1 = c(3), BPW.2 = c(0)), type="response")

Result: Probability increases by 27 percentage points (from 50% to 77%)

Original saved output: Cumulative Effect

Research Question

Original code uses its source lesson’s setup and data. Saved outputs, where shown, were not rerun for this edition.

“Are women’s matches less predictable than men’s matches?”

This is a common claim in tennis commentary. We can test this using model residuals.

Code
library(dplyr)
d$res = abs(m$residuals)
outlind = which(d$res<2)  # Remove extreme outliers
boxplot(d$res[outlind] ~ d$gender[outlind], col=c(2,3), xlab="Gender", ylab="Residual")

Larger residuals = Less accurate predictions = More unpredictable matches

Statistical Test

Original code uses its source lesson’s setup and data. Saved outputs, where shown, were not rerun for this edition.

Code
men = d %>% filter(res<2, gender=="M") %>% pull(res)
women = d %>% filter(res<2, gender=="W") %>% pull(res)
t.test(men, women, alternative = "two.sided") %>% tidy() %>% kable()
  • Mean difference: 0.07 (women have higher residuals)
  • t-statistic: -4.7 (highly significant)
  • p-value: < 0.001

Conclusion: The conventional wisdom is statistically supported - women’s tennis matches are indeed less predictable based on break points won.

Key Findings

  1. Strong Predictor: Break points won is highly predictive of match outcomes
  2. Symmetric Effects: Winning/losing break points have equal magnitude effects
  3. Quantified Impact: Each break point increases winning odds by 50%
  4. High Accuracy: Model achieves ~88% prediction accuracy
  5. Gender Difference: Women’s matches are significantly less predictable
  • Logistic regression effectively models binary sports outcomes
  • Confusion matrices provide comprehensive performance evaluation
  • Residual analysis can reveal interesting domain-specific patterns
  • Statistical testing validates common beliefs with data

Generating Non-linearly Separable Data

Original code uses its source lesson’s setup and data. Saved outputs, where shown, were not rerun for this edition.

Let’s create a circular dataset to demonstrate the kernel trick:

Original saved output: Generating Non-linearly Separable Data

The Kernel Trick Solution

The data in the circle-data plot is clearly not linearly separable. However, if we map it to a three-dimensional space using the transformation: ϕ:R2→R3(x1,x2)↦(z1,z2,z3)=(x12,2x1x2,x22), \begin{aligned} \phi: R^{2} & \longrightarrow R^{3} \\ \left(x_{1}, x_{2}\right) & \longmapsto\left(z_{1}, z_{2}, z_{3}\right)=\left(x_{1}^{2}, \sqrt{2} x_{1} x_{2}, x_{2}^{2}\right), \end{aligned} and attempt to linearly separate the transformed data, the decision boundaries become hyperplanes in R3R^{3}, expressed as ωTz+b=0\omega^{T} z + b = 0. In terms of the original variables xx, these boundaries take the form: ω1x12+ω22x1x2+ω3x22=0, \omega_{1} x_{1}^{2} + \omega_{2} \sqrt{2} x_{1} x_{2} + \omega_{3} x_{2}^{2} = 0, which corresponds to the equation of an ellipse. This demonstrates that we can apply a linear algorithm to transformed data to achieve a non-linear decision boundary with minimal effort.

The Gram Matrix and Kernels

Now, consider what the algorithm is actually doing. It relies solely on the Gram matrix KK of the data. Once KK is computed, the original data can be discarded: K=[x1Tx1x1Tx2⋯x2Tx1⋱⋮]n×n=XXT,whereX=[x1T⋮xnT]n×d. \begin{aligned} K & = \left[\begin{array}{ccc} x_{1}^{T} x_{1} & x_{1}^{T} x_{2} & \cdots \\ x_{2}^{T} x_{1} & \ddots & \\ \vdots & & \end{array}\right]_{n \times n} = X X^{T}, \\ \text{where} \quad X & = \left[\begin{array}{c} x_{1}^{T} \\ \vdots \\ x_{n}^{T} \end{array}\right]_{n \times d}. \end{aligned} Here, XX, which contains all the data, is referred to as the design matrix.

Kernel Matrix After Transformation

When we map the data using ϕ\phi, the Gram matrix becomes: K=[ϕ(x1)Tϕ(x1)ϕ(x1)Tϕ(x2)⋯ϕ(x2)Tϕ(x1)⋱⋮]. K = \left[\begin{array}{ccc} \phi\left(x_{1}\right)^{T} \phi\left(x_{1}\right) & \phi\left(x_{1}\right)^{T} \phi\left(x_{2}\right) & \cdots \\ \phi\left(x_{2}\right)^{T} \phi\left(x_{1}\right) & \ddots & \\ \vdots & & \end{array}\right]. Let us compute these inner products explicitly. For vectors rr and ss in R3R^{3} corresponding to aa and bb, respectively: ⟨r,s⟩=r1s1+r2s2+r3s3=a12b12+2a1a2b1b2+a22b22=(a1b1+a2b2)2=⟨a,b⟩2. \begin{aligned} \langle r, s \rangle & = r_{1} s_{1} + r_{2} s_{2} + r_{3} s_{3} \\ & = a_{1}^{2} b_{1}^{2} + 2 a_{1} a_{2} b_{1} b_{2} + a_{2}^{2} b_{2}^{2} \\ & = (a_1 b_1 + a_2 b_2)^2 \\ & = \langle a, b \rangle^{2}. \end{aligned}

where a=(a1,a2)a = (a_1, a_2) and b=(b1,b2)b = (b_1, b_2) are the original 2D vectors, and r=ϕ(a)r = \phi(a) and s=ϕ(b)s = \phi(b) are their transformations in R3R^3.

Visualizing the Transformation

Original code uses its source lesson’s setup and data. Saved outputs, where shown, were not rerun for this edition.

Let’s implement and visualize the transformation:

Original saved output: Visualizing the Transformation

Tree Example

Figure 1: Elementary tree scheme; visualization of the splitting process

Tree Building Process

Three main components:

  1. Splitting: Divide data based on feature values to create homogeneous subsets
  2. Stopping: Decide when to stop splitting (prevent overfitting)
  3. Pruning: Remove nodes that don’t improve accuracy

Goal: Find regions R1,R2,…,RJR_1, R_2, \ldots, R_J that minimize: RSS=∑j=1J∑i∈Rj(yi−y‾j)2\text{RSS} = \sum_{j=1}^J\sum_{i \in R_j}(y_i - \bar{y}_j)^2

Recursive Binary Splitting (CART)

Algorithm: Top-down, greedy approach

At each step, find optimal split:

  • Choose feature jj and split point ss
  • Create regions: R1(j,s)={x∣xj<s}R_1(j,s) = \{x \mid x_j < s\} and R2(j,s)={x∣xj≥s}R_2(j,s) = \{x \mid x_j \geq s\}

Optimization problem: minj,s[∑i:xi∈R1(yi−y‾1)2+∑i:xi∈R2(yi−y‾2)2]\min_{j,s}\left[ \sum_{i:x_i\in R_1}(y_i - \bar{y}_1)^2 + \sum_{i:x_i \in R_2}(y_i - \bar{y}_2)^2\right]

Prediction in region RjR_j: f(x)=y‾j=Average(yi∣xi∈Rj)f(x) = \bar{y}_j = \text{Average}(y_i \mid x_i \in R_j)

Diamond Example

  • Imagine you’re a jewelry appraiser determining a diamond’s value
  • You follow a series of questions: Is the carat weight above 1.0?
  • If yes, is the clarity VS1 or better?
  • Each question leads to another, creating a decision path
  • This mirrors our natural decision-making process

Decision Trees: The Concept

Decision trees create a flowchart of if-then rules that:

  • Mirror human decision-making processes
  • Create interpretable prediction rules
  • Handle non-linear relationships naturally
  • Capture feature interactions automatically

Our Journey Today

We’ll explore tree-based models using the classic diamonds dataset:

  • 53,940 diamonds with prices and attributes
  • Start with simple decision trees
  • Progress to ensemble methods (random forests, gradient boosting)
  • Develop insights into when and how to use these algorithms
  • Learn to avoid common pitfalls

The Diamonds Dataset

Variable Description Values
carat Weight of the diamond Numeric
cut Quality of the cut Fair, Good, Very Good, Premium, Ideal
color Color of the diamond J, I, H, G, F, E, D
clarity Clarity of the diamond I1, SI2, SI1, VS2, VS1, VVS2, VVS1, IF
depth Depth of the diamond Numeric
table Width of the diamond’s table Numeric

Loading the Data

Original code uses its source lesson’s setup and data. Saved outputs, where shown, were not rerun for this edition.

Price vs Carat Relationship

Original code uses its source lesson’s setup and data. Saved outputs, where shown, were not rerun for this edition.

Original saved output: Price vs Carat Relationship

Log-Transformed Relationships

Original code uses its source lesson’s setup and data. Saved outputs, where shown, were not rerun for this edition.

Original saved output: Log-Transformed Relationships

Beyond Carat: The Role of Clarity

Original code uses its source lesson’s setup and data. Saved outputs, where shown, were not rerun for this edition.

Although carat is the most important factor, it’s not the only one:

Original saved output: Beyond Carat: The Role of Clarity

Building Our First Decision Tree

Original code uses its source lesson’s setup and data. Saved outputs, where shown, were not rerun for this edition.

Let’s start simple with just two predictors:

Original saved output: Building Our First Decision Tree

Visualizing the Feature Space

Original code uses its source lesson’s setup and data. Saved outputs, where shown, were not rerun for this edition.

Observation: Clarity becomes most important around 1 carat level

Original saved output: Visualizing the Feature Space

Tree Prediction Regions

Original code uses its source lesson’s setup and data. Saved outputs, where shown, were not rerun for this edition.

Original saved output: Tree Prediction Regions

Understanding Prediction Regions

The visualization shows several key patterns:

  • Vertical bands indicate carat as strongest predictor
  • Non-linear patterns that linear models would miss
  • Rectangular regions with sharp boundaries
  • Rate of price increase varies across clarity levels

Note

The Algorithm:

  1. Divide predictor space into JJ distinct, non-overlapping regions: R1,R2,…,RJR_1, R_2, \ldots, R_J
  2. For every observation in region RjR_j, make the same prediction
  3. Prediction = mean of response values for training observations in RjR_j

Next Steps

From here we’ll explore:

  • Tree construction algorithms (recursive binary splitting)
  • Pruning techniques to avoid overfitting
  • Ensemble methods (Random Forests, Gradient Boosting)
  • Hyperparameter tuning for optimal performance
  • Model interpretation and feature importance

Key insights:

  • Primary split on carat (most important predictor)
  • Secondary splits on clarity
  • Rectangular prediction regions
  • Natural handling of feature interactions

Example: Boston Housing

For Saratoga use the revised 1,728-row fit. Its intercept is extrapolation, not an identified land value. Legacy dataset with a problematic constructed racial variable. Retained for historical critique, not recommended as an unqualified classroom benchmark.

Original code uses its source lesson’s setup and data. Saved outputs, where shown, were not rerun for this edition.

Results: Step function fit with 7 regions, clear visualization of decision boundaries

Original saved output: Example: Boston Housing

Random Forest Example

Original code uses its source lesson’s setup and data. Saved outputs, where shown, were not rerun for this edition.

Variable importance: Total decrease in node impurity when splitting on each variable, averaged over all trees

Original saved output: Random Forest Example

Team practice

  • State the proposed project’s prediction time, available inputs, target, and action.

  • Explain who bears a false positive and a false negative.

  • Name a simple baseline. Identify a result that would make you reconsider the project question.

What does a logit of zero mean?

Why is a probability of 0.99 costly when the event fails to happen?

What changes in the fitted parameters when you change only the threshold?

What happens to the preferred threshold when false negatives become more costly?

Which fit would you use?

Validation, generalization, and leakage.

Three fitted polynomial models

Choose before seeing new observations. State the evidence you wish you had.

θ̂=argminθ1n∑iJi(θ).\hat\theta=\arg\min_\theta\frac1n\sum_i J_i(\theta).

  • A small loss on the same observations answers a limited question.

  • We need evidence about observations that did not participate in fitting or selecting the model.

Three roles for data

Data Job
Training Fit parameters and preprocessing
Validation Choose features, models, and tuning settings
Test Evaluate the fixed choice

Selecting a model is a use of data, even when no coefficient is fitted directly to those data.

A baseline gives the score meaning

  • For regression, predict the training mean.
  • Keep validation outcomes out of that estimate.
  • Compare all models on the same observations and metric.
import numpy as np
y_train = np.array([1., 3., 3.])
y_validation = np.array([2., 4.])
baseline = y_train.mean()
mse = np.mean((y_validation - baseline)**2)
print(baseline, mse)       # 2.333... and 1.444...
assert np.isclose(mse, 13/9)

Why would using the validation mean change the experiment?

MSE=1m∑i=1m(yi−ŷi)2.\operatorname{MSE}=\frac1m\sum_{i=1}^m(y_i-\hat y_i)^2.

mm is the number of observations being evaluated.

  • RMSE is MSE\sqrt{\operatorname{MSE}}, in the units of the response.

  • The metric must reflect the question. A large error counts strongly under squared loss.

Training and validation error for the same polynomial fits

The ranking on the training observations need not be the ranking on the validation observations.

A random split can answer the wrong question

Prediction time: before a tennis match starts.

Proposed input Available then?
Player identities and scheduled surface Yes
Past-match summaries computed before today Potentially
Today’s final break-point statistics No
Today’s final score No
  • A random split does not repair an input that arrives too late.
  • Separating time or players must match the intended use.

Would your answer change for a post-match explanation?

The feature used the answer

Match outcomes plotted against final recorded tennis statistics

Original tennis example

  • A striking pattern is visible.
  • Both axes use statistics recorded during the match.
  • Those values are unavailable before the match.

Good explanation after the event, or a usable prediction before it?

Preprocessing also learns from data

  • Scaling estimates a mean and a spread.
  • Learn them on training observations only.
  • Reuse that transformation on validation observations.
Show Python: fit on training, transform validation
import numpy as np
from sklearn.preprocessing import StandardScaler
train = np.array([[1.], [2.], [3.]])
validation = np.array([[100.]])
scaler = StandardScaler().fit(train)
print(scaler.mean_, scaler.transform(validation))
assert np.allclose(scaler.mean_, [2.])

If you fitted the scaler again on the single validation case, what would happen?

Cross-validation repeats a fitting experiment

Five folds take turns as validation data
  • Fit on four folds. Score on the fifth.
  • Repeat for every proposed setting.
  • 10 settings × 5 folds = 50 fits, plus the final refit.

What does parallel execution change: elapsed time, total work, or both?

A team tries twenty models and reports the smallest test error.

What did the test set become?

It participated in selection. A fresh evaluation is needed for the selected procedure.

The betting example: what would convince us?

Recall the original betting performance plot.

Check Question for this example
Prediction time Were those odds available when the choice was made?
Selection Did the same results choose and evaluate the rule?
Baseline Does the comparison use a comparable opportunity set and stake?
Execution Could the quoted bets actually be placed?

Which check would you run before trusting the blue curve?

Kaunitz, Zhong, and Kreiner (2017): historical simulations, paper trading, and a smaller real-money experiment.

The original hard function: outside the observed range

Polynomial approximation inside and outside the observed range
  • f(x)=1/(1+25x2)f(x)=1/(1+25x^2), observed on the shaded interval [−2,2][-2,2].
  • Predictions outside that range are extrapolation.
  • A better fit inside need not behave sensibly outside. Curves leaving the panel are clipped.
Show Python: a degree-20 fit at an unobserved input
import numpy as np
x = np.linspace(-2, 2, 401)
f = lambda x: 1 / (1 + 25*x*x)
fit = np.polynomial.Polynomial.fit(x, f(x), deg=20)
print("At x=2.5:", fit(2.5), "true:", f(2.5))

ROC Example (Defualt Data Set)

Original code uses its source lesson’s setup and data. Saved outputs, where shown, were not rerun for this edition.

Build logistic regression model

ROC Curve

Original code uses its source lesson’s setup and data. Saved outputs, where shown, were not rerun for this edition.

Define the ROC curve function

Plot the ROC Curve

Original code uses its source lesson’s setup and data. Saved outputs, where shown, were not rerun for this edition.

Original saved output: Plot the ROC Curve

The Trading Algorithm Challenge

The Scenario: You’re a quant at a trading firm with a new algorithm that outperformed the state-of-the-art on historical data.

The Question:

  • Did you discover a truly dominant strategy?
  • Or did you just get lucky?

Sequential Analysis:

  • Bayesian methods
  • Decides how long to wait for sufficient evidence
  • Balances exploration vs exploitation

Trading

SimCity AB Test

SimCity Original

SimCity Variation

Electronic Arts SimCity 5: AB Testing Success

The Problem:

  • 1.1M copies sold in first 2 weeks
  • 50% digital downloads
  • Promotional banner not driving expected pre-orders

The Test:

  • Original: Banner with promotional offer
  • Variation: No promotional messaging

The Surprising Result:

  • 43.4% more purchases with no offer!
  • People just wanted to buy the game
  • No extra incentive necessary

SimCity AB Test: Statistical Analysis

Original code uses its source lesson’s setup and data. Saved outputs, where shown, were not rerun for this edition.

Test Setup:

  • Pink background: 40% purchase rate, 500 visitors
  • Black background: 30% purchase rate, 550 visitors

Result: Pink background significantly outperforms!

The Black Monday Event

Original code uses its source lesson’s setup and data. Saved outputs, where shown, were not rerun for this edition.

October 19, 1987: S&P 500 dropped -21.76%

Historical Context: - Prior monthly returns: 1.2% mean, 4.3% volatility - Distribution: X∼N(1.2,4.32)X \sim N(1.2, 4.3^2)

Z-Score Calculation: Z=X−μσ=−0.2176−0.0120.043=−5.34Z = \frac{X-\mu}{\sigma} = \frac{-0.2176 - 0.012}{0.043} = -5.34

Interpretation:

  • This is a 5-sigma event
  • Under normal model: P(X<−0.2176)=P(X < -0.2176) =

An extremely rare occurrence!

Patriots Coin Toss: Confidence Interval

Original code uses its source lesson’s setup and data. Saved outputs, where shown, were not rerun for this edition.

Conclusion: Since 0.5 is outside the confidence interval, we have evidence that coin tosses were not fair.

The Question: Is Yawning Contagious?

2006 Discovery Channel Experiment

  • 50 participants total
  • 34 in experimental group (interviewer yawned)
  • 16 in control group (no yawn)

Results:

  • Experimental: 10/34 yawned (29.4%)
  • Control: 4/16 yawned (25.0%)
  • Difference: 4.4%

Mythbusters Conclusion: Yawning is contagious!

But is this statistically significant?

Mythbusters: Statistical Analysis

Original code uses its source lesson’s setup and data. Saved outputs, where shown, were not rerun for this edition.

Statistical Conclusion: Large overlap, CI contains 0 - no evidence of difference!

Original saved output: Mythbusters: Statistical Analysis

Google Search Algorithm Test

The Experiment:

  • Test effectiveness of new search algorithm
  • Measure: Click-through rate on search results
  • Random assignment to Algo 1 or Algo 2
  • 2500 requests per algorithm
Algo1 Algo2
Success 1755 1818
Failure 745 682
Total 2500 2500

Estimated Success Rates:

  • Algo 1: p̂1=0.702\hat{p}_1 = 0.702
  • Algo 2: p̂2=0.727\hat{p}_2 = 0.727

Google Search: Confidence Intervals

Original code uses its source lesson’s setup and data. Saved outputs, where shown, were not rerun for this edition.

Result: Intervals don’t overlap, difference CI doesn’t contain 0 - Algo 2 is significantly better!

The Challenge

Original code uses its source lesson’s setup and data. Saved outputs, where shown, were not rerun for this edition.

Pepsi’s Claim: “More than half of Diet Coke drinkers prefer Diet Pepsi”

  • The Test: Double-blind experiment with 100 drinkers

  • Result: 56 favor Pepsi

  • Hypothesis Setup:

    • H0:p=0.5H_0: p = 0.5 (no preference)
    • H1:p>0.5H_1: p > 0.5 (Pepsi preferred)

Conclusion: p=0.5p=0.5 is in the CI - Pepsi’s claim is not supported!

Avonex: FDA vs Biogen

Historical teaching case. Clinical or company claims require source review before reuse as current evidence. The supplied numbers are not clinical guidance.

The Dispute

Original code uses its source lesson’s setup and data. Saved outputs, where shown, were not rerun for this edition.

Biogen’s Claim: “95% patient satisfaction rate” FDA Investigation: 60% satisfaction in random sample of 75 patients Question: Who is right?

Hypothesis Test: - H0:p=0.95H_0: p = 0.95 (Biogen innocent) - H1:p<0.95H_1: p < 0.95 (FDA right) - α=0.01\alpha = 0.01 (1% significance level)

Result: Z = -14, p-value ≈ 0 - FDA is right, Biogen is wrong!

Pfizer Viagra: Safety Concerns

Historical teaching case. Clinical or company claims require source review before reuse as current evidence. The supplied numbers are not clinical guidance.

The Safety Question

Original code uses its source lesson’s setup and data. Saved outputs, where shown, were not rerun for this edition.

1998 Data:

  • 6 million Viagra users: 77 deaths from coronary problems
  • 1.5 million non-users: 11 deaths from coronary problems Pfizer’s Claim: Death rate no higher than general population

Statistical Analysis:

  • Viagra rate: p̂1=77/6,000,000=0.00001283\hat{p}_1 = 77/6,000,000 = 0.00001283
  • Control rate: p̂2=11/1,500,000=0.00000733\hat{p}_2 = 11/1,500,000 = 0.00000733

Result: CI doesn’t contain 0 - evidence of higher death rate with Viagra!

Nobel Prize Discovery (1904)

Original code uses its source lesson’s setup and data. Saved outputs, where shown, were not rerun for this edition.

The Experiment:

  • Method 1: Remove oxygen from air, measure remaining gas density
  • Method 2: Prepare pure nitrogen by chemical decomposition
  • Question: Are the densities the same?

The Data:

Rayleigh’s Discovery: Statistical Test

Original code uses its source lesson’s setup and data. Saved outputs, where shown, were not rerun for this edition.

The Discovery: - Z-score ≈ 20 (20-sigma event!) - Massive statistical significance - Argon was discovered - the “inert” gas in air!

Original saved output: Rayleigh’s Discovery: Statistical Test

The Bias-Variance Trade-off

Original code uses its source lesson’s setup and data. Saved outputs, where shown, were not rerun for this edition.

The Hard Function Example

Inspect the actual experiment. A named regime or curve is not a universal result. Separate interpolation, noise fitting, extrapolation, basis conditioning and floating-point effects.

Original code uses its source lesson’s setup and data. Saved outputs, where shown, were not rerun for this edition.

Approximating a challenging function: f(x)=11+25x2f(x) = \frac{1}{1+25x^2}

Hard Function: Key Insights

Inspect the actual experiment. A named regime or curve is not a universal result. Separate interpolation, noise fitting, extrapolation, basis conditioning and floating-point effects.

  • Training Region: x∈[−2,2]x \in [-2,2]
  • Test Region: x∈[−3,−2)∪(2,3]x \in [-3,-2) \cup (2,3]

Observations:

  • Linear model: poor fit everywhere
  • Degree 2: captures some curvature
  • Degree 5: reasonable approximation
  • Degree 20: catastrophic overfitting!

Lesson: High-degree polynomials fit training data perfectly but fail completely on test data

Einstein’s Principle: “A model should be simple, but not simpler”

Solution: Regularization!

Data Quality Challenges

  • Missing values: Systematic vs random patterns
  • Measurement errors: Sensor noise, human error
  • Sampling bias: Non-representative samples
  • Label noise: Incorrect classifications
  • Temporal drift: Changing data distributions

Solutions:

  • Data cleaning pipelines
  • Robust estimation methods
  • Uncertainty quantification
  • Professional annotation services (Scale AI, Toloka)

Model Explainability

Why Explainability Matters:

  • Healthcare: diagnosis reasoning
  • Finance: loan decisions
  • Legal: GDPR compliance
  • Science: understanding mechanisms

Modern Techniques:

  • LIME: local explanations
  • SHAP: unified framework
  • Attention mechanisms
  • Gradient-based methods
  • Counterfactual explanations

Session Structure (45 minutes)

The numerical Bayes exercise is illustrative. Do not infer that the named deployed system uses this exact probabilistic architecture.

  1. Quick Context (5 min) - Introduction to Bayesian Health and their approach
  2. Small Group Brainstorm (10 min) - Analyze a clinical scenario
  3. Round Table Reporting (15 min) - Share insights and debate approaches
  4. Instructor Wrap-Up (15 min) - Technical deep dive and reflection

Today’s Focus

The numerical Bayes exercise is illustrative. Do not infer that the named deployed system uses this exact probabilistic architecture.

How can Bayesian methods transform healthcare from reactive to proactive?

From MYCIN’s rule-based approach in the 1970s to modern Bayesian AI

The Problem: Information Overload in Healthcare

Historical teaching case. Clinical or company claims require source review before reuse as current evidence. The supplied numbers are not clinical guidance. The numerical Bayes exercise is illustrative. Do not infer that the named deployed system uses this exact probabilistic architecture.

Healthcare generates massive amounts of data:

  • Electronic Health Records (EHRs)
  • Lab results updated continuously
  • Vital signs monitored in real-time
  • Imaging studies
  • Clinical notes

But clinicians are overwhelmed and critical events are missed

The numerical Bayes exercise is illustrative. Do not infer that the named deployed system uses this exact probabilistic architecture.

How do we transform raw healthcare data into actionable insights that save lives?

Bayesian Health: Company Overview

Historical teaching case. Clinical or company claims require source review before reuse as current evidence. The supplied numbers are not clinical guidance. The numerical Bayes exercise is illustrative. Do not infer that the named deployed system uses this exact probabilistic architecture.

Founded by: Dr. Suchi Saria (Johns Hopkins)

Mission: Transform healthcare data into clinical insights using adaptive AI

Key Innovation: Active Clinical Awareness platform

Approach: Bayesian probabilistic models for: - Early warning systems - Sepsis detection - Pressure ulcer prevention - Clinical deterioration prediction

Recent Recognition:

  • Time Best Inventions 2024
  • BioTech AI Company of the Year 2023
  • Women In AI Entrepreneur 2023

Clinical Deployment: Cleveland Clinic system-wide expansion

Why Bayesian Methods for Healthcare?

Historical teaching case. Clinical or company claims require source review before reuse as current evidence. The supplied numbers are not clinical guidance. The numerical Bayes exercise is illustrative. Do not infer that the named deployed system uses this exact probabilistic architecture.

Original code uses its source lesson’s setup and data. Saved outputs, where shown, were not rerun for this edition.

Traditional AI (Rules-Based):

Show original text code 1
IF (Temperature > 38°C AND Heart_Rate > 100) 
   THEN Alert = "Possible Sepsis"

Problems: - Brittle rules - No uncertainty quantification - Can’t learn from data - High false positive rates

Bayesian Approach: Probabilistic Reasoning

The numerical Bayes exercise is illustrative. Do not infer that the named deployed system uses this exact probabilistic architecture.

Key Advantage: Updates beliefs as new evidence arrives

P(Disease∣Symptoms, History, Labs)=P(Symptoms, Labs∣Disease)⋅P(Disease∣History)P(Symptoms, Labs)P(\text{Disease} \mid \text{Symptoms, History, Labs}) = \frac{P(\text{Symptoms, Labs} \mid \text{Disease}) \cdot P(\text{Disease} \mid \text{History})}{P(\text{Symptoms, Labs})}

  • Prior: P(Disease∣History)P(\text{Disease} \mid \text{History}) - Based on patient history
  • Likelihood: P(Symptoms, Labs∣Disease)P(\text{Symptoms, Labs} \mid \text{Disease}) - Clinical evidence
  • Posterior: Updated probability of disease

The numerical Bayes exercise is illustrative. Do not infer that the named deployed system uses this exact probabilistic architecture.

Combines prior medical knowledge with real-time patient data to provide probabilistic risk scores

The Clinical Problem: Sepsis

Historical teaching case. Clinical or company claims require source review before reuse as current evidence. The supplied numbers are not clinical guidance. The numerical Bayes exercise is illustrative. Do not infer that the named deployed system uses this exact probabilistic architecture.

Sepsis: Life-threatening organ dysfunction caused by infection

  • Prevalence: 1.7 million cases/year in US
  • Mortality: 270,000 deaths/year (15-30% mortality rate)
  • Time-sensitive: Every hour delay in treatment increases mortality by 4-8%
  • Cost: $62 billion/year in US healthcare costs

The Challenge: Early detection is critical but difficult

Traditional Sepsis Screening

Historical teaching case. Clinical or company claims require source review before reuse as current evidence. The supplied numbers are not clinical guidance. The numerical Bayes exercise is illustrative. Do not infer that the named deployed system uses this exact probabilistic architecture.

SIRS Criteria (Systemic Inflammatory Response Syndrome):

At least 2 of: - Temperature < 36°C or > 38°C - Heart rate > 90 bpm - Respiratory rate > 20/min - WBC < 4,000 or > 12,000 cells/mm³

Problems: - Low specificity (many false positives) - Detected too late - Doesn’t account for patient-specific factors - Rule-based, not probabilistic

Clinical Scenario

Historical teaching case. Clinical or company claims require source review before reuse as current evidence. The supplied numbers are not clinical guidance. The numerical Bayes exercise is illustrative. Do not infer that the named deployed system uses this exact probabilistic architecture.

Patient: 68-year-old male, post-surgery day 3

Current Status: - Temperature: 37.8°C (slightly elevated) - Heart Rate: 95 bpm (slightly elevated) - Blood Pressure: 110/70 (normal) - Recent trend: HR increasing from 85 to 95 over 6 hours - Labs: WBC 11,500 (borderline), Lactate 1.8 mmol/L

Question for Groups:

Group Discussion Task (10 min)

The numerical Bayes exercise is illustrative. Do not infer that the named deployed system uses this exact probabilistic architecture.

  1. What additional information would help assess sepsis risk?
  2. How would a Bayesian model differ from a rule-based system here?
  3. What are the trade-offs between sensitivity and specificity?
  4. How should prior patient history influence the decision?

Assign roles: Facilitator, Note-taker, Timekeeper, Reporter

Brainstorm Prompts

The numerical Bayes exercise is illustrative. Do not infer that the named deployed system uses this exact probabilistic architecture.

Consider these perspectives:

Clinical Perspective: - What subtle patterns might indicate early sepsis? - How do trends matter vs. single measurements?

Statistical Perspective: - How do we quantify uncertainty? - What’s the cost of false positives vs. false negatives?

ML/AI Perspective: - What features should the model learn? - How do we update predictions in real-time?

Group Presentations

The numerical Bayes exercise is illustrative. Do not infer that the named deployed system uses this exact probabilistic architecture.

Each group shares (2-3 min each):

  1. Key insights from your discussion
  2. Most important factors you identified
  3. Biggest challenges in implementation
  4. One question that emerged

The numerical Bayes exercise is illustrative. Do not infer that the named deployed system uses this exact probabilistic architecture.

After presentations, class discussion:

Discussion Points

The numerical Bayes exercise is illustrative. Do not infer that the named deployed system uses this exact probabilistic architecture.

Ethics & Trust: - Should algorithms override clinical judgment? - How transparent should the model be?

Implementation: - How to reduce alert fatigue? - Integration with existing workflows?

Equity: - Do Bayesian priors perpetuate bias? - Performance across diverse populations?

Bayesian Health’s TREWS System

Historical teaching case. Clinical or company claims require source review before reuse as current evidence. The supplied numbers are not clinical guidance. The numerical Bayes exercise is illustrative. Do not infer that the named deployed system uses this exact probabilistic architecture.

TREWS: Targeted Real-time Early Warning Score

Published in Nature Medicine (2022)

Key Innovation: Patient-specific dynamic risk assessment

P(Sepsist∣Data1:t,Patient History)=fBayesian(all available information)P(\text{Sepsis}_t \mid \text{Data}_{1:t}, \text{Patient History}) = f_{\text{Bayesian}}(\text{all available information})

  • Updates every hour
  • Uses 65+ features from EHR
  • Incorporates temporal trends
  • Patient-specific baselines

Technical Approach: Bayesian Networks

The numerical Bayes exercise is illustrative. Do not infer that the named deployed system uses this exact probabilistic architecture.

Original code uses its source lesson’s setup and data. Saved outputs, where shown, were not rerun for this edition.

Show original mermaid code 1
%%| fig-width: 6
%%| fig-align: center
graph TB
    PH[Patient History] --> Prior[Prior Risk]
    VS[Vital Signs] --> Likelihood[Likelihood]
    Labs[Lab Results] --> Likelihood
    Prior --> Post[Posterior Risk]
    Likelihood --> Post
    Post --> Alert{Alert Threshold}
    Alert -->|High Risk| Notify[Notify Clinician]
    Alert -->|Low Risk| Monitor[Continue Monitoring]

Advantages over simple ML: - Incorporates domain knowledge - Quantifies uncertainty - Handles missing data naturally - Interpretable reasoning chain

Mathematical Framework

The numerical Bayes exercise is illustrative. Do not infer that the named deployed system uses this exact probabilistic architecture.

Hierarchical Bayesian Model:

Level 1 - Patient-specific parameters: θi∼P(θ∣α)\theta_i \sim P(\theta \mid \alpha)

Level 2 - Population parameters: α∼P(α)\alpha \sim P(\alpha)

Level 3 - Observations: yit∼P(y∣θi,xit)y_{it} \sim P(y \mid \theta_i, x_{it})

where: - θi\theta_i = patient-specific parameters - α\alpha = population-level hyperparameters
- yity_{it} = outcome at time tt for patient ii - xitx_{it} = observed features

Bayes Rule in Action: Sepsis Detection

Historical teaching case. Clinical or company claims require source review before reuse as current evidence. The supplied numbers are not clinical guidance. The numerical Bayes exercise is illustrative. Do not infer that the named deployed system uses this exact probabilistic architecture.

Prior Probability (before new labs): P(Sepsis)=0.03 (3% based on patient risk factors)P(\text{Sepsis}) = 0.03 \text{ (3% based on patient risk factors)}

New Evidence: Lactate = 2.5 mmol/L

P(Lactate≥2.5∣Sepsis)=0.70P(\text{Lactate} \geq 2.5 \mid \text{Sepsis}) = 0.70 P(Lactate≥2.5∣No Sepsis)=0.10P(\text{Lactate} \geq 2.5 \mid \text{No Sepsis}) = 0.10

Posterior Probability: P(Sepsis∣Lactate≥2.5)=0.70×0.030.70×0.03+0.10×0.97=0.0210.118=0.178P(\text{Sepsis} \mid \text{Lactate} \geq 2.5) = \frac{0.70 \times 0.03}{0.70 \times 0.03 + 0.10 \times 0.97} = \frac{0.021}{0.118} = 0.178

Risk increases from 3% to 17.8% with new evidence!

Dynamic Updating: The Power of Sequential Bayes

The numerical Bayes exercise is illustrative. Do not infer that the named deployed system uses this exact probabilistic architecture.

Hour 1: Prior risk = 3%

Hour 2: New HR trend → Posterior = 8% (becomes new prior)

Hour 3: New lab results → Posterior = 18%

Hour 4: BP drops → Posterior = 45% → ALERT!

P(Sepsist∣All data up to time t)=P(New datat∣Sepsis)⋅P(Sepsist−1∣Previous data)P(New datat)P(\text{Sepsis}_t \mid \text{All data up to time } t) = \frac{P(\text{New data}_t \mid \text{Sepsis}) \cdot P(\text{Sepsis}_{t-1} \mid \text{Previous data})}{P(\text{New data}_t)}

The numerical Bayes exercise is illustrative. Do not infer that the named deployed system uses this exact probabilistic architecture.

Each new piece of evidence updates the probability, incorporating the full history

Handling Uncertainty: Credible Intervals

The numerical Bayes exercise is illustrative. Do not infer that the named deployed system uses this exact probabilistic architecture.

Unlike point predictions, Bayesian methods provide credible intervals:

P(0.35≤Sepsis Risk≤0.55)=0.95P(0.35 \leq \text{Sepsis Risk} \leq 0.55) = 0.95

“We are 95% confident the true risk is between 35% and 55%”

Clinical Value: - High uncertainty → gather more data before acting - Low uncertainty → confident in recommendation - Transparent about what model doesn’t know

Clinical Trial Results (Nature Medicine 2022)

Historical teaching case. Clinical or company claims require source review before reuse as current evidence. The supplied numbers are not clinical guidance. The numerical Bayes exercise is illustrative. Do not infer that the named deployed system uses this exact probabilistic architecture.

Study: Randomized controlled trial at Johns Hopkins

TREWS vs. Standard Care:

Metric Standard Care TREWS p-value
Time to antibiotics 4.2 hours 2.8 hours < 0.001
In-hospital mortality 18.3% 14.2% 0.021
ICU length of stay 5.8 days 4.9 days 0.015
False alert rate N/A 12% -

Key Finding: 1.3 hours faster treatment, 4.1% absolute mortality reduction

Pressure Ulcer Prevention (Time Best Invention 2024)

Historical teaching case. Clinical or company claims require source review before reuse as current evidence. The supplied numbers are not clinical guidance. The numerical Bayes exercise is illustrative. Do not infer that the named deployed system uses this exact probabilistic architecture.

Problem: Pressure ulcers affect 2.5 million patients/year in US

Bayesian Approach: - Real-time risk assessment every 30 minutes - Incorporates: mobility, nutrition, tissue perfusion, medical devices - Predicts risk 12-24 hours in advance

Model: P(Ulcert+12∣Datat)=Bayesian Model(Patient factors, Environmental factors, Time trends)P(\text{Ulcer}_{t+12} \mid \text{Data}_t) = \text{Bayesian Model}(\text{Patient factors, Environmental factors, Time trends})

Results: - 40% reduction in hospital-acquired pressure ulcers - Proactive interventions (repositioning, support surfaces)

Comparison: Rule-Based vs Bayesian

The numerical Bayes exercise is illustrative. Do not infer that the named deployed system uses this exact probabilistic architecture.

Original code uses its source lesson’s setup and data. Saved outputs, where shown, were not rerun for this edition.

Rule-Based System (SIRS)

Show original text code 1
IF (Temp > 38 AND HR > 90)
   THEN Risk = "High"
ELSE Risk = "Low"

Limitations: - Binary output (yes/no) - No confidence measure - Ignores patient context - Static thresholds - High false positive rate (40-60%)

Bayesian System (TREWS)

Show original text code 2
Risk = P(Sepsis | All data)
Risk ∈ [0, 1] with confidence interval

Advantages: - Probabilistic output - Quantifies uncertainty - Patient-specific - Adaptive thresholds - Lower false positive rate (12%)

Feature Importance: What Matters?

The numerical Bayes exercise is illustrative. Do not infer that the named deployed system uses this exact probabilistic architecture.

Top 10 Predictive Features in TREWS:

  1. Lactate trend (Δ over 6h)
  2. Heart rate variability
  3. Temperature trajectory
  4. Respiratory rate trend
  5. White blood cell trend
  6. Blood pressure variability
  7. Recent procedures
  8. Chronic conditions
  9. Age-adjusted baselines
  10. Time of day patterns

Bayesian Model automatically weights features based on: - Information gain - Uncertainty reduction - Interaction effects

Handling Missing Data: A Bayesian Advantage

The numerical Bayes exercise is illustrative. Do not infer that the named deployed system uses this exact probabilistic architecture.

In Healthcare: 30-40% of EHR data is missing!

Traditional ML: - Delete rows (lose data) - Impute with mean (lose variance) - Create missing indicators

Bayesian Approach: - Treat missing data as latent variables - Marginalize over possible values weighted by probability

P(Sepsis∣Observed data)=∫P(Sepsis∣Observed, Missing)⋅P(Missing∣Observed)d(Missing)P(\text{Sepsis} \mid \text{Observed data}) = \int P(\text{Sepsis} \mid \text{Observed, Missing}) \cdot P(\text{Missing} \mid \text{Observed}) \, d(\text{Missing})

Result: Uses partial information optimally without discarding data

Model Calibration: Are Probabilities Accurate?

The numerical Bayes exercise is illustrative. Do not infer that the named deployed system uses this exact probabilistic architecture.

Original code uses its source lesson’s setup and data. Saved outputs, where shown, were not rerun for this edition.

Calibration Plot: Do predicted probabilities match observed frequencies?

TREWS Calibration: - When model says 30% risk → observed frequency is 28-32% - Well-calibrated across risk spectrum

Temporal Dynamics: Time Matters

The numerical Bayes exercise is illustrative. Do not infer that the named deployed system uses this exact probabilistic architecture.

Original code uses its source lesson’s setup and data. Saved outputs, where shown, were not rerun for this edition.

Static Model: Single risk score

Dynamic Bayesian Model: Risk evolves over time

Show original mermaid code 1
%%| fig-width: 8
%%| fig-align: center
graph LR
    R0[Risk t=0] --> R1[Risk t=1]
    R1 --> R2[Risk t=2]
    R2 --> R3[Risk t=3]
    D1[Data t=1] --> R1
    D2[Data t=2] --> R2
    D3[Data t=3] --> R3

Dynamic Model captures: - Trends (increasing/decreasing) - Rates of change - Temporal patterns - Recovery trajectories

Alert Fatigue: The Implementation Challenge

The numerical Bayes exercise is illustrative. Do not infer that the named deployed system uses this exact probabilistic architecture.

Problem: Too many alerts → clinicians ignore them

Bayesian Solution: - Threshold optimization: P(Sepsis)>τP(\text{Sepsis}) > \tau - Multi-level alerts based on uncertainty - Personalized to unit/clinician

Alert Strategy:

Risk Level Action False Positive Rate
< 20% Monitor only -
20-40% Soft alert to nurse 15%
40-60% Alert to physician 8%
> 60% Urgent alert + auto-page 5%

Result: 60% reduction in alert fatigue vs. SIRS criteria

Fairness and Bias Considerations

The numerical Bayes exercise is illustrative. Do not infer that the named deployed system uses this exact probabilistic architecture.

Critical Question: Do Bayesian priors perpetuate healthcare disparities?

Potential Issues: - Historical data reflects biased treatment patterns - Different baseline risks across populations - Access to care differences

Bayesian Health’s Approach: - Stratified validation across demographics - Audit for differential performance - Adjust priors based on social determinants of health - Transparency in feature importance

P(Sepsis∣Race, Gender)=?P(Sepsis∣Clinical factors only)P(\text{Sepsis} \mid \text{Race, Gender}) \stackrel{?}{=} P(\text{Sepsis} \mid \text{Clinical factors only})

Cleveland Clinic System-Wide Deployment

Historical teaching case. Clinical or company claims require source review before reuse as current evidence. The supplied numbers are not clinical guidance. The numerical Bayes exercise is illustrative. Do not infer that the named deployed system uses this exact probabilistic architecture.

Scale of Implementation:

  • 11 hospitals
  • 6,000+ beds
  • 200,000+ patient encounters/year

Technical Infrastructure: - Real-time EHR integration (Epic) - <5 minute latency for predictions - Dashboard integration - Mobile alerts

Key to Success: - Clinician buy-in through co-design - Workflow integration - Continuous learning from feedback - Performance monitoring

Explainable AI: Opening the Black Box

The numerical Bayes exercise is illustrative. Do not infer that the named deployed system uses this exact probabilistic architecture.

Original code uses its source lesson’s setup and data. Saved outputs, where shown, were not rerun for this edition.

Clinicians need to understand WHY the model alerts

TREWS provides:

Show original text code 1
SEPSIS RISK: 52% (High)

Top Contributing Factors:
1. Lactate increasing: 1.2 → 2.5 mmol/L (+35% risk)
2. Heart rate trend: 85 → 105 bpm (+12% risk)  
3. Recent surgery (2 days ago) (+8% risk)
4. Age-adjusted baseline (+5% risk)

Alternative explanations considered:
- Post-surgical inflammation (22% probability)
- Pain response (15% probability)

Bayesian framework naturally supports explainability through probabilistic reasoning chains

Connection to Course Concepts

The numerical Bayes exercise is illustrative. Do not infer that the named deployed system uses this exact probabilistic architecture.

From Lecture 1-6:

  1. Bayes Rule: Core of the update mechanism
  2. Prior/Posterior: Patient history → Real-time updates
  3. Likelihood: Clinical evidence model
  4. Decision Theory: Optimal alert thresholds
  5. Sequential Analysis: Time-series of patient data
  6. Hierarchical Models: Patient-level + Population-level parameters

The numerical Bayes exercise is illustrative. Do not infer that the named deployed system uses this exact probabilistic architecture.

This case study demonstrates how foundational Bayesian concepts directly translate to life-saving applications

Open Questions and Future Directions

The numerical Bayes exercise is illustrative. Do not infer that the named deployed system uses this exact probabilistic architecture.

Research Challenges:

  1. Causality: Association vs. causation in predictions
  2. Generalization: Transfer across hospitals/populations
  3. Multi-task learning: Simultaneous prediction of multiple conditions
  4. Human-AI collaboration: Optimal division of labor

Emerging Applications: - ICU deterioration prediction - Post-discharge monitoring - Medication response prediction - Surgical complication forecasting

Key Takeaways

The numerical Bayes exercise is illustrative. Do not infer that the named deployed system uses this exact probabilistic architecture.

  1. Bayesian methods provide principled uncertainty quantification - critical for medical decisions

  2. Sequential updating enables real-time risk assessment - catches deterioration early

  3. Probabilistic framework handles missing data naturally - common in healthcare

  4. Calibrated probabilities enable better decision-making - transparent about confidence

  5. Implementation requires careful attention to clinical workflow - technology alone insufficient

The numerical Bayes exercise is illustrative. Do not infer that the named deployed system uses this exact probabilistic architecture.

Class Discussion (10 min)

The numerical Bayes exercise is illustrative. Do not infer that the named deployed system uses this exact probabilistic architecture.

Consider the trade-offs:

A Bayesian early warning system has: - 85% sensitivity (catches 85% of sepsis cases) - 88% specificity (12% false positive rate)

Questions:

  1. What false positive rate is acceptable given the stakes?
  2. How should the system handle uncertainty at the decision boundary (40-60% risk)?
  3. Should all patients be monitored equally, or risk-stratified?
  4. How do we balance algorithmic recommendations with clinical autonomy?

Form pairs and discuss for 5 minutes, then share with class

Regulatory and Ethical Considerations

The numerical Bayes exercise is illustrative. Do not infer that the named deployed system uses this exact probabilistic architecture.

FDA Regulation: - Bayesian Health’s platform is FDA-cleared - Classified as Software as Medical Device (SaMD) - Requires continuous monitoring and updates

Ethical Framework: - Beneficence: Does it improve outcomes? - Non-maleficence: Potential for harm from false alerts? - Autonomy: Preserves clinician decision-making? - Justice: Fair across patient populations?

Ongoing Debate: Should AI systems be held to higher standards than human clinicians?

Return on Investment: Healthcare Economics

Historical teaching case. Clinical or company claims require source review before reuse as current evidence. The supplied numbers are not clinical guidance. The numerical Bayes exercise is illustrative. Do not infer that the named deployed system uses this exact probabilistic architecture.

Cost-Benefit Analysis (per 1000 patients):

Costs: - Platform license: $500K/year - Implementation: $200K - Training: $50K - Maintenance: $100K/year

Benefits: - Lives saved: 40 patients (@ $10M VSL) = $400M - Reduced ICU days: 1000 days × $3K = $3M - Reduced readmissions: 50 × $15K = $750K - Efficiency gains: $500K

Net benefit: Substantial even without valuing lives

Comparison to Other AI Health Applications

Historical teaching case. Clinical or company claims require source review before reuse as current evidence. The supplied numbers are not clinical guidance. The numerical Bayes exercise is illustrative. Do not infer that the named deployed system uses this exact probabilistic architecture.

Bayesian Health vs. Other Approaches:

Application Method Uncertainty Interpretability Deployment
Bayesian Health Bayesian Networks ✓✓✓ ✓✓✓ System-wide
Google DeepMind (Sepsis) Deep Learning ✓ ✓ Limited
Epic Sepsis Prediction Logistic Regression ✓✓ ✓✓✓ Widespread
IBM Watson Health Rule-based + ML ✓ ✓✓ Discontinued

Bayesian Advantage: Best combination of performance and interpretability

Lessons for AI Deployment

The numerical Bayes exercise is illustrative. Do not infer that the named deployed system uses this exact probabilistic architecture.

What Made Bayesian Health Successful:

  1. Solve a real clinical problem with clear value proposition
  2. Co-design with clinicians from day one
  3. Rigorous validation through RCTs
  4. Probabilistic approach provides interpretability
  5. Continuous learning from deployment
  6. Workflow integration not just technology

The numerical Bayes exercise is illustrative. Do not infer that the named deployed system uses this exact probabilistic architecture.

Technology + Clinical workflow + Organizational change = Impact

Student Reflection Exercise

The numerical Bayes exercise is illustrative. Do not infer that the named deployed system uses this exact probabilistic architecture.

Take 3 minutes to write:

  1. One concept from Bayesian statistics you now understand better through this case study

  2. One question you still have about implementation

  3. One other domain where similar Bayesian methods could be applied

Share with a partner, then volunteers share with class

Your Turn: Apply the Concepts

The numerical Bayes exercise is illustrative. Do not infer that the named deployed system uses this exact probabilistic architecture.

Mini-Project Ideas:

  1. Build a simple Bayesian network for diabetes risk prediction
  2. Compare Bayesian vs. frequentist approaches to clinical trial analysis
  3. Implement sequential Bayesian updating for a time-series medical dataset
  4. Analyze fairness/bias in an existing clinical prediction model
  5. Design an explainable AI system for a healthcare application

Datasets: - MIMIC-III (ICU data) - eICU Collaborative Research Database - UK Biobank

The project evaluation design

  • State the unit of observation and the intended prediction time.

  • Specify the split, baseline, and comparison metric.

  • Name one plausible leakage route and how you will check it.

A model has almost zero training error and a large validation error. What would you investigate?

A model does well on a random split but poorly on the next year. What might differ?

Which part of your project’s evaluation could fail even if every line of code runs correctly?

A fit that changes too easily

Ridge regularization and stability under data perturbations.

  • We keep the same polynomial features and the same observations.

What could make the fitted curve less sensitive to small changes in the responses?

  • Predict a modification to the fitting rule before naming a method.

J(a,b)=∑i(yi−a−xi⊤b)2+λ∑jbj2.J(a,b)=\sum_i(y_i-a-x_i^\top b)^2+\lambda\sum_j b_j^2.

  • The first term rewards agreement with observed responses.

  • The second discourages large coefficients.

  • The intercept aa is unpenalized in this experiment.

  • Use degree-12 polynomial features in every fit.

  • Keep the training/validation split and response scale fixed.

  • Vary only λ\lambda.

  • This experiment isolates the effect of the penalty.

Feature scale affects the penalty

The same relationship can have very different numerical coefficients.

Input unit Same prediction Squared coefficient
Meters y=2xy=2x 44
Millimeters y=0.002xy=0.002x 0.0000040.000004
  • Equal predictions do not imply equal ridge penalties.
  • Standardize using training observations.
Show Python: identical predictions, different penalties
import numpy as np
meters = np.array([1., 2., 3.])
millimeters = 1000 * meters
assert np.allclose(2 * meters, 0.002 * millimeters)
print(2**2, 0.002**2)

A useful cost in training fit

Degree-12 fits with different ridge penalties. The features stay fixed.

Coefficient norm and prediction errors across ridge penalties
  • Coefficient size falls as the penalty grows.
  • Validation error need not move in the same direction.
  • Select the penalty with validation, not the smallest training error.

Which part of the curve suggests too much constraint?

The curves represent sensitivity

Repeated fitted curves after small changes in the observed responses
  • Same inputs. Twelve small response perturbations.
  • Left: unpenalized. Right: moderate ridge penalty.
  • A tighter collection means less sensitivity in this experiment.

Why aren’t these automatically confidence bands?

The size of a coefficient vector

∥b∥2=∑jbj2,∥b∥22=∑jbj2\|b\|_2=\sqrt{\sum_j b_j^2},\qquad \|b\|_2^2=\sum_j b_j^2

  • For b=(3,4)b=(3,4), the norm is 5 and the penalty uses 25.
  • Large positive and negative coefficients do not cancel.
import numpy as np
b = np.array([10., -10.])
print(b.sum())          # 0: signed cancellation
print(b @ b)            # 200: ridge penalty before lambda
assert b @ b == 200

If two feature columns are identical, which coefficients would ridge prefer?

  • As λ\lambda becomes very large, the penalized coefficients approach zero.

  • With an unpenalized intercept, predictions approach a constant fitted from the training responses.

Why can that be a useful baseline and a poor final predictor?

  • Record the chosen setting and its rationale.

  • Then reveal the common regression test result once.

  • If the result disappoints, report that evidence. Changing the model in response makes this test part of another selection cycle.

Bias-variance trade-off

Lasso vs Ridge Geometry

Original code uses its source lesson’s setup and data. Saved outputs, where shown, were not rerun for this edition.

Lasso Variable Selection

Original code uses its source lesson’s setup and data. Saved outputs, where shown, were not rerun for this edition.

Horseshoe Prior

The source’s shrinkage illustration is not by itself a computation of the full horseshoe posterior mean.

The horseshoe prior provides adaptive shrinkage through a hierarchical Bayesian framework. For a linear model with response (y_i) and covariates (x_i ^p), the horseshoe prior is specified as:

yi=xiTβ+εi,εi∼N(0,σ2)βj∼N(0,τ2λj2σ2),j=1,…,pλj∼Cauchy+(0,1)τ∼Cauchy+(0,1) \begin{aligned} y_i &= x_i^T \beta + \varepsilon_i, \quad \varepsilon_i \sim N(0, \sigma^2) \\ \beta_j &\sim N(0, \tau^2 \lambda_j^2 \sigma^2), \quad j = 1, \ldots, p \\ \lambda_j &\sim \text{Cauchy}^+(0, 1) \\ \tau &\sim \text{Cauchy}^+(0, 1) \end{aligned}

Here λj\lambda_j are local shrinkage parameters (one per coefficient), τ\tau is the global shrinkage parameter controlling overall sparsity.

Horseshoe Shrinkage Behavior

The source’s shrinkage illustration is not by itself a computation of the full horseshoe posterior mean.

Original code uses its source lesson’s setup and data. Saved outputs, where shown, were not rerun for this edition.

Modern Applications

  • Deep Learning: Dropout, weight decay, batch normalization
  • Compressed Sensing: Sparse signal recovery
  • Genomics: Gene expression analysis
  • Neuroimaging: Brain connectivity
  • Finance: Portfolio optimization
  • Recommendation Systems: Collaborative filtering

Practical Guidelines

Scenario Recommended Method Rationale
p<np < n, stable Ridge Numerical stability
p>np > n, sparse Lasso, Horseshoe Variable selection
Ultra-sparse Spike-and-slab Exact sparsity
Correlated predictors Bridge, Bayesian Handle correlation
Uncertainty needed Full Bayesian Credible intervals

Key Takeaways

Original code uses its source lesson’s setup and data. Saved outputs, where shown, were not rerun for this edition.

  1. MLE fails in high dimensions (p≥3p \geq 3)
  2. Shrinkage helps through bias-variance trade-off
  3. Regularization = Bayesian priors (duality)
  4. Different penalties for different sparsity patterns
  5. Modern methods combine best of both worlds
  6. Context matters for method selection

Expression

Cross-Validation in Practice

Original code uses its source lesson’s setup and data. Saved outputs, where shown, were not rerun for this edition.

Model Selection Workflow

Original code uses its source lesson’s setup and data. Saved outputs, where shown, were not rerun for this edition.

Show original mermaid code 1
graph TD
    A[Data] --> B[Exploratory Analysis]
    B --> C[Train/Validation Split]
    C --> D[Model Selection]
    D --> E[Hyperparameter Tuning]
    E --> F[Cross-Validation]
    F --> G[Final Model]
    G --> H[Test Set Evaluation]
    
    D --> D1[Ridge]
    D --> D2[Lasso] 
    D --> D3[Bridge]
    D --> D4[Bayesian]
    
    F --> F1[K-fold CV]
    F --> F2[Time Series CV]
    F --> F3[Nested CV]

Double Descent Curve

Inspect the actual experiment. A named regime or curve is not a universal result. Separate interpolation, noise fitting, extrapolation, basis conditioning and floating-point effects.

Double descent is a phenomenon of over-parameterized statistical models that challenges traditional bias-variance intuition. Over-parameterized models such as deep neural networks have an interesting re-descending property in their risk characteristics.

As model complexity increases:

  1. Classical regime: U-shaped bias-variance trade-off
  2. Interpolation threshold: Risk peaks when parameters equal observations
  3. Over-parameterized regime: Risk re-descends beyond interpolation

This phenomenon was first observed in linear regression and later in deep learning contexts.

Double Descent Phenomenon

Inspect the actual experiment. A named regime or curve is not a universal result. Separate interpolation, noise fitting, extrapolation, basis conditioning and floating-point effects.

Stylized double descent curve showing three regimes

The curve shows two distinct phases:

  • First descent follows classical bias-variance trade-off
  • Second descent occurs in over-parameterized regime
  • Peak occurs at interpolation threshold where p=np = n

Why Double Descent Matters

Inspect the actual experiment. A named regime or curve is not a universal result. Separate interpolation, noise fitting, extrapolation, basis conditioning and floating-point effects.

Modern machine learning practice increasingly uses over-parameterized models with parameters far exceeding the number of observations. Examples include large language models, image processing networks, and generative AI methods.

Key insights:

  • More parameters don’t necessarily mean worse generalization
  • Interpolators achieving zero training error can still generalize well
  • Implicit regularization from minimum-norm solutions helps
  • Traditional model selection may be unnecessarily conservative

Practical implication: Instead of carefully tuning to find optimal complexity, over-parameterize and get good performance automatically!

Double Descent Example: Polynomial Regression

Inspect the actual experiment. A named regime or curve is not a universal result. Separate interpolation, noise fitting, extrapolation, basis conditioning and floating-point effects.

We demonstrate double descent using polynomial regression with a sinusoidal target function f(x)=sin(5x)f(x) = \sin(5x).

Setup:

  • Only n=20n = 20 training observations from [−1,1][-1, 1]
  • Gaussian noise with σ=0.3\sigma = 0.3
  • Fit polynomials of degree d=1,2,…,50d = 1, 2, \ldots, 50
  • Use Legendre polynomial basis for numerical stability
  • Estimate coefficients using Moore-Penrose pseudoinverse

Small sample size is crucial for observing double descent, creating a regime where parameters can substantially exceed observations.

Polynomial Fits Across Complexity Levels

Inspect the actual experiment. A named regime or curve is not a universal result. Separate interpolation, noise fitting, extrapolation, basis conditioning and floating-point effects.

Original code uses its source lesson’s setup and data. Saved outputs, where shown, were not rerun for this edition.

Show original python code 1
#| code-fold: true
#| code-summary: "Python Setup"
import numpy as np
import matplotlib.pyplot as plt

np.random.seed(42)

def sin_func(x): 
    return np.sin(5*x)

G = np.polynomial.legendre.legvander

def poly(pts, beta, d):
    return G(pts, d).dot(beta)

n = 20
sigma = 0.3
a, b = -1, 1

ground_truth = sin_func
x = np.linspace(a, b, n)
y = ground_truth(x) + sigma * np.random.normal(size=n)
xdense = np.linspace(a, b, 100)
ygt = ground_truth(xdense)

def fit(d):
    betaHat = np.linalg.pinv(G(x, d)).dot(y)
    mseos = np.sqrt(np.mean((G(xdense, d).dot(betaHat) - ygt)**2))
    mseis = np.sqrt(np.mean((G(x, d).dot(betaHat) - y)**2))
    return betaHat, mseos, mseis

def run(d, ax):
    betaHat, mseos, mseois = fit(d)
    ax.plot(xdense, ygt, label='ground-truth')
    ax.scatter(x, y, c='r', label='samples')
    ax.plot(xdense, poly(xdense, betaHat, d), label='model')
    ax.set_ylim(-2, 2)
    ax.axis('off')
    ax.legend()
    ax.set_title('d=%d, MSE: Test=%.2f, Train=%.2f' % (d, mseos, mseois))
Show original python code 2
#| code-fold: true
#| label: fig-double-descent-grid
#| fig-cap: "Four representative polynomial degrees showing double descent phases"

fig, axes = plt.subplots(2, 2, figsize=(12, 10))
fig.suptitle('Double Descent: Polynomial Regression', fontsize=16)

run(1, axes[0, 0])   # Underparameterized
run(5, axes[0, 1])   # Classical optimum
run(20, axes[1, 0])  # Interpolation threshold
run(50, axes[1, 1])  # Over-parameterized

plt.tight_layout()
plt.show()

Understanding the Four Regimes

Inspect the actual experiment. A named regime or curve is not a universal result. Separate interpolation, noise fitting, extrapolation, basis conditioning and floating-point effects.

Degree 1 (Underparameterized): Linear model too simple to capture oscillatory sine function. High bias, poor fit to both training and test data.

Degree 5 (Classical Optimum): Sweet spot of traditional bias-variance tradeoff. Sufficient complexity to capture main features without severe overfitting.

Degree 20 (Interpolation Threshold): Exactly as many parameters as observations, enabling perfect interpolation. Wild oscillations between data points lead to poor generalization.

Degree 50 (Over-parameterized): Despite having far more parameters than observations, achieves better test performance than interpolating model. This is the double descent effect!

The Complete MSE Curve

Inspect the actual experiment. A named regime or curve is not a universal result. Separate interpolation, noise fitting, extrapolation, basis conditioning and floating-point effects.

Original code uses its source lesson’s setup and data. Saved outputs, where shown, were not rerun for this edition.

Show original python code 1
#| code-fold: true
#| label: fig-mse-curve
#| fig-cap: "Training and test MSE across polynomial degrees showing double descent"

nd = 50
mse_test = np.zeros(nd)
mse_train = np.zeros(nd)

for d in range(1, nd):
    betaHat, mseos, mseois = fit(d)
    mse_test[d] = mseos
    mse_train[d] = mseois

fig, ax1 = plt.subplots(figsize=(10, 6))
ax1.set_xlabel('Polynomial Degree (Model Complexity)', fontsize=12)
ax1.set_ylabel('log10(MSE)', color='black', fontsize=12)
ax1.plot(np.log10(mse_test), color='blue', linewidth=2, label='Test MSE')
ax2 = ax1.twinx()
ax2.set_ylabel('log10(Train MSE)', color='red', fontsize=12)
ax2.plot(np.log10(mse_train), color='red', linewidth=2, label='Train MSE')
ax2.tick_params(axis='y', labelcolor='red')

lines1, labels1 = ax1.get_legend_handles_labels()
lines2, labels2 = ax2.get_legend_handles_labels()
ax1.legend(lines1 + lines2, labels1 + labels2, loc='upper right')
plt.title('Double Descent Phenomenon in Polynomial Regression')
plt.tight_layout()
plt.show()

The test error (blue line) exhibits characteristic double descent shape with three phases:

Classical Regime (d<5d < 5): Increasing model complexity reduces both bias and test error. Traditional understanding of bias-variance tradeoff applies.

Interpolation Crisis (d≈n=20d \approx n = 20): Test error peaks dramatically as model perfectly fits training data while generalizing poorly. This is where classical theory predicts catastrophic overfitting.

Over-parameterized Regime (d>30d > 30): Test error decreases again! Extreme over-parameterization leads to improved generalization despite ability to memorize training data.

The double descent phenomenon arises from implicit regularization effects of minimum-norm solutions in over-parameterized settings.

When d>nd > n, the pseudoinverse solution corresponds to minimum ℓ2\ell_2-norm coefficients among all possible interpolating solutions. This implicit bias toward simpler functions leads to surprisingly good generalization.

Mathematical insight: Among infinitely many solutions that perfectly fit the data, we automatically select the one with smallest coefficients, providing implicit regularization without explicit penalties.

Connection to deep learning: Similar implicit regularization occurs in over-parameterized neural networks through gradient descent dynamics.

Bayesian Perspective on Double Descent

Inspect the actual experiment. A named regime or curve is not a universal result. Separate interpolation, noise fitting, extrapolation, basis conditioning and floating-point effects.

Double descent has a natural Bayesian interpretation and is not in conflict with Occam’s razor that Bayesian models possess.

Occam’s Razor: Bayesian methods naturally favor simpler models through the marginal likelihood, penalizing complexity via corrections like BIC.

Reconciliation: Even though Bayesian methods shift posterior toward lower-complexity models, highly parameterized Bayesian models can have good risk properties due to the conditional prior of parameters given the model.

The key is that over-parameterized models don’t necessarily have high effective complexity when properly regularized (implicitly or explicitly).

Implications for Practice

The double descent phenomenon has significant practical implications for modern machine learning:

Model selection strategy: Given that finding the “sweet spot” is time-consuming and computationally expensive, over-parameterization provides good performance automatically without careful tuning.

Generality: Observed across wide range of models including deep neural networks, random forests, kernel methods, and linear models.

Challenge to intuition: Classical statistical wisdom about model complexity doesn’t apply in contemporary settings with over-parameterized models.

Modern AI success: Helps explain why massive models (GPT, BERT, etc.) generalize well despite billions of parameters.

The Normal Means Problem

Setup: yi∣θi∼N(θi,σ2),i=1,…,p,p>2y_i \mid \theta_i \sim N(\theta_i, \sigma^2), \quad i=1,\ldots,p, \quad p > 2

Goal: Estimate θ=(θ1,…,θp)\theta = (\theta_1, \ldots, \theta_p) under squared loss ℒ(θ,θ̂)=∑i=1p(θi−θ̂i)2\mathcal{L}(\theta, \hat{\theta}) = \sum_{i=1}^p (\theta_i - \hat{\theta}_i)^2

MLE: θ̂iMLE=yi\hat{\theta}_i^{MLE} = y_i

Risk: R(θ,θ̂MLE)=pσ2R(\theta,\hat{\theta}^{MLE}) = p\sigma^2 (constant!)

Shocking Result

For p≥3p \geq 3, the MLE is inadmissible under squared error loss!

There exist estimators with uniformly lower risk than MLE.

James-Stein Estimator: θ̂iJS=(1−(p−2)σ2∥y∥2)yi\hat{\theta}_i^{JS} = \left(1 - \frac{(p-2)\sigma^2}{\|y\|^2}\right) y_i

Risk: R(θ,θ̂JS)<R(θ,θ̂MLE)R(\theta, \hat{\theta}^{JS}) < R(\theta, \hat{\theta}^{MLE}) for all θ\theta

Why James-Stein Works

  • Shrinkage: Pulls estimates toward zero (or overall mean)
  • Borrowing strength: Uses information across components
  • Global regularization: Single shrinkage parameter
  • Bias-variance trade-off: Small bias for large variance reduction

Key insight: Multivariate estimation is easier than univariate when using appropriate shrinkage!

Baseball Example: James-Stein in Action

Original code uses its source lesson’s setup and data. Saved outputs, where shown, were not rerun for this edition.

Empirical Bayes Interpretation

Hierarchical Model: yi∣θi∼N(θi,σ2)θi∣μ,τ2∼N(μ,τ2)\begin{aligned} y_i \mid \theta_i &\sim N(\theta_i, \sigma^2) \\ \theta_i \mid \mu, \tau^2 &\sim N(\mu, \tau^2) \end{aligned}

Empirical Bayes: - Estimate μ̂=y‾\hat{\mu} = \bar{y} - Estimate τ̂2\hat{\tau}^2 from data - Use in posterior mean calculation

Result: Closely related to James-Stein estimator

Appendix: Mathematical Details

James-Stein Risk Calculation: R(θ,θ̂JS)=pσ2−(p−2)σ2𝔼[1∥θ+ϵ∥2/σ2]R(\theta, \hat{\theta}^{JS}) = p\sigma^2 - (p-2)\sigma^2 \mathbb{E}\left[\frac{1}{\|\theta + \epsilon\|^2/\sigma^2}\right]

Horseshoe Posterior Mean: 𝔼[θi∣yi]=(1−κi)⋅0+κi⋅yi\mathbb{E}[\theta_i \mid y_i] = \left(1 - \kappa_i\right) \cdot 0 + \kappa_i \cdot y_i where κi\kappa_i depends on τ\tau and yiy_i

Appendix: Simulation Study

Original code uses its source lesson’s setup and data. Saved outputs, where shown, were not rerun for this edition.

Appendix: Bayesian Computation

Original code uses its source lesson’s setup and data. Saved outputs, where shown, were not rerun for this edition.

MCMC for Horseshoe:

Double Descent Example

Inspect the actual experiment. A named regime or curve is not a universal result. Separate interpolation, noise fitting, extrapolation, basis conditioning and floating-point effects.

Original code uses its source lesson’s setup and data. Saved outputs, where shown, were not rerun for this edition.

Show original python code 1
#| echo: false
import numpy as np
import numpy.random as rand
import numpy.linalg as la
import matplotlib.pyplot as plt

# Set random seed for reproducibility
np.random.seed(42)
# Functions
def arctan_gt(x): 
    return np.arctan(5*x)

def cubic_gt(x): 
    return poly(x, np.array([0, -1, 0, 1]), 3)

def relu(x): 
    return x*(x >= 0)

def sin(x): 
    return np.sin(5*x)

def Vand(x, d):
    """Vandermonde matrix for pts x, to degree d"""
    X = np.array([x**i for i in range(0, d+1)]).T
    return X

Polynomial Regression Setup

Inspect the actual experiment. A named regime or curve is not a universal result. Separate interpolation, noise fitting, extrapolation, basis conditioning and floating-point effects.

Original code uses its source lesson’s setup and data. Saved outputs, where shown, were not rerun for this edition.

Show original python code 1
#| code-fold: true

n = 20  # number of samples
sigma = 0.3  # stdev of noise
a = -1
b = 1  # range of x values
# Use Legendre polynomial basis by default
G = np.polynomial.legendre.legvander

def poly(pts, beta, d):
    return G(pts, d).dot(beta)

# Initialize data
ground_truth = sin
x = np.linspace(a, b, n)
y = ground_truth(x) + sigma * np.random.normal(size=n)
xdense = np.linspace(a, b, 100)
ygt = ground_truth(xdense)

# Core functions
def solve_reg(A, y, lamb):
    return la.solve(A.T.dot(A) + lamb * np.identity(A.shape[1]), A.T.dot(y))

def fit(d):
    betaHat = la.pinv(G(x, d)).dot(y)
    mseos = np.sqrt(np.mean((G(xdense, d).dot(betaHat) - ygt)**2))
    mseis = np.sqrt(np.mean((G(x, d).dot(betaHat) - y)**2))
    return betaHat, mseos, mseis

def run(d, ax):
    """Compute the regressor for degree d, and plot the solution."""
    betaHat, mseos, mseois = fit(d)
    ax.plot(xdense, ygt, label='ground-truth')
    ax.scatter(x, y, c='r', label='samples')
    ax.plot(xdense, poly(xdense, betaHat, d), label='model')
    ax.set_ylim(-2, 2)
    ax.axis('off')
    ax.legend()
    ax.set_title('d=%d, MSE: Test=%.2f, Train=%.2f' % (d, mseos, mseois))

Double Descent Results

Inspect the actual experiment. A named regime or curve is not a universal result. Separate interpolation, noise fitting, extrapolation, basis conditioning and floating-point effects.

Original code uses its source lesson’s setup and data. Saved outputs, where shown, were not rerun for this edition.

Show original python code 1
#| code-fold: true
#| label: fig-double-descent-grid
#| fig-cap: "Double Descent Phenomenon: Polynomial Regression with Different Degrees"

# Create 2x2 subplot grid
fig, axes = plt.subplots(2, 2, figsize=(12, 10))
fig.suptitle('Double Descent Phenomenon: Polynomial Regression', fontsize=16)

# Plot each degree in its respective subplot
run(1, axes[0, 0])   # Top left
run(5, axes[0, 1])   # Top right  
run(20, axes[1, 0])  # Bottom left
run(50, axes[1, 1])  # Bottom right

plt.tight_layout()
plt.show()

Original saved output: Double Descent Results

MSE Curve Analysis

Inspect the actual experiment. A named regime or curve is not a universal result. Separate interpolation, noise fitting, extrapolation, basis conditioning and floating-point effects.

Original code uses its source lesson’s setup and data. Saved outputs, where shown, were not rerun for this edition.

Show original python code 1
#| code-fold: true
#| label: fig-mse-curve
#| fig-cap: "Bias-Variance Trade-off: Training and Test MSE vs Model Complexity"

# Generate MSE data for different polynomial degrees
nd = 50
mse1 = np.zeros(nd)  # Test MSE
mse2 = np.zeros(nd)  # Train MSE

for d in range(1, nd):
    betaHat, mseos, mseois = fit(d)
    mse1[d] = mseos
    mse2[d] = mseois
fig, ax1 = plt.subplots()
ax1.set_xlabel('Number of Features')
ax1.set_ylabel('MSE', color='black')
ax1.plot(np.log10(mse1), color='blue', label='out-of-sample')
ax2 = ax1.twinx()
ax2.plot(np.log10(mse2), color='red', label='in-sample')
fig.legend()

Original saved output: MSE Curve Analysis

Double Descent Phases

Inspect the actual experiment. A named regime or curve is not a universal result. Separate interpolation, noise fitting, extrapolation, basis conditioning and floating-point effects.

  1. Classical Regime (d<5d < 5): Traditional bias-variance tradeoff

  2. Interpolation Crisis (d≈n=20d \approx n = 20): Test error peaks at perfect fit

  3. Over-parameterized Regime (d>30d > 30): Test error decreases with extreme over-parameterization

Key insight: Implicit regularization through minimum-norm solutions

Project build checkpoint

  • Show the baseline and one alternative under the agreed evaluation design.

  • Explain the strongest check that could have failed.

  • Identify one remaining uncertainty that matters to the recommendation.

Why should feature units matter to ridge?

Why would selecting λ\lambda using training error defeat the purpose?

What remains when the penalty is huge and the intercept is unpenalized?

How would you distinguish a poor constraint from an optimizer that failed?

Self-practice

  • Classification. Move the intercept and one coefficient, and fit a straight logit to the circle data. Compare thresholds 0.3, 0.5, and 0.8. For scores log3,log2,0\log 3,\log 2,0, compute the three probabilities and the loss of the first class, then add 1,000 to every score.
  • Evaluation. Fit polynomial degrees 1, 3, and 12. Compare training and validation error with the constant baseline. Then add a feature recorded after the outcome.
  • Regularization. Fit penalties 0, 0.01, 1, and 100. Add a little noise to the training responses and compare a weak penalty with a moderate one.