Overview

Bayesian Thinking
in Precision Health

An interactive 3-week module on Bayesian inference — from flipping coins to updating clinical diagnoses. Learn to reason under uncertainty like a scientist.

Week 1

Foundations of Bayesian Reasoning

Understand prior beliefs, evidence, and how to update beliefs rationally using Bayes' Theorem.

Textbook: Bayes' Theorem Basics
Lab: Coin Flip Explorer
Conceptual Assignment
Week 2

The Beta Distribution & Sequential Updating

Code your own Bayesian updating routine in Python or Java. Watch the posterior evolve with each observation.

Textbook: Beta Distributions
Lab: Beta Shaper + Posterior Tracker
Coding + Analysis Assignment
Week 3

Bayesian Inference in Precision Health

Apply Bayesian reasoning to real clinical scenarios — disease prevalence, diagnostic tests, and personalized risk.

Textbook: Clinical Applications
Lab: Diagnostic Simulator
Case Study Assignment
Learning Objectives
By the end of this module, students will: (1) explain Bayes' Theorem in plain language, (2) implement Bayesian updating in Python or Java, (3) visualize how prior beliefs shift with evidence, and (4) apply Bayesian reasoning to at least one clinical diagnostic scenario.
Course Overview

Course Syllabus

Bayesian Thinking in Precision Health — a 3-week intensive module bridging statistical inference, scientific computing, and clinical application.
Format
Hybrid / Flipped
Duration
3 Weeks
Contact Hours
~9 hrs / week
Total Points
180 pts
Prerequisites
Intro Stats, Python basics
Coding Languages
Python or Java

Course Description

This module introduces Bayesian statistical reasoning as a foundational tool for precision medicine and health informatics. Students will progress from first principles — Bayes' Theorem and prior beliefs — through hands-on implementation of Beta-Binomial updating, to real-world applications in clinical diagnostics, digital phenotyping, and personalized medicine.

The course is structured around an integrated interactive platform combining textbook readings, live browser-based simulations, and an embedded Python coding environment. No external software installation is required.

Learning Objectives

By the end of this module, students will be able to:

LO 1 — Conceptual
Explain Bayes' Theorem and the roles of prior, likelihood, and posterior in plain language
LO 2 — Technical
Implement Beta-Binomial updating in Python or Java from scratch
LO 3 — Visualization
Generate and interpret evolving posterior distribution charts across sequential observations
LO 4 — Applied
Apply Bayesian reasoning to diagnostic test interpretation, including sensitivity, specificity, and PPV
LO 5 — Clinical
Connect Bayesian sequential updating to at least one real precision health application
LO 6 — Critical Thinking
Distinguish Bayesian from frequentist reasoning and argue when each is preferable

Weekly Schedule

Week 1
Foundations of Bayesian Reasoning
50 pts ~9 hrs
Topics Covered
  • → Probability as degree of belief
  • → Bayes' Theorem: P(H|E) = P(E|H)·P(H)/P(E)
  • → Prior, likelihood, posterior — definitions & intuition
  • → Iterative belief updating
  • → Frequentist vs. Bayesian paradigms
  • → Clinical relevance: base rate fallacy
Activities
  • Read Week 1 Textbook (~60 min)
  • Coin Flip Explorer lab (~30 min)
  • Python coding challenge — sandbox (~45 min)
  • Assignment: 4 written/calc questions
Assignment due end of Week 1 — 50 points: Conceptual explanation of prior/posterior (10 pts) · Bayes' Theorem calculation with disease prevalence (15 pts) · Lab observation writeup (10 pts) · Prior strength reflection (15 pts)
Week 2
The Beta Distribution & Sequential Updating
60 pts ~9 hrs
Topics Covered
  • → The Beta distribution Beta(α, β)
  • → α and β as pseudo-counts
  • → Conjugate priors and the Binomial likelihood
  • → Closed-form updating: Beta(α+h, β+t)
  • → Posterior mean, mode, variance
  • → Strong vs. weak priors — convergence speed
Activities
  • Read Week 2 Textbook (~60 min)
  • Beta Shaper + Sequential Updater labs (~40 min)
  • Python coding sandbox — Beta updater (~60 min)
  • Assignment: code + analysis + visualization
Assignment due end of Week 2 — 60 points: Implement flip_and_update() in Python/Java (25 pts) · Compare flat vs strong prior convergence (20 pts) · Produce posterior evolution plot (15 pts)
Week 3
Bayesian Inference in Precision Health
70 pts ~9 hrs
Topics Covered
  • → Sensitivity, specificity, PPV, NPV
  • → Disease prevalence as a Bayesian prior
  • → Sequential clinical test updating
  • → Precision medicine: pharmacogenomics, biomarkers
  • → Digital phenotyping & wearable data streams
  • → The Bayesian brain: perception as inference
Activities
  • Read Week 3 Textbook (~60 min)
  • Diagnostic Testing Simulator lab (~30 min)
  • Python coding sandbox — clinical Bayesian (~60 min)
  • Assignment: case study + code + reflection
Assignment due end of Week 3 — 70 points: Alzheimer's biomarker case study (25 pts) · Sequential diagnostic simulator code (30 pts) · Precision health reflection (15 pts)

Grading Summary

ComponentWeekPoints% of TotalType
Assignment 1: Conceptual FoundationsWeek 15028%Written + Calculation
Assignment 2: Beta-Binomial CodingWeek 26033%Code + Analysis
Assignment 3: Clinical Case StudyWeek 37039%Case Study + Code
Total—180100%—
A
162–180 pts
90–100%
B
144–161 pts
80–89%
C
126–143 pts
70–79%
D
108–125 pts
60–69%
F
< 108 pts
< 60%

Course Policies

Prerequisites

Students should have completed an introductory statistics course covering basic probability. Familiarity with Python (variables, loops, functions) or Java (classes, methods) is expected for the Week 2 coding assignment. No prior Bayesian experience is required.

Tools & Technology

All course materials are embedded in the interactive HTML platform — no installation required. For the coding assignments, students may use the in-browser Python sandbox (powered by Pyodide) or submit code written in a local Python 3.8+ or Java 11+ environment. Required Python packages: numpy, scipy, matplotlib.

Late Policy

Assignments submitted within 48 hours of the deadline receive a 10% deduction. Submissions beyond 48 hours are not accepted without prior arrangement. Extensions may be granted for documented circumstances with at least 24 hours' notice.

Academic Integrity

Students are encouraged to discuss concepts with peers, but all written responses and submitted code must be independently authored. Use of AI coding assistants is permitted for Week 2 and 3 coding tasks provided the student can explain every line of their submission.

Accessibility

All interactive labs function in any modern browser without plugins. Students requiring alternative formats for any course material should contact the instructor at least one week in advance.

Required Technical Setup (Week 1 Prep)
For the in-browser sandbox: a modern browser with internet access (Chrome 90+ recommended). For local coding: Python 3.8+ with pip install numpy scipy matplotlib, or Java 11+ with Apache Commons Math. Verify your setup works before Week 2 begins.
Getting Started

How to Use This Interactive Lab

This platform is your laboratory, textbook, and workspace — all in one. Here's how to navigate it effectively.

Navigation

Use the sidebar on the left to move between weeks and content types. Each week contains four items:

ItemPurposeWho it's for
TextbookCore reading material with examples, formulas, and explanationsAll students — read before lab
Interactive LabHands-on simulation to explore concepts visuallyAll students — during lab sessions
AssignmentQuestions and coding tasks to complete for submissionAll students — submit to instructor
Answer SheetFull solutions with explanationsInstructors only (initially)

Using the Interactive Labs

The labs require no installation — they run directly in your browser. Each lab has:

  • Sliders and controls — adjust parameters and see results instantly
  • Run Simulation buttons — execute coin flips or updates
  • Live charts — watch distributions evolve in real time
  • Statistics panel — track key metrics (α, β, mean, variance)
  • Flip log — a scrollable record of every flip outcome

Coding Exercises

Assignments include Python and Java code templates. You will write functions to simulate coin flips, update a Beta distribution, and visualize the posterior. The lab shows you the expected output so you can verify your code is correct.

Before You Start Week 1
Make sure you have Python 3.8+ (with NumPy, SciPy, Matplotlib) OR a Java 11+ environment installed. The textbook code blocks can be copied directly into your editor.

Recommended Weekly Flow

  1. Read the Textbook section (~45–60 min)
  2. Open the Interactive Lab and explore for ~30 min
  3. Complete the Assignment (coding + written responses)
  4. Review the Answer Sheet after submitting
Week 1 — Textbook

Bayes' Theorem:
Updating Beliefs with Evidence

What does it mean to learn from data? Bayesian inference offers a mathematically precise answer — and it starts with a deceptively simple formula.

1. The Problem of Uncertain Beliefs

Imagine you find a coin on the street. Is it a fair coin? You don't know. Maybe it's perfectly balanced, maybe it's loaded to land heads 70% of the time. Your prior belief is that it's probably fair — but you're not certain.

Now you flip it 10 times and get 8 heads. Should you update your belief? Of course. But by how much? This is precisely the question Bayesian inference answers.

2. The Formula

Bayes' Theorem tells us how to update a probability when we receive new evidence:

P(H | E) = P(E | H) × P(H) / P(E)
SymbolNameMeaning
P(H)PriorYour belief in H before seeing evidence
P(E|H)LikelihoodHow probable is the evidence if H is true?
P(H|E)PosteriorYour updated belief after seeing evidence E
P(E)MarginalTotal probability of the evidence (normalizing constant)

3. An Intuitive Example: The Coin

Let's define two hypotheses:

  • H₁: The coin is fair (P(heads) = 0.5)
  • H₂: The coin is biased (P(heads) = 0.7)

Suppose we start believing both hypotheses equally: P(H₁) = P(H₂) = 0.5. We flip the coin and get Heads.

Calculation
P(Heads | fair) = 0.5    P(Heads | biased) = 0.7

P(E) = 0.5 × 0.5 + 0.5 × 0.7 = 0.60

P(fair | Heads) = (0.5 × 0.5) / 0.60 ≈ 0.417
P(biased | Heads) = (0.7 × 0.5) / 0.60 ≈ 0.583

One heads made us slightly more convinced the coin is biased. Makes sense! Each flip is weak evidence, but evidence accumulates.

4. The Key Insight: Updating Is Iterative

The posterior from one update becomes the prior for the next update. This is the beating heart of Bayesian inference: beliefs evolve continuously as evidence arrives, making it perfectly suited to medical data streams, sensor readings, and longitudinal studies.

Why This Matters in Healthcare
A patient's test result doesn't exist in a vacuum. Bayesian reasoning lets us combine a test's sensitivity and specificity with the population prevalence of a disease to compute the true probability a positive test means the patient is sick — often strikingly different from what intuition suggests.

5. Frequentist vs. Bayesian Thinking

ApproachQuestion AskedWhat's Random?
Frequentist"What would happen over many repetitions?"The data
Bayesian"Given this data, what should I believe?"The hypothesis

Neither is universally superior — but Bayesian methods shine when prior knowledge is valuable and when you need to update beliefs sequentially.

6. Summary

Bayes' Theorem is a machine for rational belief revision. You start with a prior, multiply by the likelihood of observed evidence, and normalize. The result — the posterior — becomes your new, better-informed belief. Repeat with every new observation.
Week 1 — Interactive Lab

Coin Flip Explorer

Flip a coin with an unknown bias and watch how your belief about P(heads) updates with each observation.

Bayesian Coin Flip Simulator

Set the coin's true bias (hidden), choose your prior, and flip. Can you detect the bias?

0.65 (65% heads)
α = 2
β = 2
H
Last flip
—
0
Total Flips
0
Heads
0
Tails
0.50
Posterior Mean
Flip Log
Flip the coin to begin...
What to Observe
Notice how the posterior distribution (blue curve) starts wide and uncertain, then narrows and shifts as you accumulate more flips. With enough evidence, the posterior should converge near the true bias — even if your initial prior was wrong.

Python Coding Challenge — Write It Yourself

Now code your own Bayesian coin flip simulator below. The starter template uses only built-in Python — no imports needed. Edit the code, click ▶ Run, and see your posterior evolve in real time.

  • Change TRUE_BIAS and N_FLIPS to explore different scenarios
  • Modify the prior (alpha, beta) and observe how it affects convergence
  • Try adding print statements to log the mean at every 10 flips
week1_coin_bayes.py  — Bayesian Coin Flip
Python 3.11 · Pyodide
loading…
Ctrl+Enter to run
console output
Python environment loading… this takes a few seconds on first use.
visualization
Run your code to generate a plot
Week 1 Assignment

Conceptual Foundations of Bayesian Inference

Due: End of Week 1
Points: 50
Format: Written + Short Calculation
Question 1 — 10 pts
In your own words, explain the difference between a prior, a likelihood, and a posterior in Bayesian inference. Use the coin-flip scenario from the lab to ground your explanation.
Write your answer here (3–5 sentences)
Question 2 — 15 pts
A lab test for a rare disease returns positive. The disease affects 1% of the population. The test has 95% sensitivity (true positive rate) and 90% specificity (true negative rate). Using Bayes' Theorem, calculate the probability that a patient with a positive test actually has the disease. Show all steps.
Show your calculation here
Question 3 — 10 pts
Using the Week 1 Interactive Lab, set the true coin bias to 0.70 and start with a flat prior (α=1, β=1). Flip 50 times and record the posterior mean. Then flip another 50 times and record again. What pattern do you observe? Include screenshots or note the values.
Record your observations and explain the pattern
Question 4 — 15 pts
Why might a strong prior belief require a lot of evidence to overcome? Give an example from medicine where prior beliefs about disease prevalence substantially affect how we should interpret diagnostic test results.
Write your answer here (3–5 sentences)
Instructor Resource

Week 1 — Answer Sheet

Full solutions with grading guidance
Question 1 — Model Answer
In your own words, explain prior, likelihood, and posterior.
Answer
The prior is your belief about the coin's fairness before any flips — e.g., "I think it's probably fair." The likelihood describes how probable the observed data (e.g., 8 heads in 10 flips) would be under a specific hypothesis (e.g., given that P(heads)=0.7). The posterior is your updated belief after combining the prior with the likelihood via Bayes' Theorem — it reflects what you now believe given the evidence. In the coin lab, the posterior distribution shifts toward higher P(heads) values when many heads are observed, reflecting rational belief revision.

Grading note: Award full credit for correct directional understanding. Accept varied wording. Deduct 3 pts if student confuses prior and posterior.
Question 2 — Model Answer
Disease base rate 1%, sensitivity 95%, specificity 90%.
Full Calculation
Let D = disease, T+ = positive test.

P(D) = 0.01    P(T+|D) = 0.95    P(T+|¬D) = 0.10

P(T+) = P(T+|D)·P(D) + P(T+|¬D)·P(¬D)
       = 0.95 × 0.01 + 0.10 × 0.99 = 0.0095 + 0.099 = 0.1085

P(D|T+) = (0.95 × 0.01) / 0.1085 ≈ 0.0876 ≈ 8.76%

Despite a 95% sensitive test, only ~9% of positives actually have the disease — because the disease is rare. This is the base rate fallacy.
Question 3 — Model Answer
Lab observation with bias=0.70, flat prior.
Expected Observations
After 50 flips: posterior mean should be approximately 0.63–0.72 (random variation).
After 100 flips: posterior mean should be closer to 0.70, with a narrower distribution.

Pattern: The posterior mean converges toward the true bias (0.70) as more data accumulates. The distribution also becomes narrower (more certain). This demonstrates the law of large numbers in a Bayesian framework.

Accept any reasonable empirical observation. Award full credit if student correctly describes convergence and reduced uncertainty.
Question 4 — Model Answer
Strong priors and evidence requirements in medicine.
Answer
A strong prior (e.g., concentrated Beta(20,20) belief in fairness) mathematically requires many data points to shift the posterior significantly, because the evidence must "outvote" the prior weight. In medicine, if a disease has prevalence of 0.01% (e.g., a rare genetic disorder), even a highly accurate test will produce mostly false positives in population screening — because P(Disease) in the prior is extremely low. The evidence of a positive test must contend with the strong prior probability of the patient not having the disease. This is why rare disease screening requires confirmation testing.
Week 2 — Textbook

The Beta Distribution:
A Prior Made for Probabilities

The Beta distribution is the natural choice for representing uncertainty about a probability. It lives between 0 and 1, and it updates beautifully when new data arrives.

1. Why We Need a Distribution for P

In Week 1, we treated our hypotheses as discrete ("fair" vs. "biased"). But in reality, the coin's bias θ is a continuous value between 0 and 1. We need a probability distribution that lives on [0,1] and can represent all our uncertainty about θ.

Enter the Beta distribution: Beta(α, β).

Beta(θ | α, β) ∝ θ^(α−1) · (1−θ)^(β−1)

2. Understanding α and β

Think of α and β as "pseudo-counts":

ParameterIntuitionEffect on Distribution
αPrior heads observationsShifts distribution right (toward 1)
βPrior tails observationsShifts distribution left (toward 0)
α+βTotal prior "confidence"Concentration: higher = narrower = more certain

A flat prior (total ignorance) is Beta(1,1) — a uniform distribution. "I believe the coin is fair, with moderate confidence" might be Beta(10,10).

3. The Magic: Conjugate Updating

The Beta distribution is a conjugate prior for the Binomial likelihood. This means: if you start with Beta(α, β) and observe h heads and t tails, your posterior is simply:

Posterior = Beta(α + h, β + t)

No integration. No numerical approximation. Just add your counts to the prior parameters. This is the mathematical elegance that makes Beta-Binomial updating so powerful and intuitive.

4. Python Implementation

PYTHON
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import beta as beta_dist
import random

# === PARAMETERS ===
TRUE_BIAS = 0.65        # The "true" bias of the coin (unknown to us)
ALPHA_PRIOR = 2        # Initial prior: pseudo-heads count
BETA_PRIOR  = 2        # Initial prior: pseudo-tails count
N_FLIPS = 100           # Number of coin flips to simulate

def flip_coin(p_heads=0.5):
    """Simulate a single biased coin flip."""
    return 1 if random.random() < p_heads else 0

def update_posterior(alpha, beta_param, outcome):
    """Update Beta parameters given a coin flip outcome (1=H, 0=T)."""
    if outcome == 1:   # Heads
        alpha += 1
    else:              # Tails
        beta_param += 1
    return alpha, beta_param

# === SIMULATION ===
alpha, beta_param = ALPHA_PRIOR, BETA_PRIOR
theta = np.linspace(0, 1, 200)
snapshots = [(0, alpha, beta_param)]

for i in range(N_FLIPS):
    outcome = flip_coin(TRUE_BIAS)
    alpha, beta_param = update_posterior(alpha, beta_param, outcome)
    if (i + 1) in [5, 10, 25, 50, 100]:
        snapshots.append((i + 1, alpha, beta_param))

# === PLOTTING ===
fig, axes = plt.subplots(1, len(snapshots), figsize=(18, 4))
for ax, (n, a, b) in zip(axes, snapshots):
    y = beta_dist.pdf(theta, a, b)
    ax.fill_between(theta, y, alpha=0.3, color='steelblue')
    ax.plot(theta, y, color='steelblue')
    ax.axvline(TRUE_BIAS, color='red', ls='--', alpha=0.7)
    ax.set_title(f'n={n}\nBeta({a},{b})')
    ax.set_xlabel('θ (P heads)')
plt.suptitle('Posterior Evolution: Beta-Binomial Updating', fontsize=14)
plt.tight_layout()
plt.savefig('posterior_evolution.png', dpi=150)
plt.show()

5. Java Implementation

JAVA
import org.apache.commons.math3.distribution.BetaDistribution;
import java.util.Random;

public class BayesianCoinFlip {
    private double alpha;
    private double beta;
    private final double trueBias;
    private final Random rng = new Random();

    public BayesianCoinFlip(double alpha, double beta, double trueBias) {
        this.alpha    = alpha;
        this.beta     = beta;
        this.trueBias = trueBias;
    }

    /** Simulate one coin flip and update the posterior. */
    public boolean flipAndUpdate() {
        boolean heads = rng.nextDouble() < trueBias;
        if (heads) alpha++; else beta++;
        return heads;
    }

    public double posteriorMean() { return alpha / (alpha + beta); }
    public double posteriorVariance() {
        double n = alpha + beta;
        return (alpha * beta) / (n * n * (n + 1));
    }

    public static void main(String[] args) {
        BayesianCoinFlip sim = new BayesianCoinFlip(2, 2, 0.65);
        int[] snappoints = {5, 10, 25, 50, 100};
        int next = 0;
        for (int i = 1; i <= 100; i++) {
            sim.flipAndUpdate();
            if (next < snappoints.length && i == snappoints[next]) {
                System.out.printf("n=%3d | Mean: %.3f | Var: %.5f%n",
                    i, sim.posteriorMean(), sim.posteriorVariance());
                next++;
            }
        }
    }
}
Week 2 — Interactive Lab

Beta Distribution Shaper

Explore how α and β shape the Beta distribution. Then run the full sequential Bayesian updating simulation.

Beta Distribution Explorer

Adjust α and β to shape your prior belief about P(heads). Observe mean, mode, and variance.

α = 2.0
β = 2.0
0.50
Mean (α/(α+β))
0.50
Mode
0.050
Variance
—
95% Credible Interval
Try these presets:

Sequential Bayesian Updating

Run a full simulation and watch posterior snapshots at 5, 10, 25, 50, and 100 flips.

θ = 0.70

Python Coding Challenge — Build the Beta Updater

Write your own Beta-Binomial sequential updater below. The code computes the posterior at multiple snapshots and renders an overlay chart — all inside your browser.

  • Change TRUE_BIAS, ALPHA, BETA, and N_FLIPS
  • Modify SNAP_AT to choose which flip counts to snapshot
  • Try a strong prior Beta(20,20) vs flat Beta(1,1) — compare convergence speed
week2_beta_updater.py  — Beta Distribution Updater
Python 3.11 · Pyodide
loading…
Ctrl+Enter to run
console output
Python environment shared — already loaded if you ran Week 1.
visualization — posterior snapshots overlay
Run your code to generate a snapshot overlay chart
Week 2 Assignment

Coding the Beta-Binomial Updater

Due: End of Week 2
Points: 60
Format: Code Submission + Analysis
Question 1 — Coding (25 pts)
Implement the flip_and_update() function in Python (or the Java equivalent). Your function should accept the current α and β, simulate one coin flip using a given true bias, and return the updated (α, β) pair. Run 200 flips and print the posterior mean every 10 flips.
Submit your code file (.py or .java) along with printed output
Question 2 — Analysis (20 pts)
Run two experiments: (A) Start with Beta(1,1) — flat prior. (B) Start with Beta(20,20) — strong "fair coin" prior. Both times use a true bias of θ = 0.75 and flip 100 times. Compare the posterior means and widths (variance) after 100 flips. Which prior recovered the true bias more quickly? Why?
Write your analysis (4–6 sentences) and include code output
Question 3 — Visualization (15 pts)
Produce a plot showing the posterior Beta distribution at n = 0 (prior), 10, 50, and 200 flips. Use a vertical dashed line to mark the true bias. Label each curve with its (α, β) values. Submit the saved image file.
Attach image file: posterior_evolution.png
Instructor Resource

Week 2 — Answer Sheet

Question 1 — Reference Code (Python)
Model Implementation
import random

def flip_and_update(alpha, beta, true_bias):
    outcome = 1 if random.random() < true_bias else 0
    if outcome == 1:
        alpha += 1
    else:
        beta += 1
    return alpha, beta

alpha, beta = 2, 2
for i in range(200):
    alpha, beta = flip_and_update(alpha, beta, 0.70)
    if (i + 1) % 10 == 0:
        print(f"n={i+1:3d} | Posterior mean = {alpha/(alpha+beta):.4f}")
        
Expected output: posterior mean converges toward ~0.70 over 200 flips.
Question 2 — Expected Analysis
Key Points
Experiment A (Beta(1,1)): After 100 flips with θ=0.75, expected α≈76, β≈26. Posterior mean ≈ 76/102 ≈ 0.745. Narrow distribution.

Experiment B (Beta(20,20)): After 100 flips with θ=0.75, expected α≈95, β≈45. Posterior mean ≈ 95/140 ≈ 0.679. Wider and slower to converge.

Flat prior recovers true bias more quickly because the data can dominate without fighting a strong prior assumption of fairness. The strong prior requires more evidence to shift. Grading: award credit for correct directional reasoning even if numeric values differ.
Question 3 — Visualization Rubric
Grading Criteria
5 pts: Correct Beta distributions plotted at each snapshot
5 pts: Distributions visually narrow and shift toward true bias over time
3 pts: True bias dashed line present
2 pts: Proper labels (α, β values, n, axes)
Week 3 — Textbook

Bayesian Inference
in Precision Health

From coin flips to clinical decisions — Bayesian reasoning is transforming how we diagnose disease, personalize treatment, and interpret biomarker data.

1. The Clinical Relevance of Base Rates

In Week 1, we showed that even a 95%-accurate test for a 1% prevalence disease is only 8.76% likely to be correct on a positive result. This is not a flaw in the test — it's a fundamental property of probability that physicians must internalize.

The Base Rate Fallacy
Studies show that many physicians intuitively give test sensitivity and specificity more weight than disease prevalence when interpreting test results. Bayesian literacy directly counters this dangerous cognitive error.

2. Sensitivity, Specificity, and Predictive Values

MetricFormulaBayesian Interpretation
Sensitivity (TPR)TP / (TP + FN)P(Test+ | Disease+) = Likelihood
Specificity (TNR)TN / (TN + FP)1 − P(Test+ | Disease−)
PPVTP / (TP + FP)P(Disease+ | Test+) = Posterior
NPVTN / (TN + FN)P(Disease− | Test−) = Posterior

PPV and NPV are the clinically actionable numbers — and both depend critically on disease prevalence (the prior).

3. Sequential Updating in Patient Care

Bayesian updating mirrors how good clinicians think. A physician's initial assessment ("fever + cough → 30% probability of pneumonia") is a prior. A chest X-ray is evidence. The updated probability is the posterior. A positive culture is more evidence. The final treatment decision is informed by the final posterior.

4. Precision Medicine Applications

  • Pharmacogenomics — Bayesian models update drug response probabilities given genotype
  • Cancer screening — Combining PSA, family history, and imaging with Bayesian networks
  • Wearable sensor data — Continuously updating arrhythmia risk from ECG streams
  • Clinical trial design — Bayesian adaptive trials can stop early for efficacy or futility
  • Digital phenotyping — Updating behavioral models from smartphone sensor data over time

5. The Bayesian Brain

Remarkably, neuroscientists now believe the brain itself performs Bayesian inference — combining prior expectations (based on experience) with sensory evidence to construct perception. In this sense, Bayesian thinking is not just a statistical method — it's how intelligence works.

"Bayesian inference is the mathematics of learning. It describes, in a unified framework, how any rational agent — human, clinical algorithm, or AI — should update beliefs when new information arrives."
Week 3 — Interactive Lab

Diagnostic Testing Simulator

Simulate clinical Bayesian inference. Adjust disease prevalence and test performance, and see how posterior probability changes with sequential testing.

Bayesian Diagnostic Simulator

Set prevalence, sensitivity, and specificity. Run tests and update your clinical probability estimate.

1.0%
95.0%
90.0%
1.0%
Prior Probability
—
PPV (P(Disease|+))
—
NPV (P(No Disease|−))
0
Tests Run
Run a test to see clinical interpretation...
Clinical Insight
Notice how running the same test multiple times on a positive patient gradually increases your certainty. Also observe how a negative test dramatically reduces probability — sometimes more than a positive test raises it.

Python Coding Challenge — Clinical Bayesian Inference

Code a full diagnostic Bayesian simulator. Adjust disease parameters, simulate multiple tests, and visualize how clinical certainty evolves — all in pure Python running in your browser.

  • Set HAS_DISEASE = True/False to test both patient types
  • Try rare disease: PREVALENCE = 0.005 — notice how hard it is to reach certainty
  • Add a second independent test type by defining sens2, spec2 and interleaving
week3_diagnostic_bayes.py  — Clinical Bayesian Simulator
Python 3.11 · Pyodide
loading…
Ctrl+Enter to run
console output
Python environment shared — runs instantly if already loaded.
visualization — posterior probability trajectory
Run your code to generate the diagnostic trajectory chart
Week 3 Assignment

Bayesian Reasoning in Clinical Cases

Due: End of Week 3
Points: 70
Format: Case Study + Code + Reflection
Question 1 — Case Study (25 pts)
Scenario: A new biomarker test for early Alzheimer's disease has 90% sensitivity and 85% specificity. In the general population over age 65, roughly 10% have early Alzheimer's. A 68-year-old patient tests positive.

(a) Calculate P(Alzheimer's | Positive test).
(b) The same patient undergoes a second independent test (same metrics) and again tests positive. Calculate the updated probability.
(c) Explain in plain language why two positive tests increase certainty substantially more than one.
Show all calculations and written explanation
Question 2 — Coding (30 pts)
Write a Python or Java program that simulates sequential Bayesian diagnostic updating. The program should: (1) Accept prevalence, sensitivity, specificity as inputs, (2) Simulate a patient who either has or doesn't have the disease, (3) Run up to 5 tests, updating the posterior after each, (4) Plot the posterior probability trajectory. Use the Week 3 lab as a reference for expected behavior.
Submit code file and output plot
Question 3 — Reflection (15 pts)
Describe one real-world precision health application where Bayesian reasoning is (or could be) applied. What is the prior? What is the evidence (likelihood)? What does the posterior represent in clinical practice? How might this change patient care?
Write 4–6 sentences
Instructor Resource

Week 3 — Answer Sheet

Question 1 — Case Study Answers
Part (a): First Positive Test
P(D) = 0.10, P(+|D) = 0.90, P(+|¬D) = 0.15
P(+) = 0.90×0.10 + 0.15×0.90 = 0.09 + 0.135 = 0.225
P(D|+) = 0.09 / 0.225 = 0.400 (40%)
Part (b): Second Positive Test — Use posterior from (a) as new prior
New prior = 0.40
P(+) = 0.90×0.40 + 0.15×0.60 = 0.36 + 0.09 = 0.45
P(D|++) = 0.36 / 0.45 = 0.800 (80%)
Part (c): Explanation
Each positive test updates the prior upward. The second test starts from a much higher prior (40% vs 10%), so the same likelihood ratio produces a much larger jump. The multiplicative nature of Bayesian updating means early tests are relatively weak (fighting against a strong "no disease" prior), while later tests operate from a higher baseline and can dramatically concentrate probability. This is why confirmatory testing is so powerful — each result compounds the certainty from the last.
Question 2 — Reference Code
Python Solution
import random
import matplotlib.pyplot as plt

def run_diagnostic_simulation(prevalence, sensitivity, specificity, has_disease, n_tests=5):
    fp_rate = 1 - specificity
    prior = prevalence
    history = [prior]

    for _ in range(n_tests):
        # Simulate test outcome
        if has_disease:
            test_pos = random.random() < sensitivity
        else:
            test_pos = random.random() < fp_rate

        if test_pos:
            likelihood = sensitivity
            likelihood_neg = fp_rate
        else:
            likelihood = 1 - sensitivity
            likelihood_neg = specificity

        # Bayes update
        numerator = likelihood * prior
        denominator = numerator + likelihood_neg * (1 - prior)
        posterior = numerator / denominator
        history.append(posterior)
        prior = posterior

    return history

history = run_diagnostic_simulation(0.10, 0.90, 0.85, has_disease=True)
plt.plot(range(len(history)), [h*100 for h in history], 'o-', color='purple')
plt.xlabel('Tests Completed')
plt.ylabel('P(Disease) %')
plt.title('Sequential Bayesian Diagnostic Updating')
plt.grid(True, alpha=0.3)
plt.savefig('diagnostic_trajectory.png', dpi=150)
plt.show()
        
Question 3 — Sample Strong Answer
Model Answer
In digital phenotyping for depression monitoring, smartphone sensor data (movement, screen time, call frequency) serves as ongoing evidence. The prior might be established from a patient's clinical history — a known baseline depression risk score. The likelihood is derived from a trained model of how behavioral signals correlate with depressive episodes. The posterior updates daily, giving clinicians a continuously refined estimate of current mental health status. This could enable early intervention — alerting care teams when posterior risk crosses a threshold — before the patient presents in crisis, fundamentally shifting care from reactive to proactive.