27  Machine Learning for Biostatistics

27.1 Learning objectives

By the end of this chapter you should be able to:

  • Use tidymodels to specify, fit, tune, and evaluate predictive models with a consistent workflow.
  • Choose between gradient-boosted trees (xgboost, lightgbm), random forests (ranger), and regularized GLMs based on dataset characteristics, interpretability needs, and the role of the model in the analysis.
  • Implement nested cross-validation for hyperparameter tuning and unbiased performance estimation, and recognize when single-level CV is misleadingly optimistic.
  • Apply calibration assessment and recalibration to probabilistic classifiers, and explain why area under the ROC curve does not measure calibration.
  • Use SHAP values (Lundberg & Lee, 2017) for model interpretation, and articulate what they show and what they do not (association, not causation).
  • Recognize when a ‘machine learning’ framing is hiding a classical statistical question, and when the reverse is true.

27.2 Orientation

The boundary between machine learning and biostatistics is porous and, in places, confused. Both disciplines fit predictive models from data, both quantify uncertainty, and both worry about overfitting and generalization. The usual cultural distinction holds that ML emphasizes black-box prediction while biostatistics emphasizes interpretable inference. That distinction was never as clean as the caricature suggests, and it has eroded further as each field adopts the other’s tools.

The reader should not expect an introduction to machine learning here; our goal is narrower. We shall consider how to use the modern ML toolkit in biostatistical work where the question is genuinely predictive. We shall also consider how to recognize when the toolkit is being misapplied to a question that calls for classical inference instead.

We begin with tidymodels (Kuhn & Silge, 2022) as the contemporary R interface. It is a coherent, principled stack that handles preprocessing, resampling, tuning, and evaluation with consistent verbs. We then turn to the algorithm choices that matter most in clinical and epidemiological work, and after that to the validation and calibration machinery. Lastly, we discuss the interpretability tools that have made black-box models more defensible than they used to be, and we close with a worked example on readmission risk.

27.3 The statistician’s contribution

LLMs can fit a gradient-boosted tree, run cross-validation, and produce a calibration plot. They cannot, however, decide whether prediction or inference is the right framing. Nor can they judge whether the deployed model will actually improve the decision it informs, or whether the data resemble those in which the model will be used.

(Judgment 1.) Prediction is not inference. A model that achieves high AUC on a held-out set is a good predictor. It is not, however, a tool for asking which variables cause the outcome, what the conditional effect of treatment is, or how a policy intervention would change outcomes. Conflating prediction performance with causal or counterfactual claims is the most common error in applied ML in medicine. The statistician’s job is to keep this distinction visible in the analysis, in the report, and in the conversation with collaborators.

(Judgment 2.) The held-out set should represent the deployment distribution, not the design distribution. Models trained on data from one hospital and evaluated on held-out cases from the same hospital are evaluated on the training distribution. A model that will be deployed to a different hospital, or to a future cohort, must be evaluated under that shift. The options include temporal hold-out, geographic hold-out, and prospective validation. The statistician identifies the deployment scenario and designs the evaluation to match it.

(Judgment 3.) Calibration is the metric clinicians need. Discrimination (AUC, accuracy) tells us whether the model orders patients correctly. It does not tell us whether ‘the model says 30%’ means that 30% of those patients will have the event. Some decisions require absolute risk thresholds (treat / do not treat above 10% predicted risk). For such decisions calibration is the binding constraint, and it is not what tuning typically optimizes. The statistician therefore checks calibration explicitly and recalibrates if needed.

27.4 The tidymodels workflow

tidymodels (Kuhn & Silge, 2022) is a meta-package covering the steps of a modeling pipeline:

  • rsample for resampling (CV, bootstrap, time-based splits).
  • recipes for preprocessing (centering, encoding, missing data handling).
  • parsnip for model specification (uniform interface across glmnet, ranger, xgboost, keras, etc.).
  • tune for hyperparameter tuning.
  • yardstick for performance metrics.
  • workflows for binding preprocessing + model into one object.

The design goal is consistency. That is, switching from logistic regression to gradient boosting changes a single line. To illustrate, consider a typical pipeline:

library(tidymodels)

split <- initial_split(d, strata = outcome, prop = 0.75)
train <- training(split)
test <- testing(split)

rec <- recipe(outcome ~ ., data = train) |>
  step_rm(id) |>
  step_impute_median(all_numeric_predictors()) |>
  step_dummy(all_nominal_predictors()) |>
  step_normalize(all_numeric_predictors())

xgb_spec <- boost_tree(
  trees = 1000, tree_depth = tune(),
  learn_rate = tune(), min_n = tune()
) |>
  set_engine("xgboost") |>
  set_mode("classification")

wf <- workflow() |>
  add_recipe(rec) |>
  add_model(xgb_spec)

folds <- vfold_cv(train, v = 5, strata = outcome)
grid <- grid_latin_hypercube(
  tree_depth(), learn_rate(), min_n(),
  size = 30
)

tuned <- tune_grid(
  wf, resamples = folds, grid = grid,
  metrics = metric_set(roc_auc, brier_class)
)

best <- select_best(tuned, metric = "brier_class")
final_fit <- finalize_workflow(wf, best) |>
  last_fit(split, metrics = metric_set(
    roc_auc, brier_class, accuracy))

Two design choices in this pipeline warrant comment. First, the metric used to select hyperparameters determines what is optimized. Choosing on roc_auc optimizes ranking, whereas choosing on brier_class (or mn_log_loss) optimizes probabilistic calibration. We should choose the metric that the downstream decision actually uses.

Second, last_fit() deliberately uses the test split only once, after tuning is complete. Peeking at the test set and re-tuning is the single largest source of optimistic performance estimates in applied ML.

27.5 Algorithm choices that matter

For tabular biomedical data, four model families do most of the work. We take them in turn.

Regularized generalized linear models (glmnet). The elastic net from Chapter 26 fits cleanly into tidymodels via parsnip::logistic_reg(penalty = tune(), mixture = tune()). It is interpretable and, with an appropriate penalty, well calibrated by construction. It is also the right baseline for any classification problem with sample sizes in the thousands or fewer.

Random forests (ranger). They need little tuning and perform reliably on tabular data with non-linear interactions. They are less prone to overfitting than boosted trees. However, they are typically outperformed by boosted trees when tuning is done well.

Gradient-boosted trees (xgboost, lightgbm). These are the default for high-performance prediction on tabular data. xgboost (Chen & Guestrin, 2016) is the established choice. lightgbm is faster on very large datasets and handles categorical predictors more naturally. Both require careful tuning of learn_rate, tree_depth, min_n, and the number of trees. With too little capacity they underfit, and with too much they overfit.

Neural networks (torch, keras). For tabular biomedical data with \(n\) in the thousands, neural networks rarely outperform gradient boosting, and they require considerably more engineering effort. They earn their place on high-dimensional sequence, image, or text data. Examples include clinical notes via transformers, medical imaging via convolutional networks, and time series via recurrent or attention architectures. Outside those settings, we would prefer trees.

A practical decision rule is as follows.

Setting Default model
\(p < n\), interpretability matters Regularized GLM
\(p < n\), raw prediction matters Gradient boosting
\(p \approx n\) or \(p > n\), sparse Lasso (Chapter 26)
Tabular with non-linear interactions Gradient boosting
Imaging, text, sequence Deep learning

Question. A clinical decision support tool will use a risk model output to display ‘high’, ‘medium’, or ‘low’ risk to clinicians. The thresholds are predicted probability above 30% (high) and below 10% (low). Should hyperparameters be tuned on AUC or on Brier score?

Answer.

Brier score (or log loss). The decision rule uses absolute predicted probabilities, so calibration matters for the decision. AUC measures discrimination (does the model correctly order patients?) and is invariant to monotonic transformations of the score. A model with excellent AUC can therefore have terrible calibration. That is, it ranks correctly, but its predicted probabilities are systematically off. Tuning on AUC and then deploying with absolute-threshold decisions is a common error. We would tune on Brier score and report AUC for context.

27.6 Validation: nested CV and external validation

Single-level cross-validation gives an optimistic estimate of out-of-sample performance when CV is also used for hyperparameter tuning. The reason is that the tuning has implicitly seen all of the data.

Nested CV corrects this. An inner CV loop chooses hyperparameters, and an outer CV loop estimates performance. Because the outer loop never sees the tuning, its performance estimate is unbiased.

nested <- nested_cv(
  train,
  outside = vfold_cv(v = 10),
  inside = vfold_cv(v = 5)
)

Nested CV is computationally expensive. The example above requires 50 fits, plus a final fit on the full training set. Nevertheless, it is the correct estimator when the question is ‘what performance should we expect when we deploy this pipeline?’

For models intended for deployment, external validation on data the model has never seen is more important than any internal CV estimate. The relevant external set depends on the deployment scenario:

  • Temporal validation: train on cases through year \(T\) and evaluate on year \(T+1\). This catches drift in case mix, coding practices, and population.
  • Geographic validation: train on hospital A and evaluate on hospital B. This catches site-specific feature distributions.
  • Prospective validation: train on retrospective data and evaluate on prospectively collected cases under the actual deployment workflow. This is the gold standard for high-stakes deployments.

A model that drops 0.05 AUC from internal CV to external validation has a deployment problem. A drop of 0.15 points to an external distribution fundamentally different from the training set, and the analyst should investigate before deployment.

27.7 Calibration and recalibration

Calibration is the property that ‘the model says 20%’ means that 20% of those cases have the event. We check it by plotting predicted probability (binned) against the observed event rate. A perfectly calibrated model lies on the diagonal.

library(probably)
cal_plot_breaks(test_with_preds,
                truth = outcome, estimate = .pred_yes,
                num_breaks = 10)

Two patterns are common:

  • Over-confident model: predicts probabilities too close to 0 and 1, so the curve is steeper than the diagonal. This is common with deep learning models trained on small data.
  • Under-confident model: predicts probabilities too close to the base rate, so the curve is shallower than the diagonal. This is common with heavy regularization or with log-loss-suboptimal training.

Recalibration post-fits a one-dimensional function that maps raw scores to calibrated probabilities. There are two standard methods:

  • Platt scaling: fits a logistic regression of the outcome on the raw score.
  • Isotonic regression: fits a non-decreasing function. It is more flexible but requires more recalibration data.

probably::cal_apply() integrates these into the tidymodels workflow. Recalibration is essential when we deploy a model whose raw outputs do not match the deployment distribution. It is also a free improvement on most ML models, since the cost of training a calibration layer is trivial.

27.8 Interpretability: SHAP and beyond

For a deployed model, the relevant interpretability question is rarely ‘which features are most important overall’, which permutation importance answers. The more common question is ‘why did the model give this patient this prediction’. SHAP values (Lundberg & Lee, 2017) (Shapley values from cooperative game theory) provide a principled per-prediction decomposition.

library(SHAPforxgboost)
shap_long <- shap.prep(xgb_model = final_xgb,
                       X_train = X_matrix)
shap.plot.summary(shap_long)
shap.plot.dependence(shap_long, x = "age")

SHAP values have two strong properties. They sum to the prediction (local accuracy), and they distribute credit fairly across features. Unfortunately, they also have one persistent limitation: they describe the model’s dependence on a feature, not the world’s. Suppose the model has learned a spurious association; say, sex is associated with outcome because of unmeasured confounders. SHAP will then faithfully describe that association as the model uses it. SHAP does not provide causal inference. An interpreter who treats SHAP values as causal effects is making a claim the method cannot support.

An explanation of the model says something about the data only to the extent that the analyst trusts the model. To illustrate, suppose a clinician asks ‘why does the model predict high risk for this patient?’ SHAP gives a defensible answer. Suppose the same clinician then asks ‘so if we intervene on age, will risk drop?’ SHAP cannot answer that question.

27.9 Worked example: 30-day readmission risk model

We now extend the readmission example from Chapter 23 to a machine-learning workflow with proper validation and calibration.

library(tidymodels)
library(probably)

set.seed(2026)
n <- 8000
d <- tibble(
  age = rnorm(n, 65, 12),
  cmi = rnorm(n, 1.5, 0.4),
  prior_admits = rpois(n, 0.6),
  los = rgamma(n, shape = 2, rate = 0.4),
  service = sample(c("med","surg","cards"), n,
                   replace = TRUE)
)
d$readmit <- factor(rbinom(
  n, 1,
  plogis(-2 + 0.02 * (d$age - 65) +
         0.5 * (d$cmi - 1.5) +
         0.3 * d$prior_admits +
         0.05 * d$los)
), labels = c("no","yes"))

split <- initial_split(d, strata = readmit, prop = 0.75)
train <- training(split); test <- testing(split)

rec <- recipe(readmit ~ ., data = train) |>
  step_dummy(all_nominal_predictors()) |>
  step_normalize(all_numeric_predictors())

xgb_spec <- boost_tree(
  trees = 500, tree_depth = tune(),
  learn_rate = tune(), min_n = tune()
) |> set_engine("xgboost") |>
     set_mode("classification")

wf <- workflow() |> add_recipe(rec) |> add_model(xgb_spec)

folds <- vfold_cv(train, v = 5, strata = readmit)
grid <- grid_latin_hypercube(
  tree_depth(range = c(2, 6)),
  learn_rate(range = c(-3, -1)),
  min_n(),
  size = 25
)

tuned <- tune_grid(
  wf, resamples = folds, grid = grid,
  metrics = metric_set(roc_auc, brier_class)
)

best <- select_best(tuned, metric = "brier_class")
final_fit <- finalize_workflow(wf, best) |>
  last_fit(split,
           metrics = metric_set(roc_auc, brier_class))

collect_metrics(final_fit)

The held-out AUC is around 0.74 and the Brier score around 0.16. These values are competent for a heavily simulated example. The calibration plot from probably::cal_plot_breaks() reveals a mild over-confidence at high predicted probabilities, and a Platt recalibration narrows the gap.

A logistic regression with elastic-net regularization, fit to the same problem, gives an AUC around 0.73 and a Brier score around 0.16. That is, the two models are effectively indistinguishable. For this dataset the flexibility of the gradient-boosted tree yields no benefit over the regularized GLM, and the simpler model is the right deployment.

This is the typical finding in applied biomedical ML. On tabular data with thousands of cases, regularized GLMs and gradient-boosted trees are within a percent of each other. The gradient-boosted tree wins when there are strong non-linear interactions. Otherwise the simpler model wins on parsimony, calibration, and ease of explanation.

27.10 Collaborating with an LLM on machine learning

LLMs handle the syntax of tidymodels, xgboost, and SHAP fluently. Unfortunately, they are unreliable on the choice between prediction and inference, on validation strategy, and on the interpretation of model explanations. We consider three representative prompts.

Prompt 1: ‘Build me a tidymodels pipeline for this binary outcome.’ Provide the data and the outcome.

What to watch for. The LLM will produce a working pipeline. It will rarely ask whether the goal is prediction or inference, and it will rarely propose external validation. It will also default to AUC as the tuning metric, even when absolute calibration is the binding constraint.

Verification. Before accepting the pipeline, we should articulate the decision the model will inform. If the decision is a threshold-based action (‘treat above 10% predicted risk’), we override the metric to Brier score and add a calibration plot. If the decision is to deploy at another site, we plan external validation now, not after CV is complete.

Prompt 2: ‘Why is the model giving this prediction for this patient?’ Provide the patient’s features and the model.

What to watch for. The LLM will produce a SHAP-style explanation: ‘age contributes +0.4 to the log-odds, low CMI contributes -0.2,’ etc. It will rarely flag that this explains the model’s behavior, not the underlying biology. It may also slip into language that sounds causal, such as ‘increasing age increases risk.’

Verification. The model explanation describes how the trained model uses the features in this case. It is not a causal effect. We therefore translate any LLM explanation into explicit ‘the model attributes’ language before showing it to a clinician.

Prompt 3: ‘Compare gradient boosting and logistic regression on this dataset.’ Provide the data.

What to watch for. The LLM will fit both models, report metrics, and pick the higher-AUC model. It will rarely test the difference for significance, run nested CV to estimate generalization honestly, or check calibration on the selected model. It will often miss that an apparent 0.005-AUC advantage is well within sampling noise.

Verification. We estimate the uncertainty in the AUC difference via a paired bootstrap on the test set. We then run nested CV to confirm that the advantage is not an artifact of single-level tuning. If the difference is small, we report both models and let the parsimony argument decide.

The LLM, then, is best treated as a fluent technician. It is competent at the mechanics (pipeline construction, metric calculation, SHAP plots). It is weak at judging whether the model matches the deployment scenario, whether an apparent advantage is real, and what an explanation actually means.

27.11 Principle in use

Three habits define defensible ML work:

  1. State the deployment scenario before tuning. We need to know who will use the model, where, and on what distribution. The validation strategy and the metric are then tuned to match. A model evaluated on the same distribution it was trained on is a benchmark, not a deployable artifact.

  2. Calibrate before deployment. Most ML models are poorly calibrated out of the box. Recalibration via Platt scaling or isotonic regression on a held-out set is cheap insurance. Unfortunately, threshold-based decisions on uncalibrated scores are a common source of clinical-deployment failures.

  3. Distinguish model explanation from causal claim. SHAP, permutation importance, and partial-dependence plots describe the model, not the world. Reports that conflate the two mislead clinicians and reviewers.

27.12 Exercises

  1. Repeat the readmission worked example with \(n = 800\) instead of \(n = 8000\). Compare the AUC and Brier improvements of the gradient-boosted tree over the logistic regression at small sample size.

  2. Implement nested CV for the readmission pipeline. Compare the nested-CV AUC estimate to the simple train/test estimate. How large is the optimism?

  3. Train the model on the first 70% of the data sorted by date, and evaluate it on the last 30%. Compare the temporal-validation AUC to the random-split AUC. Discuss any differences.

  4. Apply Platt recalibration to a deliberately over-confident model (e.g., a deep tree with no regularization). Plot calibration before and after.

  5. Use SHAP on the readmission gradient-boosted tree. Identify a patient where the model’s prediction is surprising (high predicted risk despite a low-risk profile). Investigate the SHAP attribution and discuss whether it would be defensible language to use with a clinician.

27.13 Further reading

  • Kuhn & Silge (2022), the tidymodels book (https://www.tmwr.org/). The canonical applied reference.
  • Hastie et al. (2009), The Elements of Statistical Learning. The textbook treatment of the underlying methods.
  • Lundberg & Lee (2017), the SHAP paper. Best read alongside the shap documentation (https://shap.readthedocs.io/).
  • Van Calster et al. (2019), Calibration: the Achilles heel of predictive analytics. The essential applied reference for clinical prediction model calibration.