---
title: "Machine Learning Fundamentals – The Public Health AI Handbook"
source: "https://publichealthaihandbook.com/foundations/ai-basics.html"
author: "Bryan Tegomoh, MD, MPH"
last_updated: "2026-11-01"
doi: "10.5281/zenodo.18263441"
license: CC BY 4.0
generated-by: handbook-markdown-export
---

# Machine Learning Fundamentals

Machine learning for public health does not require a PhD. Practitioners need working knowledge of common paradigms, when to compare logistic regression with tree-based and neural models, how to avoid overfitting, and how domain knowledge should inform feature definition and validation.

Test characteristics at the bedside, including sensitivity, prevalence, and calibration at a decision threshold, are in the [Physician AI Handbook](https://physicianaihandbook.com/foundations/ai-basics.html).

Learning Objectives

Readers will be able to:

- Distinguish three ML paradigms (supervised, unsupervised, reinforcement learning)
- Select appropriate algorithms based on problem structure and interpretability needs
- Recognize overfitting, data leakage, and the bias-variance tradeoff
- Choose evaluation metrics beyond accuracy (precision, recall, AUROC)
- Identify common pitfalls causing deployment failures
- Distinguish genuine AI capabilities from marketing hype

Prerequisites: [History of AI in Public Health](../foundations/history.html).

Chapter Summary (TL;DR)

**The Big Picture:** Practitioners need enough knowledge to choose the right tool, avoid serious mistakes, and communicate with technical teams. The focus is on practical public health applications.

**Three ML Paradigms (Pick the Right One):**

- **Supervised Learning (most common in public health AI):** Learn from labeled examples (input + correct output) → predict outcomes. Use when you have historical data with known answers (disease diagnosis, outbreak prediction, risk stratification)
- **Unsupervised Learning:** Find hidden patterns in unlabeled data (clustering, anomaly detection). Use for exploratory analysis and discovering structure
- **Reinforcement Learning:** Learn optimal actions through trial and error. **Much harder** to implement than supervised learning; use it only for sequential decision optimization

**Algorithm Selection Guide (Start Simple, Add Complexity Only If Needed):**

1.  **Logistic Regression:** Your default starting point. Interpretable coefficients (odds ratios), works with modest data, fast, epidemiologists understand it intuitively
2.  **Random Forests:** Best first “real” ML model. Robust, handles messy data, provides feature importance, works out-of-the-box
3.  **Gradient Boosting (XGBoost):** Often a strong benchmark for tabular data, but not a universal winner over neural networks; more hyperparameters to tune
4.  **Deep Learning:** Only for images (CNNs), text (transformers), or truly complex patterns. For tabular public health data, tree-based methods often perform better in benchmark comparisons

**Critical Reality Check:** For most public health **spreadsheet data** (rows and columns), gradient-boosted trees often outperform neural networks in benchmark comparisons. Save deep learning for medical imaging, clinical notes, and multimodal data.

**Evaluation Metrics (Accuracy Alone Is Misleading):**

- **Accuracy:** Total correct predictions. **Fails with imbalanced data** (99% accuracy predicting “no disease” for 1% prevalence = useless)
- **Sensitivity (Recall):** Fraction of actual cases detected. **Critical for screening** (do not miss disease)
- **Specificity:** Fraction of healthy correctly identified. **Critical when false alarms are costly**
- **ROC-AUC:** Summarizes discrimination across thresholds (0.5 = random). Interpret it alongside calibration and threshold-specific metrics; no fixed AUC value establishes clinical utility
- **Always report confusion matrix** so readers can calculate their preferred metric

**The Cardinal Sins (What Kills Models):**

1.  **Overfitting:** Training accuracy 95%, test accuracy 65% → model memorized noise. Fix: more data, regularization, simpler model, cross-validation
2.  **Data Leakage:** Test information contaminates training (e.g., normalizing before splitting). Makes model look better than it is. **Always split first, then preprocess**
3.  **Ignoring Class Imbalance:** Rare events (1% outbreaks) need special handling: use class weights, SMOTE, or appropriate metrics (F1, ROC-AUC, not accuracy)
4.  **Temporal Violations:** For time series, **never use future to predict past**. Use temporal train/test splits, not random shuffling

**The Bias-Variance Tradeoff:**

- **Underfitting (high bias):** Model too simple, fails even on training data
- **Overfitting (high variance):** Model too complex, memorizes training data, fails on new data
- **Sweet spot:** Complex enough to capture patterns, simple enough to generalize

**The Most Important Lesson:** **Feature engineering and model choice both depend on the decision context.** Domain knowledge helps define meaningful variables, avoid leakage, and interpret failure modes. Technical expertise is also necessary for valid model development and evaluation.

**The Takeaway for Public Health Practitioners:** Start with an interpretable baseline such as logistic regression. For many medium-sized tabular datasets, gradient-boosted trees are a strong benchmark, but performance depends on the dataset, representation, validation design, and tuning ([Shwartz-Ziv & Armon, 2022, *Information Fusion*](https://doi.org/10.1016/j.inffus.2021.11.011); [Grinsztajn et al., 2022, *NeurIPS*](https://proceedings.neurips.cc/paper_files/paper/2022/hash/0378c7692da36807bdec87ab043cdadc-Abstract-Datasets_and_Benchmarks.html)). Compare model families rather than assuming one will win. Always validate on held-out data or with an appropriate nested resampling design, and report multiple decision-relevant metrics.

→ **See also:** [Evaluating AI in Public Health Practice](../implementation/evaluation.html) for validation strategies and [The Data Problem in Public Health AI](../foundations/data.html) for data quality and feature engineering guidance

Check Your Understanding

Test your grasp of the key concepts before proceeding:

**1. Algorithm Selection:** You have a dataset of 5,000 patient records (rows) with 30 clinical variables (columns) predicting hospital readmission. Which algorithm should you try FIRST?

- A. Deep neural network with 10 hidden layers
- B. Logistic regression
- C. Reinforcement learning
- D. Large language model

Click for answer

**Answer: B. Logistic regression**

Why: For tabular public health data with modest size, start simple. Logistic regression is interpretable, works with this data size, and epidemiologists understand it. Save deep learning for images/text or after simpler methods fail.

**2. Evaluation Metrics:** Your disease screening model has 95% accuracy predicting COVID-19 from symptoms. Disease prevalence is 2%. Should you deploy it?

- A. Yes, 95% accuracy is excellent
- B. No, need to check sensitivity, specificity, and ROC-AUC first
- C. No, accuracy is meaningless for imbalanced data
- D. Both B and C

Click for answer

**Answer: D. Both B and C**

Why: With 2% prevalence, a model predicting “no COVID” for everyone gets 98% accuracy but is useless. For rare events, accuracy is misleading. Check sensitivity (do not miss cases), specificity (minimize false alarms), and ROC-AUC.

**3. Cardinal Sins:** Your model gets 92% training accuracy but only 67% test accuracy. What’s the problem?

- A. Data leakage
- B. Overfitting
- C. Underfitting
- D. Class imbalance

Click for answer

**Answer: B. Overfitting**

Why: Large gap between training and test performance indicates overfitting: the model memorized training noise instead of learning generalizable patterns. Fix: more data, regularization, simpler model, cross-validation.

**4. Feature Engineering:** A data scientist with a PhD in machine learning and a public health epidemiologist with 10 years of field experience are both building outbreak prediction models. Who has the advantage?

- A. Data scientist, they know advanced algorithms
- B. Epidemiologist, they know which variables matter
- C. Neither, both skills are equally important
- D. Depends on the problem

Click for answer

**Answer: C. Neither, both skills are equally important**

Why: Epidemiologic knowledge is essential for defining time windows, risk factors, and plausible features. Machine-learning expertise is essential for constructing and validating the model. The strongest approach is collaboration, not assuming either discipline has a universal advantage.

**5. Practical Application:** You’re asked to build an AI system to “improve public health.” What should you do FIRST?

- A. Choose an algorithm (deep learning is popular)
- B. Collect as much data as possible
- C. Define a specific, measurable problem
- D. Read papers on the latest AI techniques

Click for answer

**Answer: C. Define a specific, measurable problem**

Why: “Improve public health” is too vague. AI solves specific problems: predict hospital readmission, detect disease outbreaks, classify medical images. Start with the problem, not the technology. Vague goals → failed projects.

**Scoring:**

- **5/5:** The fundamentals are in place. Proceed to the next section.
- **3–4/5:** Good grasp. Review sections where you missed questions.
- **0–2/5:** Reread the TL;DR summary above before continuing.

## Introduction

You do not need a PhD in machine learning to use AI effectively in public health. You need to understand **just enough** to:

- Choose the right tool for your problem
- Interpret results critically
- Avoid common pitfalls
- Communicate with technical teams
- Know when AI is the wrong solution

The emphasis is on **concepts, intuition, and practical application** rather than heavy math.

What This Chapter Is NOT

This is not a comprehensive ML course. For deep technical knowledge, see [Andrew Ng’s Machine Learning Specialization](https://www.coursera.org/specializations/machine-learning-introduction) or the [Deep Learning book](https://www.deeplearningbook.org/) by Goodfellow et al.

The aim is working knowledge for evaluating AI systems, communicating with technical teams, and making informed decisions about AI adoption.

## How Machine Learning Actually Works

These core concepts define what “machine learning” means and underpin the algorithms that follow.

### What is a Model?

A **model** is a mathematical function that maps inputs to outputs. You already use models: logistic regression maps patient characteristics to disease probability. The equation \\\text{logit}(p) = \beta_0 + \beta_1 X_1 + ...\\ is a model.

In ML, “model” means the same thing, but models can have millions of adjustable values instead of a handful of \\\beta\\ coefficients.

### What is “Learning”?

When we say a model “learns,” we mean: **the algorithm adjusts numerical values (parameters) to minimize prediction errors on training data.**

This is identical to what happens when you fit a logistic regression. The computer finds \\\beta\\ values that best predict your outcome. ML extends this to models with vastly more parameters, using different optimization techniques.

### What is a Loss Function?

A **loss function** quantifies how wrong the model’s predictions are. Common examples:

- **Squared error** for regression: \\(y\_{true} - y\_{pred})^2\\
- **Cross-entropy** for classification: measures how far predicted probabilities are from 0/1 truth

Training minimizes this loss. Different problems use different loss functions, and the choice shapes what the model learns to optimize.

### What is Gradient Descent?

When you have millions of parameters, you cannot solve for optimal values directly (no closed-form solution). Instead, ML uses **gradient descent**: an iterative process that finds good parameter values by following the slope of the loss function “downhill.”

**Intuition:** Imagine finding the lowest point in a valley while blindfolded. You feel which direction goes downhill, take a small step that way, then repeat. Eventually you reach the bottom. That is gradient descent: the “gradient” tells you which direction is steepest.

The **learning rate** controls step size: too large and you overshoot; too small and training becomes slow.

### Parameters vs. Hyperparameters

Two types of numerical values in ML:

- **Parameters**: Learned from data during training (like \\\beta\\ coefficients). The model adjusts these automatically.
- **Hyperparameters**: Set by you before training (like tree depth, learning rate, number of hidden layers). These control the learning process itself.

**Example:** In Random Forest, the number of trees (500) is a hyperparameter you choose. The specific split points in each tree are parameters learned from data.

For Epidemiologists: What You Already Know

Much of ML is familiar under different names:

| Biostatistics               | Machine Learning | Notes                         |
|-----------------------------|------------------|-------------------------------|
| Predictors, covariates      | Features         | Identical concept             |
| Outcome, dependent variable | Label, target    | Identical concept             |
| Model fitting               | Training         | Same process, different name  |
| Residual deviance           | Loss             | Both measure prediction error |
| LASSO, Ridge regression     | Regularization   | Identical technique           |
| Validation sample           | Test set         | Similar purpose               |
| Penalized likelihood        | Regularized loss | Same mathematical approach    |

You already understand the core concepts. ML extends them to larger models and different problem types.

## Three Common Learning Paradigms

Most machine learning methods fall into three categories. For a textbook introduction to the field, see [Mitchell’s *Machine Learning*](https://www.cs.cmu.edu/~tom/mlbook.html). Master these, and most AI applications in public health will be familiar.

### 1. Supervised Learning: Learning from Examples

**The Idea:** You show the algorithm examples of inputs and correct outputs. It learns the pattern. Then it predicts outputs for new inputs.

**Analogy:** Teaching a medical student by showing them patient cases with known diagnoses.

**Real-world example:**

    Input: Patient symptoms (fever, cough, chest pain)
    Output: Diagnosis (pneumonia)

    You show the algorithm 10,000 labeled examples.
    It learns: "fever + productive cough + chest pain → pneumonia (85% probability)"

**When to use it:**

- You have labeled historical data (inputs + correct answers)
- You want to predict a specific outcome
- Examples: disease diagnosis, outbreak prediction, risk stratification

**Public health applications:**

- Predicting which patients will develop [sepsis using electronic health records](https://doi.org/10.1126/scitranslmed.aab3719)
- Classifying disease from medical images
- [Forecasting epidemic curves](https://doi.org/10.1073/pnas.1812594116)
- Identifying high-risk populations

The Key Constraint

Supervised learning requires **labeled data**, meaning someone (often human experts) must have already provided the “correct answers” for your training examples.

In public health, getting quality labels is often the hardest part. As [Rajkomar et al. (2019) note in their NEJM review](https://doi.org/10.1056/NEJMra1814259), a model is only as good as its training data.

### 2. Unsupervised Learning: Finding Hidden Patterns

**The Idea:** You give the algorithm data with NO labels. It finds structure, patterns, or groups on its own.

**Analogy:** Sorting a messy pile of patient records into natural categories without being told what categories to use.

**Real-world example:**

    Input: Symptom reports from 50,000 emergency department visits
    Output: "I found 7 distinct clusters, one looks like flu-like illness,
       another looks like gastrointestinal illness, etc."

**When to use it:**

- You have unlabeled data (as most data are)
- You want to discover structure or segments
- You’re exploring without a specific prediction goal

**Public health applications:**

- Identifying disease subtypes from symptom patterns
- Segmenting populations by health behavior
- [Detecting anomalies in outbreak surveillance](https://doi.org/10.1109/ACCESS.2020.3022366)
- Reducing data dimensions for visualization

**Common techniques:**

- **Clustering** (k-means, hierarchical, [DBSCAN](https://dl.acm.org/doi/10.5555/3001460.3001507))
- **Dimensionality reduction** (PCA, [t-SNE](https://www.jmlr.org/papers/v9/vandermaaten08a.html), [UMAP](https://arxiv.org/abs/1802.03426))
- **Anomaly detection**

### 3. Reinforcement Learning: Learning by Trial and Error

**The Idea:** An agent takes actions in an environment and receives rewards or penalties. It learns which actions lead to the best outcomes. This approach, formalized by [Sutton and Barto in their seminal text](http://incompleteideas.net/book/the-book-2nd.html), has applications in sequential decision-making.

**Analogy:** Training a dog: reward good behavior, discourage bad behavior, and let it learn through experience.

**When to use it:**

- You’re optimizing sequential decisions
- There’s no “correct answer” dataset
- You have a simulator or can interact safely

**Public health applications:**

- [Optimizing vaccine distribution strategies](https://doi.org/10.1145/3502827.3502844)
- [Adaptive clinical trial designs](https://doi.org/10.1186/s12916-020-01808-2)
- Resource allocation during outbreaks
- [Personalized treatment sequencing](https://doi.org/10.1038/s41591-018-0310-5)

Reality Check

Reinforcement learning is appealing but **much harder** to implement than supervised learning. It requires careful reward engineering and substantial computational resources.

For most public health problems, supervised learning is more practical. Do not use RL for its novelty alone.

**The rest of this chapter focuses primarily on supervised learning.** It represents the majority of practical public health AI applications.

Beyond Traditional RL: LLM-Based AI Agents

The “agents” described above refer to traditional reinforcement learning. A newer paradigm has emerged: **LLM-based AI agents** that combine large language models with tool use (web search, code execution, API calls) to accomplish complex multi-step goals. These agents can plan, act, observe results, and iterate autonomously. For coverage of tool-using language models, applications, and safety considerations, see [Large Language Models in Public Health: Theory and Practice](../future/llm-theory-practice.html).

## Core Supervised Learning Concepts

### The Machine Learning Workflow

Most supervised learning projects follow this pattern, as outlined in [Geron’s practical guide](https://www.oreilly.com/library/view/hands-on-machine-learning/9781492032632/):

1.  **Collect labeled data** (features + known outcomes)
2.  **Define a validation design**: preserve an untouched test set when feasible, and use a separate validation set or nested cross-validation for tuning according to sample size and deployment setting ([scikit-learn nested cross-validation guidance](https://scikit-learn.org/stable/auto_examples/model_selection/plot_nested_cross_validation_iris.html))
3.  **Choose and train a model** (algorithm learns patterns from training data)
4.  **Evaluate on unseen test data** (measure real-world performance)
5.  **Deploy and monitor** (put into production, track ongoing performance)

Python: ML Workflow Overview

Show code

``` sourceCode
# 1. Collect labeled data
data = load_outbreak_data() # Features + outcomes

# 2. Split into train/test sets
train_data, test_data = split(data, test_size=0.2)

# 3. Choose and train a model
model = RandomForestClassifier()
model.fit(train_data.features, train_data.outcomes)

# 4. Evaluate on unseen test data
predictions = model.predict(test_data.features)
accuracy = evaluate(predictions, test_data.outcomes)

# 5. Deploy and monitor
model.save('outbreak_predictor.pkl')
```

Each step is described below.

### Step 1: Features and Labels

**Features** (also called “predictors” or “independent variables”): The inputs your model uses to make predictions.

**Labels** (also called “targets” or “dependent variables”): The outputs you’re trying to predict.

**Example: Predicting dengue outbreaks**

| Week | Temperature | Rainfall | Prev_Cases | **Label: Outbreak?** |
|------|-------------|----------|------------|----------------------|
| 1    | 28°C        | 120mm    | 15         | No                   |
| 2    | 30°C        | 200mm    | 18         | No                   |
| 3    | 31°C        | 250mm    | 45         | **Yes**              |
| 4    | 29°C        | 180mm    | 60         | **Yes**              |

Features: Temperature, Rainfall, Previous Cases Label: Outbreak (Yes/No)

Feature Engineering: The Secret Sauce

Raw data is rarely ideal for ML. **Feature engineering**, creating new features from existing data, is where domain expertise matters most, as emphasized in [Domingos’ influential paper on machine learning pitfalls](https://dl.acm.org/doi/10.1145/2347736.2347755).

Examples:

- Raw: Daily case counts → Engineered: 7-day rolling average
- Raw: Birth date → Engineered: Age in years
- Raw: GPS coordinates → Engineered: Distance to nearest hospital
- Raw: Text symptoms → Engineered: Presence/absence of key symptom terms

This is where **epidemiologic expertise matters most**: epidemiologists know which features matter biologically and epidemiologically.

### Step 2: Training, Validation, and Testing

**A critical concept:** When sample size allows, use THREE data splits, not just two, as explained in [Hastie et al.’s comprehensive statistical learning text](https://hastie.su.domains/ElemStatLearn/).

1.  **Training set (60–70%)**: Model learns patterns from this
2.  **Validation set (10–20%)**: Used to tune model settings (hyperparameters)
3.  **Test set (20%)**: **Never touched until final evaluation**, simulates real-world performance

**Why this matters:**

- **BAD approach:** Tune your model based on test set performance. This “cheats” by peeking at data meant to simulate real-world conditions.
- **GOOD approach:** Use the validation set for all adjustments. Only check the test set once, at the very end.

Python: Train/Validation/Test Splits

Show code

``` sourceCode
# BAD: Tuning on test data
model = train_model(train_data)
# Adjust model settings...
performance = evaluate(model, test_data) # Too optimistic!

# GOOD: Using validation set
model = train_model(train_data)
# Adjust model settings based on validation performance...
performance = evaluate(model, validation_data)
# Only after all tuning is done:
final_performance = evaluate(model, test_data) # True performance
```

The Cardinal Sin: Data Leakage

**Data leakage** happens when information from the test set “leaks” into training. This makes your model look better than it really is.

[Kaufman et al.](https://doi.org/10.1145/2382577.2382579) describe leakage more generally as the introduction of information about the prediction target that should not legitimately be available, and note that it has been deemed one of the top ten data mining mistakes.

Common mistakes:

- Normalizing features before splitting data
- Including future information in features
- Using the same patients in both train and test
- Cross-validation on time series without respecting temporal order

See [this excellent guide on data leakage](https://machinelearningmastery.com/data-leakage-machine-learning/) for more.

### Step 3: What “Training” Actually Means

The term “training” has a specific meaning.

**In brief:** The algorithm adjusts internal parameters to minimize prediction errors.

**Logistic regression makes this concrete** (a familiar epidemiologic method):

You’re familiar with: \\\text{logit}(p) = \beta_0 + \beta_1 X_1 + \beta_2 X_2 + ...\\

In traditional statistics, you estimate \\\beta\\ coefficients using [maximum likelihood estimation](https://doi.org/10.1098/rsta.1922.0009).

**Predictive machine learning often uses related estimation ideas, but:**

- Often with millions of parameters
- Using iterative optimization ([stochastic gradient methods](https://doi.org/10.1214/aoms/1177729586), not closed-form solutions)
- With [regularization to prevent overfitting](https://doi.org/10.1198/016214501753382273)
- On much larger datasets

The model is **learning from mistakes**: making predictions, measuring how wrong they are (the “loss”), and adjusting parameters to reduce that error. This cycle repeats until performance stops improving.

How Training Works (Technical Detail)

Show code

``` sourceCode
# Simplified training loop
for epoch in range(num_epochs):
 # Make predictions with current parameters
 predictions = model.predict(X_train)

 # Calculate error (loss)
 error = calculate_loss(predictions, y_train)

 # Adjust parameters to reduce error
 gradients = compute_gradients(error)
 parameters = parameters - learning_rate * gradients

 # Repeat until error stops decreasing
```

## Common Machine Learning Algorithms

The algorithms below are those most often encountered in public health AI. Each entry covers how it works, strengths and weaknesses, when to use it, and a practical example.

### 1. Logistic Regression: Your Old Friend

**You already know this one!** [Logistic regression](https://doi.org/10.1111/j.2517-6161.1958.tb00292.x) predicts binary outcomes (disease/no disease, outbreak/no outbreak).

**When to use it:**

- Binary classification problems
- You want interpretable coefficients (odds ratios)
- You have modest amounts of data
- Linear relationships are reasonable

**Strengths:**

- Interpretable (you can explain to stakeholders)
- Fast to train
- Works well with small data
- Provides probability estimates
- Epidemiologists understand it intuitively

**Weaknesses:**

- Assumes linear relationships (in log-odds space)
- Cannot capture complex interactions automatically
- Performance limited on very complex patterns

Python: Logistic Regression

Show code

``` sourceCode
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import classification_report
import pandas as pd
import numpy as np

# Load outbreak data
data = pd.read_csv('../data/examples/dengue_outbreaks.csv')

# Features and label
X = data[['temperature', 'rainfall', 'prev_cases', 'population_density']]
y = data['outbreak'] # 0 or 1

# Train/test split
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(
 X, y, test_size=0.2, random_state=42
)

# Train model
model = LogisticRegression(max_iter=1000)
model.fit(X_train, y_train)

# Evaluate
y_pred = model.predict(X_test)
print(classification_report(y_test, y_pred))

# Interpret: Look at coefficients (like ORs in epi)
feature_names = X.columns
coefficients = model.coef_[0]

for feature, coef in zip(feature_names, coefficients):
 odds_ratio = np.exp(coef)
 print(f"{feature}: OR = {odds_ratio:.2f}")
```

**Output interpretation:**

    temperature: OR = 1.15 → Each 1°C increase → 15% higher outbreak odds
    rainfall: OR = 1.08  → Each 1mm increase → 8% higher outbreak odds
    prev_cases: OR = 1.25 → Each additional case → 25% higher outbreak odds

Start Here

Logistic regression should be your **default starting point** for classification problems. Only move to complex models if it does not work well enough.

Many applied prediction models in public health are well-specified logistic regressions with careful feature engineering.

Prediction vs. Inference: A Critical Mindset Shift

Regression coefficients are associational unless a causal interpretation is supported by a defensible identification strategy and its assumptions. Predictive model coefficients are likewise weights for prediction, not causal effects. A model might weight “time since last outbreak” heavily even when the feature is not a cause of outbreak occurrence. Multicollinearity can make coefficient estimates unstable and imprecise; it does not by itself determine whether causal identification is valid ([Hernán and Robins, 2020](https://www.hsph.harvard.edu/miguel-hernan/causal-inference-book/)).

**Key implications:**

- ML finds correlations, not causes. A model predicting hospital readmission identifies correlated factors, but changing those factors may not reduce readmissions.
- Confounding is not automatically addressed. ML may use confounders as predictive features rather than controlling for them.
- For causal questions (“Does X cause Y?”), you still need DAGs, propensity scores, instrumental variables, or randomized trials.

If you need to explain *why* something happens, use epidemiological methods. If you need to predict *what* will happen, ML often excels.

### 2. Decision Trees: Readable Rules

**The idea:** The algorithm builds a tree of yes/no questions to classify data, as introduced in [Breiman et al.’s seminal CART work](https://www.taylorfrancis.com/books/mono/10.1201/9781315139470/classification-regression-trees-leo-breiman-jerome-friedman-richard-olshen-charles-stone).

**Analogy:** A flowchart a doctor might use: “If fever \> 38°C AND cough present AND chest X-ray abnormal → Pneumonia likely”

**Visual example:**

         Fever > 38°C?
         /    \
         Yes    No
        /     \
      Cough present?   Low risk
       /  \
       Yes   No
       /    \
     Chest X-ray  Moderate risk
     abnormal?
     /  \
     Yes  No
     /   \
    Pneumonia Viral infection

Python: Decision Trees

Show code

``` sourceCode
from sklearn.tree import DecisionTreeClassifier
from sklearn import tree
import matplotlib.pyplot as plt

# Train decision tree
model = DecisionTreeClassifier(max_depth=3, random_state=42)
model.fit(X_train, y_train)

# Visualize the tree
plt.figure(figsize=(20,10))
tree.plot_tree(model,
    feature_names=X.columns,
    class_names=['No outbreak', 'Outbreak'],
    filled=True,
    fontsize=10)
plt.savefig('../images/examples/decision_tree.png', dpi=300, bbox_inches='tight')
plt.show()

# Make predictions
predictions = model.predict(X_test)
probabilities = model.predict_proba(X_test)
```

**Strengths:**

- Highly interpretable (you can draw the exact decision process)
- Handles non-linear relationships automatically
- No need to normalize features
- Works with mixed data types (numerical + categorical)
- Can capture interactions between features

**Weaknesses:**

- Prone to overfitting (memorizing training data)
- Unstable (small data changes → very different trees)
- Often less accurate than ensemble methods

Single trees vs. Forests

Single decision trees are rarely used in production because they overfit easily. Instead, we use **ensembles** of many trees ([Random Forests](https://doi.org/10.1023/A:1010933404324), [Gradient Boosting](https://doi.org/10.1214/aos/1013203451)), see next sections.

But single trees are excellent for **exploratory analysis** and **communicating findings** to non-technical stakeholders.

### 3. Random Forests: Democracy of Trees

**The idea:** Instead of one decision tree, train hundreds or thousands of trees on slightly different subsets of data. Each tree “votes” on the final prediction. This [ensemble method introduced by Breiman (2001)](https://doi.org/10.1023/A:1010933404324) has become one of the most widely used algorithms in machine learning.

**Why it works:** Individual trees overfit in different ways, and averaging their predictions reduces variance.

**Analogy:** Instead of asking one doctor, you ask 500 doctors and take the majority opinion.

Python: Random Forests

Show code

``` sourceCode
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import roc_auc_score, confusion_matrix
import numpy as np

# Train random forest
model = RandomForestClassifier(
 n_estimators=500,  # Number of trees
 max_depth=10,   # Limit tree depth (prevent overfitting)
 min_samples_split=20, # Require at least 20 samples to split
 random_state=42
)

model.fit(X_train, y_train)

# Predict probabilities (not just 0/1)
y_pred_proba = model.predict_proba(X_test)[:, 1]

# Evaluate with ROC-AUC
auc = roc_auc_score(y_test, y_pred_proba)
print(f"ROC-AUC: {auc:.3f}")

# Feature importance: Which features matter most?
importances = model.feature_importances_
feature_importance_df = pd.DataFrame({
 'feature': X.columns,
 'importance': importances
}).sort_values('importance', ascending=False)

print("\nFeature Importance:")
print(feature_importance_df)

# Plot with handbook styling
import sys
sys.path.append('..')
from styles.plot_config import set_handbook_style, HANDBOOK_COLORS

set_handbook_style()
import seaborn as sns

plt.figure(figsize=(10, 6))
sns.barplot(data=feature_importance_df, x='importance', y='feature',
   color=HANDBOOK_COLORS['primary_blue'])
plt.title('Feature Importance in Outbreak Prediction')
plt.xlabel('Importance Score')
plt.tight_layout()
plt.savefig('../images/examples/feature_importance.png', dpi=300, bbox_inches='tight')
```

**Strengths:**

- Often accurate across many problem types
- Handles thousands of features without feature selection
- Less prone to overfitting than single trees
- Provides feature importance scores
- No need for feature scaling
- Works out-of-the-box with minimal tuning

**Weaknesses:**

- Less interpretable than single trees (500 trees is hard to explain)
- Slower to train and predict than simple models
- Large file sizes (saving 500 trees takes space)
- Can struggle with highly imbalanced data

Practical Advice

Random Forests are often the **best first “real” ML model** to try after logistic regression. They’re:

- Forgiving of mistakes in data preparation
- Robust to outliers
- Accurate enough for many applications
- Easy to use with [scikit-learn](https://scikit-learn.org/stable/modules/generated/sklearn.ensemble.RandomForestClassifier.html)

For many public health prediction tasks, a well-tuned Random Forest is sufficient.

### 4. Gradient Boosting: A Strong Tabular Benchmark

**The idea:** Build trees sequentially, where each new tree focuses on correcting the mistakes of previous trees. This approach was formalized by [Friedman (2001)](https://doi.org/10.1214/aos/1013203451).

**Analogy:** Instead of 500 doctors voting independently (Random Forest), you have a team of 500 doctors where each successive doctor specifically tries to fix the previous doctor’s misdiagnoses.

**Popular implementations:**

- [XGBoost](https://doi.org/10.1145/2939672.2939785) (widely used)
- [LightGBM](https://papers.nips.cc/paper/2017/hash/6449f44a102fde848669bdd9eb6b76fa-Abstract.html) (faster, good for large data)
- [CatBoost](https://arxiv.org/abs/1706.09516) (handles categorical features well)

Python: Gradient Boosting (XGBoost)

Show code

``` sourceCode
from xgboost import XGBClassifier
from sklearn.model_selection import cross_val_score

# Train XGBoost model
model = XGBClassifier(
 n_estimators=500,
 learning_rate=0.05, # How much each tree contributes
 max_depth=6,
 subsample=0.8,   # Use 80% of data for each tree
 colsample_bytree=0.8, # Use 80% of features for each tree
 random_state=42
)

model.fit(X_train, y_train)

# Cross-validation for robust performance estimate
cv_scores = cross_val_score(model, X_train, y_train,
        cv=5, scoring='roc_auc')
print(f"Cross-validated AUC: {cv_scores.mean():.3f} (+/- {cv_scores.std():.3f})")

# Test set performance
y_pred_proba = model.predict_proba(X_test)[:, 1]
test_auc = roc_auc_score(y_test, y_pred_proba)
print(f"Test AUC: {test_auc:.3f}")

# Feature importance (SHAP values for better interpretation)
import shap
explainer = shap.TreeExplainer(model)
shap_values = explainer.shap_values(X_test)

# Visualize what drives predictions
shap.summary_plot(shap_values, X_test, feature_names=X.columns)
```

**Strengths:**

- Often a strong benchmark for tabular prediction
- Outperforms neural networks on average in some tabular benchmarks, but not universally ([Shwartz-Ziv & Armon, 2022, *Information Fusion*](https://doi.org/10.1016/j.inffus.2021.11.011); [Grinsztajn et al., 2022, *NeurIPS*](https://proceedings.neurips.cc/paper_files/paper/2022/hash/0378c7692da36807bdec87ab043cdadc-Abstract-Datasets_and_Benchmarks.html))
- Handles missing data automatically
- Built-in regularization reduces overfitting
- Excellent with tabular data (most public health data)

**Weaknesses:**

- More hyperparameters to tune than Random Forests
- Easier to overfit if not careful
- Requires more computational resources
- Harder to interpret than a single tree ([SHAP values](https://proceedings.neurips.cc/paper/2017/hash/8a20a8621978632d76c43dfd28b67767-Abstract.html) help explain individual predictions)

When to Use Gradient Boosting

Use gradient boosting when:

- You have tried Random Forests and need better performance
- Cross-validation or an external test shows a decision-relevant gain over simpler baselines
- Prediction accuracy is critical
- You have time/resources for hyperparameter tuning

Stick with Random Forests when:

- You want simplicity and fast iteration
- It validates better for the available data and intended population
- Interpretability is paramount

### 5. Neural Networks and Deep Learning

**The idea:** Layers of interconnected “neurons” that transform inputs into outputs through learned weights. Neural networks are [universal approximators](https://doi.org/10.1016/0893-6080(89)90020-8), meaning they can theoretically learn any function given enough data and capacity.

**Simplified structure:**

    Input Layer → Hidden Layer(s) → Output Layer
     ↓    ↓     ↓
    [Features] [Learned  [Predictions]
        representations]

Each connection has a “weight” that’s adjusted during training using [backpropagation](https://doi.org/10.1038/323533a0).

**When neural networks shine:**

- Large datasets (millions of examples)
- Complex patterns (images, text, audio)
- Representation learning (automatic feature extraction)

**When they struggle:**

- Datasets too small or unrepresentative for the selected architecture
- Tabular data, where trees often perform better on average in benchmark comparisons ([Shwartz-Ziv & Armon, 2022, *Information Fusion*](https://doi.org/10.1016/j.inffus.2021.11.011))
- Interpretability is required

Python: Neural Networks

Show code

``` sourceCode
from sklearn.neural_network import MLPClassifier
from sklearn.preprocessing import StandardScaler

# Neural networks need scaled features
scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled = scaler.transform(X_test)

# Build neural network
# (100, 50) means:
# - First hidden layer: 100 neurons
# - Second hidden layer: 50 neurons
model = MLPClassifier(
 hidden_layer_sizes=(100, 50),
 activation='relu',  # Activation function
 max_iter=500,
 random_state=42,
 early_stopping=True,  # Stop if validation performance plateaus
 validation_fraction=0.1
)

model.fit(X_train_scaled, y_train)

# Predict
y_pred = model.predict(X_test_scaled)
y_pred_proba = model.predict_proba(X_test_scaled)[:, 1]

# Evaluate
from sklearn.metrics import classification_report
print(classification_report(y_test, y_pred))
```

Reality Check: Neural Networks for Tabular Data

For many medium-sized public health **tabular datasets** (spreadsheets with rows and columns), gradient-boosted trees are a strong benchmark, but performance depends on the dataset, representation, validation design, and tuning ([Grinsztajn et al., 2022, *NeurIPS*](https://proceedings.neurips.cc/paper_files/paper/2022/hash/0378c7692da36807bdec87ab043cdadc-Abstract-Datasets_and_Benchmarks.html)).

Neural networks excel at:

- Medical imaging (chest X-rays, histopathology)
- Time series with complex temporal patterns
- Natural language processing
- Multi-modal data (combining images + text + numbers)

For structured-data prediction, compare a tree-based method with an interpretable baseline before considering more complex models.

### Deep Learning Architectures for Public Health

**Deep learning** = neural networks with many layers (10s to 100s of layers), as comprehensively covered in [Goodfellow et al.’s textbook](https://www.deeplearningbook.org/).

**Key architectures relevant to public health:**

#### Convolutional Neural Networks (CNNs)

- **Purpose:** Image analysis
- **Applications:** Medical imaging (X-rays, CT scans, pathology slides), [skin lesion classification](https://doi.org/10.1038/nature21056)
- **How they work:** Learn spatial hierarchies (edges → textures → organs → diagnoses)

Python: CNNs for Medical Imaging

Show code

``` sourceCode
# Example: Chest X-ray pneumonia detection with CNN
from tensorflow.keras.applications import ResNet50
from tensorflow.keras.layers import Dense, GlobalAveragePooling2D
from tensorflow.keras.models import Model

# Load pre-trained ResNet50 (transfer learning)
base_model = ResNet50(weights='imagenet', include_top=False,
      input_shape=(224, 224, 3))

# Add custom classification layers
x = base_model.output
x = GlobalAveragePooling2D()(x)
x = Dense(256, activation='relu')(x)
predictions = Dense(1, activation='sigmoid')(x) # Binary: pneumonia or not

model = Model(inputs=base_model.input, outputs=predictions)

# Freeze pre-trained layers, train only new layers
for layer in base_model.layers:
 layer.trainable = False

model.compile(optimizer='adam', loss='binary_crossentropy',
    metrics=['accuracy', 'AUC'])

# Train on chest X-ray dataset
# model.fit(train_images, train_labels, epochs=10, validation_split=0.2)
```

**Key concept: Transfer Learning** Instead of training from scratch, start with a model pre-trained on millions of images ([ImageNet](https://www.image-net.org/)), then fine-tune it on your medical images. This [transfer learning approach](https://doi.org/10.1109/CVPR.2014.81) works even with small datasets (1,000-10,000 images).

#### Recurrent Neural Networks (RNNs) and LSTMs

- **Purpose:** Sequential data (time series, text)
- **Applications:** Epidemic forecasting, patient trajectory prediction, clinical note analysis
- **How they work:** “Remember” previous time steps when processing current time step using [LSTM architectures](https://doi.org/10.1162/neco.1997.9.8.1735)

Python: RNNs for Time Series

Show code

``` sourceCode
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import LSTM, Dense, Dropout

# Example: Flu case forecasting
model = Sequential([
 LSTM(50, return_sequences=True, input_shape=(timesteps, features)),
 Dropout(0.2),
 LSTM(50, return_sequences=False),
 Dropout(0.2),
 Dense(1) # Predict next week's case count
])

model.compile(optimizer='adam', loss='mse')
# model.fit(X_train, y_train, epochs=50, batch_size=32)
```

#### Transformers and Large Language Models

- **Purpose:** Natural language understanding
- **Applications:** Clinical note extraction, literature review, patient Q&A, surveillance
- **Key models:** [BERT](https://aclanthology.org/N19-1423/), frontier LLMs (GPT series, Claude, Gemini), and domain-specific variants like [Bio_ClinicalBERT](https://aclanthology.org/W19-1909/) and [PubMedBERT](https://doi.org/10.1145/3458754)

LLMs are covered in [Large Language Models in Public Health: Theory and Practice](../future/llm-theory-practice.html).

Deep Learning in Practice

**In practice:** Practitioners rarely need to build deep learning models from scratch. Instead:

1.  **Use pre-trained models** (transfer learning)
2.  **Use existing libraries:** [TensorFlow](https://www.tensorflow.org/), [PyTorch](https://pytorch.org/), [Hugging Face](https://huggingface.co/)
3.  **Start with tutorials:** [Fast.ai](https://www.fast.ai/), [DeepLearning.AI](https://www.deeplearning.ai/)

For most public health applications, **fine-tuning existing models** is more practical than training from scratch.

## Quick Algorithm Selection Guide

Use this decision tree to choose algorithms:

    Do you have labeled data?
     └─ No → Unsupervised learning (clustering, anomaly detection)
     └─ Yes → Continue...

    What type of data?
     └─ Images  → CNNs (ResNet, EfficientNet)
     └─ Text   → Transformers (BERT, GPT)
     └─ Time series → LSTMs, Transformers, or gradient boosting
     └─ Tabular  → Continue...

    How much data?
     └─ < 1,000 rows  → Logistic regression, single decision tree
     └─ 1,000-10,000  → Random Forest
     └─ > 10,000   → Gradient boosting (XGBoost)
     └─ > 100,000  → Gradient boosting; add neural networks only if validation favors them

    Do you need interpretability?
     └─ Critical → Logistic regression or single decision tree
     └─ Nice  → Random Forest + SHAP values
     └─ Less important → Gradient boosting or neural networks

## Evaluation Metrics: Measuring Success

A trained model needs evaluation with metrics matched to its intended use.

### For Classification (Disease/No Disease, Outbreak/No Outbreak)

#### 1. Confusion Matrix

The foundation of classification evaluation:

|                        | **Predicted: Disease** | **Predicted: No Disease** |
|------------------------|------------------------|---------------------------|
| **Actual: Disease**    | True Positive (TP)     | False Negative (FN)       |
| **Actual: No Disease** | False Positive (FP)    | True Negative (TN)        |

From this, we derive all other metrics.

#### 2. Accuracy

\\\text{Accuracy} = \frac{TP + TN}{TP + TN + FP + FN}\\

**When it’s misleading:** Imbalanced data

Example: If only 1% of patients have disease, a model that predicts “No disease” for everyone gets 99% accuracy but detects no cases.

#### 3. Sensitivity (Recall, True Positive Rate)

\\\text{Sensitivity} = \frac{TP}{TP + FN}\\

“Of all people with disease, what fraction did we detect?”

**Critical when:** Missing cases is dangerous (e.g., cancer screening)

#### 4. Specificity (True Negative Rate)

\\\text{Specificity} = \frac{TN}{TN + FP}\\

“Of all healthy people, what fraction did we correctly identify?”

**Critical when:** False alarms are costly or harmful

#### 5. Positive Predictive Value (Precision)

\\\text{PPV} = \frac{TP}{TP + FP}\\

“Of all positive predictions, how many are correct?”

**Critical when:** You act on positive predictions (e.g., administering expensive treatment)

#### 6. F1 Score

\\F1 = 2 \times \frac{\text{Precision} \times \text{Recall}}{\text{Precision} + \text{Recall}}\\

Harmonic mean of precision and recall, [introduced by van Rijsbergen (1979)](https://www.dcs.gla.ac.uk/Keith/Preface.html) in information retrieval. Useful when you need a single metric balancing both.

#### 7. ROC-AUC (Area Under the Receiver Operating Characteristic Curve)

ROC-AUC summarizes discrimination across classification thresholds and was introduced in [signal detection theory](https://doi.org/10.1126/science.134.3473.168).

- Plots True Positive Rate vs. False Positive Rate at all threshold values
- AUC = 0.5: Random guessing
- AUC = 1.0: Perfect classifier
- Values farther above 0.5 indicate better ranking on the evaluated population, but no universal AUC threshold establishes clinical utility.

Report calibration, uncertainty, threshold-specific sensitivity, specificity, predictive values, and net benefit for the intended use ([Steyerberg et al., 2010](https://doi.org/10.1097/EDE.0b013e3181c30fb2); [Sadatsafavi et al., 2021](https://doi.org/10.1183/13993003.01186-2021)).

Python: ROC-AUC Visualization

Show code

``` sourceCode
from sklearn.metrics import roc_curve, auc, RocCurveDisplay
import matplotlib.pyplot as plt
import sys
sys.path.append('..')
from styles.plot_config import set_handbook_style, HANDBOOK_COLORS

set_handbook_style()

# Get predicted probabilities
y_pred_proba = model.predict_proba(X_test)[:, 1]

# Calculate ROC curve
fpr, tpr, thresholds = roc_curve(y_test, y_pred_proba)
roc_auc = auc(fpr, tpr)

# Plot with handbook colors
fig, ax = plt.subplots(figsize=(8, 6))
ax.plot(fpr, tpr, color=HANDBOOK_COLORS['primary_blue'], lw=2, label=f'ROC curve (AUC = {roc_auc:.2f})')
ax.plot([0, 1], [0, 1], color=HANDBOOK_COLORS['mid_gray'], linestyle='--', lw=1.5, label='Random Chance')
ax.set_xlim([0.0, 1.0])
ax.set_ylim([0.0, 1.05])
ax.set_xlabel('False Positive Rate')
ax.set_ylabel('True Positive Rate')
ax.set_title(f'ROC Curve (AUC = {roc_auc:.3f})')
ax.legend(loc="lower right")
ax.grid(True, alpha=0.3)
plt.tight_layout()
plt.savefig('../images/examples/roc_curve.png', dpi=300, bbox_inches='tight')
```

Choosing the Right Metric

**No single metric tells the whole story**. The right metric depends on your use case:

| Scenario | Primary Metric | Why |
|----|----|----|
| Disease screening | Sensitivity and downstream harms | Missed cases and false-positive follow-up both matter |
| Confirmatory testing | Specificity, PPV, and downstream harms | False positives can trigger costly or harmful action |
| Balanced classes | F1, Accuracy | Both errors equally important |
| Imbalanced data | ROC-AUC, PR-AUC | Accuracy is misleading |
| Rare events (\<5%) | Precision-Recall AUC | ROC-AUC can be overoptimistic |

**Always report the confusion matrix** so readers can calculate their preferred metric.

#### 8. Calibration: When Probabilities Must Be Accurate

A model can have excellent discrimination (high AUC) but **poorly calibrated probabilities**. If your model outputs “70% probability of readmission,” patients with that score should actually be readmitted about 70% of the time.

**Why calibration matters in public health:**

- **Clinical decision support**: When probability thresholds trigger interventions (e.g., “if risk \> 50%, refer to specialist”), the probabilities must be accurate
- **Cost-benefit analyses**: Require accurate probability estimates, not just good ranking
- **Communicating risk**: Telling a patient “you have 80% risk” is only meaningful if 80% is calibrated

**How to check calibration:**

- **Reliability diagrams** (calibration curves): Plot predicted probabilities vs. observed frequencies. A perfectly calibrated model follows the 45-degree line.
- **Brier score**: A proper score of probabilistic accuracy that can be decomposed into reliability, resolution, and uncertainty; lower is better

A Common Mistake

Many ML practitioners optimize only for AUC and ignore calibration. A model with AUC = 0.90 but poor calibration may be useless for clinical decision-making where you need to trust the probability values, not just the ranking.

For clinical applications, always check calibration using reliability diagrams. See [Steyerberg et al. (2010)](https://doi.org/10.1097/EDE.0b013e3181c30fb2) for calibration assessment in clinical prediction models.

### For Regression (Predicting Continuous Values)

#### 1. Mean Absolute Error (MAE)

\\MAE = \frac{1}{n}\sum \|y\_{\text{true}} - y\_{\text{pred}}\|\\

Average absolute difference. Easy to interpret (same units as target).

#### 2. Root Mean Squared Error (RMSE)

\\RMSE = \sqrt{\frac{1}{n}\sum (y\_{\text{true}} - y\_{\text{pred}})^2}\\

Penalizes large errors more than MAE. More sensitive to outliers.

#### 3. R² (Coefficient of Determination)

\\R^2 = 1 - \frac{\sum(y\_{\text{true}} - y\_{\text{pred}})^2}{\sum(y\_{\text{true}} - \bar{y})^2}\\

- R² = 1: Perfect predictions
- R² = 0: Model no better than predicting mean
- R² \< 0: Model worse than predicting mean

**Code example:**

Show code

``` sourceCode
from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score
import numpy as np

# Predict continuous outcome (e.g., number of cases next week)
y_pred = model.predict(X_test)

# Calculate metrics
mae = mean_absolute_error(y_test, y_pred)
rmse = np.sqrt(mean_squared_error(y_test, y_pred))
r2 = r2_score(y_test, y_pred)

print(f"MAE: {mae:.2f}")
print(f"RMSE: {rmse:.2f}")
print(f"R²: {r2:.3f}")

# Visualize predictions vs. actual with handbook styling
import sys
sys.path.append('..')
from styles.plot_config import set_handbook_style, HANDBOOK_COLORS

set_handbook_style()

plt.figure(figsize=(8, 6))
plt.scatter(y_test, y_pred, alpha=0.6, color=HANDBOOK_COLORS['primary_blue'],
   edgecolors=HANDBOOK_COLORS['dark_gray'], linewidth=0.5, s=50)
plt.plot([y_test.min(), y_test.max()],
   [y_test.min(), y_test.max()],
   color=HANDBOOK_COLORS['secondary_coral'], linestyle='--', lw=2, label='Perfect Prediction')
plt.xlabel('Actual Values')
plt.ylabel('Predicted Values')
plt.title('Predictions vs. Actual')
plt.legend()
plt.tight_layout()
plt.savefig('../images/examples/regression_performance.png', dpi=300, bbox_inches='tight')
```

## Overfitting and Underfitting: The Bias-Variance Tradeoff

### The Central Challenge

This fundamental concept, formalized in [Geman et al.’s seminal paper](https://doi.org/10.1162/neco.1992.4.1.1), represents the core challenge of machine learning.

**Underfitting (High Bias):** Model is too simple. Fails to capture patterns even in training data.

**Overfitting (High Variance):** Model is too complex. Memorizes training data perfectly but fails on new data.

**The Goal:** Find the sweet spot, a model complex enough to capture true patterns but not so complex it memorizes noise.

**Visual intuition:**

    Underfitting:  Just Right:   Overfitting:

     • • •   • • •    • • •
     • ── •   • ~~~ •   • │ •
     •  •   •  •   • │ •
    •   •  •   •   •  │ •
     (Line)   (Smooth curve)  (Zigzag through
               every point)

![Three scatter plots showing regression fits: left plot shows linear underfit with high bias, center shows appropriate polynomial fit, right shows severe overfit with high variance passing through all training points](../images/chapter02/overfitting-underfitting.png)

Figure 5.1: Visualization of underfitting vs. overfitting. The green line (left) represents an underfit model that’s too simple to capture the data pattern. The black line (center) shows a well-fit model that generalizes appropriately. The blue curve (right) shows an overfit model that memorizes training data noise and will not generalize. Source: Wikimedia Commons (Public Domain)

### How to Detect Overfitting

Show code

``` sourceCode
# Compare training vs. test performance
train_accuracy = model.score(X_train, y_train)
test_accuracy = model.score(X_test, y_test)

print(f"Training accuracy: {train_accuracy:.3f}")
print(f"Test accuracy:  {test_accuracy:.3f}")
print(f"Difference:  {train_accuracy - test_accuracy:.3f}")
```

**Red flags:**

- Training accuracy = 0.95, Test accuracy = 0.65 → **Overfitting**
- Training accuracy = 0.60, Test accuracy = 0.58 → **Underfitting** (both low)
- Training accuracy = 0.82, Test accuracy = 0.80 → **Just right** (close and good)

### How to Prevent Overfitting

1.  **More data** (the best solution, if possible)
2.  **Regularization** (penalize model complexity using [L1/L2 penalties](https://doi.org/10.1198/016214501753382273))
3.  **Cross-validation** (validate on multiple splits)
4.  **Simpler model** (fewer features, less depth)
5.  **Early stopping** (stop training before overfitting starts)
6.  **Ensemble methods** (average multiple models)

**Example with regularization:**

Show code

``` sourceCode
from sklearn.linear_model import LogisticRegressionCV

# CV suffix = automatic cross-validation for hyperparameter tuning
model = LogisticRegressionCV(
 Cs=10,    # Try 10 different regularization strengths
 cv=5,    # 5-fold cross-validation
 scoring='roc_auc',
 random_state=42
)

model.fit(X_train, y_train)

# Best regularization parameter found automatically
print(f"Best C (regularization): {model.C_[0]:.4f}")
```

## Common Pitfalls and How to Avoid Them

### 1. Data Leakage

**The problem:** Test data “leaks” into training, inflating performance estimates.

[Kaufman et al.](https://doi.org/10.1145/2382577.2382579) note that leakage has been deemed one of the top ten data mining mistakes.

**Example mistake:**

Show code

``` sourceCode
# BAD: Normalize before splitting
from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X) # Uses ALL data including test!
X_train, X_test = train_test_split(X_scaled, test_size=0.2)
```

**Correct approach:**

Show code

``` sourceCode
# GOOD: Split first, then normalize
X_train, X_test = train_test_split(X, test_size=0.2)
scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train) # Fit on train only
X_test_scaled = scaler.transform(X_test)  # Apply to test
```

### 2. Ignoring Class Imbalance

**The problem:** When one class is rare (e.g., 1% outbreak rate), models can get high accuracy by always predicting the majority class.

**Solutions:**

Show code

``` sourceCode
# Option 1: Use class_weight parameter
model = RandomForestClassifier(class_weight='balanced')

# Option 2: Use appropriate evaluation metrics (F1, ROC-AUC, not accuracy)

# Option 3: Resample data using SMOTE (Chawla et al., 2002)
from imblearn.over_sampling import SMOTE
smote = SMOTE(random_state=42)
X_train_balanced, y_train_balanced = smote.fit_resample(X_train, y_train)
```

See [Chawla et al. (2002)](https://doi.org/10.1613/jair.953) for the original SMOTE paper.

### 3. Not Using Cross-Validation

**The problem:** Single train/test split might be lucky or unlucky. [Cross-validation](https://doi.org/10.1111/j.2517-6161.1974.tb00994.x), introduced by Stone (1974), provides more robust performance estimates.

**Solution:**

Show code

``` sourceCode
from sklearn.model_selection import cross_val_score

# 5-fold cross-validation
cv_scores = cross_val_score(model, X_train, y_train,
        cv=5, scoring='roc_auc')
print(f"CV AUC: {cv_scores.mean():.3f} (+/- {cv_scores.std():.3f})")
```

### 4. Ignoring Temporal Ordering

**The problem:** In time series, future information leaks into past predictions.

**Wrong:**

Show code

``` sourceCode
# Random split destroys temporal order
X_train, X_test = train_test_split(X, test_size=0.2) # BAD for time series
```

**Correct:**

Show code

``` sourceCode
# Respect temporal order
split_point = int(0.8 * len(df))
train_df = df[:split_point]
test_df = df[split_point:]

X_train, y_train = train_df[features], train_df['outcome']
X_test, y_test = test_df[features], test_df['outcome']
```

## Questions to Ask Vendors and Data Scientists

When evaluating AI systems or working with technical teams, use these questions to assess model quality:

Essential Questions Checklist

**Performance Validation:**

1.  Is there material optimism between training and test performance across repeated validation, with uncertainty reported? No fixed percentage defines overfitting.
2.  How was the data split? (Random vs. temporal, patient-level vs. record-level)
3.  What evaluation metrics were used beyond accuracy? (Request sensitivity, specificity, ROC-AUC, confusion matrix)
4.  Was the model validated on external data from a different population or time period?

**Data and Generalizability:**

5.  What population was the training data drawn from? Will it generalize to our setting?
6.  How old is the training data? Has anything changed since then?
7.  What is the class balance in training data vs. our population?
8.  How are missing values handled?

**Interpretability and Trust:**

9.  Can you explain what features drive the model’s predictions?
10. How will clinicians/staff know when to trust or override the model?
11. What is the plan for monitoring performance after deployment?
12. How will the model be updated as conditions change?

**Operational Readiness:**

13. What monitoring is in place for performance degradation after deployment?
14. How quickly will we know if the model starts failing?
15. What’s the rollback procedure if performance drops?
16. What triggers model retraining? Scheduled or performance-based?

**Reproducibility:**

17. Can you provide the exact training code and random seeds?
18. What versions of libraries were used?
19. Is the training data archived and accessible for audit?

**Red Flags to Watch For:**

- Vendor only shows ROC-AUC without confusion matrix (may hide poor sensitivity/specificity)
- No external validation (model may not generalize)
- Training data demographics do not match your population
- No plan for ongoing monitoring or model updates
- Claims of \>95% accuracy on imbalanced outcomes (likely misleading)
- Cannot explain what features drive predictions
- No documentation of preprocessing steps

For detailed deployment monitoring guidance, see [AI Deployment in Healthcare](../implementation/deployment.html).

## Key Takeaways

1.  **Start simple:** Logistic regression → Random Forest → Gradient Boosting → Deep Learning. Do not skip steps.

2.  **Domain and technical expertise are complementary:** Domain knowledge guides feature definition and validity; comparative validation determines whether a model family adds value.

3.  **Evaluation is multi-dimensional:** No single metric tells the whole story. Report confusion matrix, ROC-AUC, and metrics relevant to your use case.

4.  **Overfitting is the enemy:** Always validate on held-out test data. Use cross-validation. Be skeptical of “too good” results.

5.  **Interpretability matters:** In public health, stakeholders need to understand and trust models. Use SHAP values, feature importance, and simple models when possible.

6.  **AI is pattern recognition from data:** Output quality depends on input quality, and domain knowledge remains essential.

7.  **Most problems do not require deep learning:** For tabular data, compare interpretable baselines with tree ensembles and justify added complexity from validation evidence.

## Recommended Learning Path

### Beginner (You are here)

- This chapter
- [Scikit-learn tutorials](https://scikit-learn.org/1.4/tutorial/index.html)
- [Kaggle Learn: Intro to ML](https://www.kaggle.com/learn/intro-to-machine-learning)

### Intermediate

- [Hands-On Machine Learning](https://www.oreilly.com/library/view/hands-on-machine-learning/9781492032632/) by Aurélien Géron
- [Introduction to Statistical Learning](https://www.statlearning.com/) by James et al. (free PDF)
- [Andrew Ng’s ML Specialization](https://www.coursera.org/specializations/machine-learning-introduction)

### Advanced (When you need deep learning)

- [Deep Learning](https://www.deeplearningbook.org/) by Goodfellow et al.
- [Dive into Deep Learning](https://d2l.ai/) (interactive book)
- [Fast.ai Practical Deep Learning](https://course.fast.ai/)
- [Stanford CS229: Machine Learning](https://cs229.stanford.edu/)

### Public Health Specific

- [Big Data and Machine Learning in Health Care](https://doi.org/10.1001/jama.2017.18391) (JAMA review)
- [Machine Learning in Epidemiology and Health Outcomes Research](https://doi.org/10.1146/annurev-publhealth-040119-094437) (*Annual Review of Public Health*)
- [Healthcare AI Resources](https://github.com/medtorch/awesome-healthcare-ai)

## Practice Exercises

### Exercise 1: Your First Classifier

Using the outbreak detection code patterns above:

1.  Modify features (try removing or adding features)
2.  Try different algorithms (logistic regression, decision tree)
3.  Compare performance: which works best, and why?

### Exercise 2: Handle Imbalance

Create a dataset where outbreaks are only 2% of weeks:

1.  Train a model without addressing imbalance
2.  Train with `class_weight='balanced'`
3.  Compare using F1 score and ROC-AUC

### Exercise 3: Interpret Predictions

Pick one misclassified test example:

1.  What features contributed to the wrong prediction?
2.  Use SHAP values to visualize
3.  Could a human have made the same mistake?

## Check Your Understanding

Test your knowledge of machine learning fundamentals and their applications in public health. Each question builds on the key concepts from this chapter.

Question 1

You’re building a model to predict dengue outbreaks using historical data with known outbreak labels (yes/no). You have temperature, rainfall, and previous case counts as features. Which machine learning paradigm should you use?

1.  Unsupervised learning, because weather patterns are complex
2.  Supervised learning, because you have labeled historical outbreak data
3.  Reinforcement learning, because outbreak prediction requires sequential decision-making
4.  Deep learning, because outbreak prediction is a complex task

**Correct Answer: b) Supervised learning, because you have labeled historical outbreak data**

This is a classic supervised learning problem because:

- You have **labeled data**: Historical weeks with known outbreak outcomes (yes/no)
- You have **features**: Temperature, rainfall, previous case counts
- You want to **predict a specific outcome**: Whether an outbreak will occur

The three fundamental paradigms are distinguished by:

1.  **Supervised learning**: You have labeled examples (inputs + correct outputs), and you want to predict outcomes for new data
2.  **Unsupervised learning**: You have unlabeled data and want to discover patterns or structure (clustering, anomaly detection)
3.  **Reinforcement learning**: You’re optimizing sequential decisions through trial and error with rewards/penalties

Common supervised learning applications in public health include:

- Disease diagnosis from symptoms or images
- Outbreak prediction from surveillance data
- Risk stratification for high-risk patients
- Hospital readmission prediction

For this dengue outbreak problem, you’d likely start with logistic regression (binary classification), then try Random Forests or gradient boosting if you need better performance.

Question 2

You’ve trained a model to predict hospital readmissions. Training accuracy is 95%, but test accuracy is only 68%. What is the most likely problem, and what should you do?

1.  Underfitting: use a more complex model with more parameters
2.  Overfitting: the model memorized training data and does not generalize well
3.  Data leakage: information from the test set leaked into training
4.  Class imbalance: readmissions are rare events

**Correct Answer: b) Overfitting: the model memorized training data and does not generalize well**

The large gap between training (95%) and test (68%) accuracy is a classic sign of **overfitting**. The model is too complex and has essentially memorized the training data, including its noise and quirks, rather than learning generalizable patterns.

**Why overfitting happened:**

- Model is too complex (too many parameters, too deep trees)
- Too little training data for the model’s complexity
- Insufficient regularization
- Training for too many iterations

**How to fix overfitting:**

1.  **Use regularization**: Add L1/L2 penalties to constrain model complexity
2.  **Simplify the model**: Use fewer features, shallower trees, or simpler algorithms
3.  **Get more data**: The best solution if possible
4.  **Use cross-validation**: Validate on multiple data splits to catch overfitting early
5.  **Early stopping**: Stop training before the model starts memorizing
6.  **Ensemble methods**: Average multiple models to reduce overfitting

**Why other answers are wrong:**

- **Underfitting** would show *both* training and test accuracy being low (e.g., 60% and 58%)
- **Data leakage** would make test performance *too good* (unrealistically high)
- **Class imbalance** could be a problem but would not explain the train/test gap

Question 3

For most public health tabular data (structured rows and columns with patient demographics, lab results, and outcomes), which approach typically performs BEST?

1.  Deep neural networks with many hidden layers
2.  Gradient boosting methods (XGBoost, LightGBM) or Random Forests
3.  Simple logistic regression with no feature engineering
4.  Convolutional neural networks (CNNs)

**Correct Answer: b) Gradient boosting methods (XGBoost, LightGBM) or Random Forests**

For **tabular data** (spreadsheet-style structured data), tree-based ensemble methods often outperform neural networks in benchmark comparisons. Here’s why:

**Advantages of gradient boosting/Random Forests for tabular data:**

- Naturally handle mixed data types (numerical + categorical)
- Do not require feature scaling or normalization
- Robust to outliers and missing data
- Automatic feature interaction detection
- Excellent performance with modest amounts of data (thousands to tens of thousands of rows)
- Provide interpretable feature importance scores

**When deep learning excels (NOT tabular data):**

- **Images**: CNNs for chest X-rays, pathology slides, skin lesions
- **Text**: Transformers/LLMs for clinical notes, literature, patient messages
- **Complex time series**: LSTMs for epidemic forecasting with long-term dependencies
- **Multimodal data**: Combining images + text + structured data

**Recommended approach for tabular public health data:**

1.  Start with **logistic regression** (interpretable baseline)
2.  Try **Random Forest** (forgiving, works well out-of-the-box)
3.  Compare **XGBoost/LightGBM** when validation suggests added complexity may help
4.  Only use neural networks if tree methods fail and you have massive amounts of data

For many medium-sized tabular benchmarks, gradient boosting performs strongly on average, but no model family wins universally.

Question 4

You’re evaluating a disease screening tool for a rare condition (1% prevalence). The model achieves 99% accuracy. Your colleague says “This is excellent! Let’s deploy it.” What’s the problem?

1.  There is no problem; 99% accuracy is excellent for any application
2.  Accuracy is misleading with imbalanced data; the model might just predict “no disease” for everyone
3.  99% is too high and suggests the model is overfitting
4.  Screening tools should prioritize specificity over accuracy

**Correct Answer: b) Accuracy is misleading with imbalanced data; the model might just predict “no disease” for everyone**

This is the **class imbalance problem**. With 1% disease prevalence, a completely useless model that predicts “no disease” for everyone would achieve **99% accuracy** while providing zero clinical value.

**Why accuracy fails:**

- Accuracy = (TP + TN) / (TP + TN + FP + FN)
- If the model predicts “no disease” for all 1,000 patients:
  - True Negatives (TN): 990 (correctly identified healthy)
  - False Negatives (FN): 10 (missed all disease cases)
  - Accuracy = 990/1000 = 99%
  - Sensitivity (recall) = 0/10 = **0%** (detected zero disease cases)

**What you should check instead:**

1.  **Confusion matrix**: See actual TP, TN, FP, FN counts
2.  **Sensitivity (recall)**: TP/(TP+FN), critical for screening (do not miss disease)
3.  **Specificity**: TN/(TN+FP), to avoid false alarms
4.  **Positive Predictive Value (PPV)**: TP/(TP+FP), the probability that a flagged person actually has disease
5.  **ROC-AUC**: Overall discriminative ability across all thresholds
6.  **F1 Score**: Balances precision and recall

**For disease screening**, sensitivity (detecting actual cases) is usually prioritized over specificity. You cannot afford to miss cases of a serious disease, even if it means some false positives that require follow-up testing.

**How to fix:**

- Use `class_weight='balanced'` in your model
- Use appropriate evaluation metrics (F1, ROC-AUC, not accuracy)
- Consider SMOTE or other resampling techniques

Question 5

A critical concept in machine learning is preventing “data leakage.” Which scenario represents data leakage that would invalidate your model evaluation?

1.  Using domain expertise to engineer new features before splitting train/test sets
2.  Normalizing features using statistics (mean, std) computed on the entire dataset before splitting into train/test sets
3.  Including demographic variables that might correlate with protected classes
4.  Training on data from 2020–2022 and testing on data from 2023

**Correct Answer: b) Normalizing features using statistics (mean, std) computed on the entire dataset before splitting into train/test sets**

This is a **classic data leakage mistake** that makes your model appear better than it really is.

**Why this is leakage:**

**WRONG approach:**

Show code

``` sourceCode
# Compute statistics using ALL data (including test!)
X_scaled = scaler.fit_transform(X)
X_train, X_test = train_test_split(X_scaled)
```

The test set’s mean and standard deviation influenced the scaling transformation. The model indirectly “saw” information from the test set during training.

**CORRECT approach:**

Show code

``` sourceCode
# Split FIRST, then normalize
X_train, X_test = train_test_split(X)
scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train) # Fit on train only
X_test_scaled = scaler.transform(X_test)  # Apply to test
```

**Other common data leakage scenarios:**

- Including future information in features (e.g., using next week’s data to predict this week)
- Using the same patients in both train and test sets
- Performing feature selection on the full dataset before splitting
- Cross-validation on time series without respecting temporal order

**Why other answers are NOT leakage:**

- **Feature engineering before splitting**: Fine, as long as you do not use test labels or test-specific statistics
- **Including demographic variables**: An ethical/fairness concern, not leakage
- **Time-based train/test split**: The correct approach for temporal data, because it avoids leakage

**The cardinal rule**: Test data must remain completely untouched until final evaluation. Any processing (scaling, feature selection, etc.) must be fit on training data only.

Question 6

You’re choosing between a Random Forest with 85% accuracy that you cannot easily explain, and logistic regression with 80% accuracy that provides interpretable odds ratios. For predicting which communities should receive limited outbreak response resources, which should you choose and why?

1.  Random Forest: 5 percentage points of added accuracy could save lives, and interpretability does not matter
2.  Logistic regression: interpretability is critical for stakeholder trust and accountability in resource allocation
3.  Deep learning: should always use the most sophisticated method available
4.  Either model is fine since they’re both above 80% accuracy

**Correct Answer: b) Logistic regression: interpretability is critical for stakeholder trust and accountability in resource allocation**

This question highlights a fundamental tension in applied machine learning: **accuracy vs. interpretability**. For public health applications, especially those involving resource allocation, interpretability often matters more than marginal accuracy gains.

**Why interpretability is critical here:**

1.  **Stakeholder trust**: Public health officials, community leaders, and the public need to understand *why* certain communities were prioritized. “The black-box algorithm said so” erodes trust.

2.  **Accountability**: If resources are misallocated, you need to explain what went wrong and fix it. With logistic regression, you can identify which factors (e.g., population density, previous outbreak rates) drove the decision.

3.  **Equity concerns**: Resource allocation decisions can perpetuate health inequities. Interpretable models let you audit for fairness: does the model discriminate based on race, income, or other protected attributes?

4.  **Domain validation**: Epidemiologists can review odds ratios and say “this makes biological sense” or “this is spurious.” That review is harder with a Random Forest.

5.  **Legal/regulatory**: Many jurisdictions require explainable decision-making for consequential decisions affecting people’s lives.

**When to prioritize accuracy over interpretability:**

- Medical imaging diagnosis (radiology AI supporting clinicians)
- Internal risk flagging (clinician reviews all flagged cases anyway)
- Non-consequential applications (exploratory analysis)

**Best practice approach:**

1.  Start with interpretable model (logistic regression)
2.  If accuracy is insufficient for clinical value, try more complex models
3.  Use SHAP values or LIME to interpret complex models
4.  Consider the **context**: resource allocation demands more interpretability than internal screening tools

**The 5-percentage-point accuracy gap must be weighed against:**

- Can you defend decisions to communities?
- Can you audit for bias?
- Can domain experts validate the logic?
- Will stakeholders trust and adopt the system?

For consequential public health decisions, the answer is usually: choose the interpretable model unless the accuracy gap is unacceptably large.

Frequently Asked Questions

### Which machine-learning algorithm should be used for public health tabular data?

Begin with an interpretable baseline and compare plausible model families under the same validation design. Gradient-boosted trees are often strong tabular benchmarks, but no algorithm consistently wins across datasets, representations, tuning, sample sizes, and deployment settings. Choose the simplest model that meets the decision-relevant performance, calibration, interpretability, equity, and maintenance requirements.

### Why can accuracy be misleading?

Accuracy can remain high when the outcome is rare even if the model identifies few true cases. It also hides the relative consequences of false positives and false negatives. Report the confusion matrix, sensitivity, specificity, predictive values, calibration, uncertainty, subgroup results, and decision consequences at the intended threshold.

## Discussion Questions

1.  When would you choose logistic regression over a Random Forest, even if the Random Forest has higher accuracy?

2.  Your model has 95% accuracy but only 40% sensitivity. Is this acceptable for an outbreak detection system? Why or why not?

3.  A colleague says “deep learning is always better than traditional ML.” How do you respond?

4.  You train a model to predict hospital readmission with AUC = 0.92 on test data. Should you deploy it immediately? What else should you check?

5.  If forced to choose between a model that’s 90% accurate but uninterpretable vs. 80% accurate but fully interpretable, which would you choose for a public health application? Does the context matter?

## Further Reading

### Foundational Papers

- Mitchell, T. (1997). [Machine Learning](https://www.cs.cmu.edu/~tom/mlbook.html). McGraw-Hill.
- Breiman, L. (2001). [“Random Forests.”](https://doi.org/10.1023/A:1010933404324) *Machine Learning*, 45(1), 5-32.
- Friedman, J.H. (2001). [“Greedy function approximation: A gradient boosting machine.”](https://doi.org/10.1214/aos/1013203451) *Annals of Statistics*, 29(5), 1189-1232.
- Goodfellow, I., Bengio, Y., & Courville, A. (2016). [*Deep Learning*](https://www.deeplearningbook.org/). MIT Press.

### Public Health Applications

- Rajkomar, A., et al. (2019). [“Machine Learning in Medicine.”](https://doi.org/10.1056/NEJMra1814259) *New England Journal of Medicine*, 380(14), 1347-1358.
- Beam, A.L., & Kohane, I.S. (2018). [“Big Data and Machine Learning in Health Care.”](https://jamanetwork.com/journals/jama/article-abstract/2675024) *JAMA*, 319(13), 1317-1318. doi:10.1001/jama.2017.18391
- Bzdok, D., Altman, N., & Krzywinski, M. (2018). [“Statistics versus machine learning.”](https://doi.org/10.1038/nmeth.4642) *Nature Methods*, 15(4), 233-234.

### Explainability and Fairness

- Lundberg, S.M., & Lee, S.I. (2017). [“A unified approach to interpreting model predictions.”](https://proceedings.neurips.cc/paper/2017/hash/8a20a8621978632d76c43dfd28b67767-Abstract.html) *NIPS* 2017.
- Ribeiro, M.T., Singh, S., & Guestrin, C. (2016). [“‘Why Should I Trust You?’: Explaining the Predictions of Any Classifier.”](https://doi.org/10.1145/2939672.2939778) *KDD* 2016.
- Obermeyer, Z., et al. (2019). [“Dissecting racial bias in an algorithm used to manage the health of populations.”](https://doi.org/10.1126/science.aax2342) *Science*, 366(6464), 447-453.

------------------------------------------------------------------------

The remaining chapters apply these concepts to specific public health problems.

*Next chapter: [The Data Problem in Public Health AI](../foundations/data.html): why public health data is uniquely challenging and how to handle it.*

![](../images/bryan-tegomoh-author.jpg)

[Bryan Tegomoh, MD, MPH](https://bryantegomoh.com/)

Physician-scientist and epidemiologist in health AI and biosecurity.

[Follow @BryanTegomoh](https://x.com/intent/follow?screen_name=BryanTegomoh) [Follow on LinkedIn](https://www.linkedin.com/comm/mynetwork/discovery-see-all?usecase=PEOPLE_FOLLOWS&followMember=bryan-tegomoh-md-mph) [Support](../support.html)

The Public Health AI Handbook is free to read and cite, with no third-party advertising. If this chapter informed your work, [you can support the handbook](../support.html).
