About this page
How-to guide- What this page solves
- You have a clinical table of data, for example baseline measures and in-hospital death for 1,000 patients, and want a model that predicts death risk. Peer reviewers will ask whether the sample is large enough, why the variables were chosen, and whether the model was validated.
- Who it is for
- Researchers or graduate students building their first clinical prediction model. You can read data into R or Python, but you have not yet done cross-validation and model evaluation systematically.
- What you will have
- By the end you will have a modelling script with fixed folds; an internally validated model with its AUC, calibration intercept and slope, and decision curve; a nomogram; and a methods checklist against TRIPOD+AI.
- Covers
- Estimating the sample size needed to develop a model with the Riley method (pmsampsize)
- Handling missing values, deciding the form of continuous variables, and selecting variables with LASSO
- Estimating performance on new data with nested cross-validation or bootstrap
- Evaluating discrimination, calibration and decision curves, drawing a nomogram, and reporting against TRIPOD+AI
- Branches for survival outcomes, small samples and SHAP explanations
- Does not cover
- Causal inference, that is, estimating the effect of an intervention
- Upstream processing of expression data such as GEO download and batch correction (see the GEO data mining guide)
- Neural networks and deep learning models
- Item-by-item PROBAST risk-of-bias judgements (mentioned only in the reporting part)
- Differential expression and enrichment analysis (see the differential expression and enrichment guide)
Main steps
Sample size
Why this stepSample size determines whether the model can estimate each coefficient stably. EPV is the number of outcome events per candidate parameter; a common rule of thumb is EPV ≥ 10. This step uses the Riley method instead, which takes both the outcome incidence and the expected model performance into account.
First state the prediction question: which population, which time point and which outcome. Count parameters as the total number of candidate parameters before selection.
The example is the SUPPORT study data: 1,000 patients, 253 in-hospital deaths, prevalence 0.253. The 21 candidate variables expand to 30 parameters.
The C statistic measures how well a model separates the two groups; for a binary outcome it is the same as the AUC. Here it is taken from a published model for the same outcome, 0.80.
Run the code below. For a binary outcome, take the largest of the three criteria. If the C statistic or the number of parameters changes, the required sample size changes a lot; see the reference table. If the sample is too small, see the choices section on sample size and class imbalance.
library(pmsampsize) # 1.1.3
# Binary outcome: prevalence 0.253, C statistic 0.80 from a published model (prefer an optimism-adjusted value), 30 candidate parameters
pmsampsize(type = "b", cstatistic = 0.80, parameters = 30, prevalence = 0.253)
#> Criteria 1 (shrinkage >= 0.9) 1136
#> Criteria 2 (R2 optimism <= 0.05) 774
#> Criteria 3 (intercept +/- 0.05) 291
#> Final 1136, 288 events, EPP = 9.58Data preparation
Why this stepMissing values and variable form change the model inputs directly, so they are decided before modelling. A continuous variable is one that takes any numerical value, such as age or blood pressure.
Multiple imputation is the recommended method for missing values. It creates several completed datasets, fits the model to each and then combines the results. The imputation model is fitted on training data only.
The example data were singly imputed with the normal values recommended by SUPPORT. This is for demonstration only; a formal analysis should use multiple imputation.
If the analysis sample is much smaller than the raw data, see the matching troubleshooting entry.
- 01
Count missing values
Count the proportion missing for each variable and record it. You will report it in the methods later.
- 02
Impute missing values
Fill in missing values with multiple imputation. Fit the imputation model on training data only.
- 03
Keep continuous variables continuous
Keep continuous variables in continuous form. If the relation to risk is curved, model it with restricted cubic splines (rcs), a smooth term that lets the curve bend.
Data splitting
Why this stepSplitting decides which samples are used for modelling and which are used to test the model. Cross-validation divides the sample into several folds; each round tests on one fold and models on the others.
With a small sample, a single random 70:30 split changes with the split and leaves a small validation set, so this page uses cross-validation instead.
A training fold is the part of the sample used to fit the model in one round. Scaling, imputation, variable selection and tuning are all done inside the training folds, not on the whole dataset first.
Fix the folds when the analysis starts and save them. Every later analysis uses the same foldid.
If you need independent data, see the choices section on validation methods. If the results change a lot with another seed, see troubleshooting: LASSO selects different variables each run.
library(glmnet)
set.seed(2026)
foldid <- sample(rep(1:10, length.out = nrow(dat))) # each sample is assigned to one of folds 1 to 10Variable selection
Why this stepLASSO is a penalised regression. The penalty shrinks the coefficients of variables with little effect to 0, which selects the variables. The strength of the penalty is called lambda, and cross-validation chooses it. Variables with a coefficient of 0 do not enter the model.
cv.glmnet uses LASSO by default (alpha = 1) and standardises each column internally before applying the penalty. Coefficients are returned on the original scale, so you do not need to scale the data yourself.
When you read the coefficients, write the s argument explicitly, choosing lambda.min or lambda.1se. The difference between them is explained in the explanation section.
This page uses lambda.1se, which keeps fewer variables. If the selected variables differ between runs, see troubleshooting: LASSO selects different variables each run.
library(glmnet) # version 5.0 used on this page
X <- model.matrix(y ~ ., data = dat)[, -1] # factors expanded to dummy variables; X must be a numeric matrix
y <- dat$y # 0 or 1
cv <- cv.glmnet(X, y, family = "binomial", foldid = foldid) # use the folds fixed in step 3
plot(cv) # left line lambda.min, right line lambda.1se
coef(cv, s = "lambda.min") # write s explicitly
coef(cv, s = "lambda.1se")Internal validation
Why this stepInternal validation estimates how the model will perform on new samples, using the same data. The cross-validation error used for tuning is itself optimistic, so the estimate is repeated in an outer loop. The outer loop of nested cross-validation estimates the performance of the whole modelling procedure.
The inner loop is used only for tuning, and the outer loop is used only to estimate performance. Set the folds of the two loops separately.
The final model is refitted on all data with the same tuning procedure as the inner loop. It is normal for the outer folds to select different hyperparameters.
A regression model can also use bootstrap optimism correction: repeat the whole modelling on resamples drawn with replacement, then estimate and subtract the optimism. The code is in the reference section.
If the result is much better than external validation, see troubleshooting: tuning and reporting used the same cross-validation.
import numpy as np
from sklearn.model_selection import StratifiedKFold, GridSearchCV, cross_validate
from sklearn.pipeline import Pipeline
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import RandomForestClassifier
from xgboost import XGBClassifier
inner = StratifiedKFold(n_splits=5, shuffle=True, random_state=1) # inner loop: tuning
outer = StratifiedKFold(n_splits=5, shuffle=True, random_state=2) # outer loop: performance estimate
models = {
# penalty is deprecated from scikit-learn 1.8; L1 is l1_ratio=1. Before 1.8 use penalty="l1"
"lasso_lr": (Pipeline([("imp", SimpleImputer(strategy="median")),
("sc", StandardScaler()),
("clf", LogisticRegression(l1_ratio=1, solver="saga", max_iter=5000))]),
{"clf__C": np.logspace(-3, 1, 20)}),
"rf": (Pipeline([("imp", SimpleImputer(strategy="median")),
("clf", RandomForestClassifier(n_estimators=500, random_state=0))]),
{"clf__max_features": ["sqrt", 0.33, 0.5], "clf__min_samples_leaf": [1, 5, 10, 20]}),
"xgb": (Pipeline([("clf", XGBClassifier(n_estimators=300, eval_metric="logloss"))]),
{"clf__learning_rate": [0.03, 0.1], "clf__max_depth": [2, 3, 4],
"clf__min_child_weight": [1, 5]}),
}
for name, (pipe, grid) in models.items():
search = GridSearchCV(pipe, grid, cv=inner, scoring="neg_log_loss") # tune on log loss, which also rewards calibration
res = cross_validate(search, X, y, cv=outer, scoring=["roc_auc", "neg_brier_score"])
print(name, res["test_roc_auc"].mean().round(3), res["test_roc_auc"].std().round(3),
(-res["test_neg_brier_score"]).mean().round(4))Evaluation
Why this stepEvaluation answers three questions: can the model separate people with and without the outcome, are the predicted probabilities accurate, and does using the model for decisions give net benefit? Discrimination is measured by the AUC. Calibration means whether predicted probabilities match observed event rates. Decision curve analysis (DCA) compares the net benefit of using the model with treating everyone and treating no one.
Report the AUC with its 95% CI. Calibration is shown by the calibration intercept, the calibration slope and a smoothed calibration curve.
The target value of the calibration intercept is 0, and the target value of the calibration slope is 1.
Set the range of thresholds for the decision curve before the analysis, according to the clinical context. If the AUC is high but the net benefit is low, see the explanation section: a high AUC does not mean high net benefit.
library(pROC); library(rms); library(dcurves)
# p: predicted probabilities from external validation (or outer CV / bootstrap-corrected); y: 0/1 outcome
r <- roc(y, p, direction = "<", quiet = TRUE) # set direction explicitly on validation data
ci.auc(r) # DeLong 95% CI by default
# roc.test(r1, r2) # paired DeLong test for two non-nested models in the same patients
val.prob(p, y) # C, Brier, calibration intercept, slope, Emax, and a smoothed calibration curve
df <- data.frame(y = y, model = p)
dca(y ~ model, data = df, thresholds = seq(0, 0.5, by = 0.01)) |>
plot(smooth = TRUE) # Treat All and Treat None are drawn as referencesNomogram
Why this stepA nomogram draws a fitted model as a chart of scales, so the risk can be read off by hand. A nomogram does not add validity to the model. It has the same reporting requirements: internal validation, calibration and external validation. Report against the TRIPOD+AI checklist item by item.
datadist is the rms setting that records each variable's range. Set it before fitting, using the same data frame. When fitting, add x = TRUE, y = TRUE, so that internal validation and calibration can run.
The calibrate plot has two lines, Apparent and Bias-corrected. Report the Bias-corrected line.
The TRIPOD+AI table is in the reference section. Nomograms for survival outcomes are in the choices section. If you see a datadist or x = TRUE error, see the matching troubleshooting entry.
library(rms) # checked against 8.1.1
dd <- datadist(dat); options(datadist = "dd") # set before fitting, using the same data frame
fit <- lrm(y ~ rcs(age, 4) + sex + scoma + meanbp + pafi + alb + bili + crea,
data = dat, x = TRUE, y = TRUE) # x, y = TRUE are needed by validate and calibrate
nom <- nomogram(fit, fun = plogis, funlabel = "Risk of in-hospital death",
fun.at = c(0.05, 0.1, 0.2, 0.4, 0.6, 0.8))
plot(nom)
set.seed(2026)
validate(fit, B = 200) # optimism-corrected Dxy, slope, etc.; C = Dxy / 2 + 0.5; B defaults to only 40
cal <- calibrate(fit, B = 200)
plot(cal) # Apparent and Bias-corrected lines; report Bias-correctedChoose by your situation
Hand it to an agent
Sample size calculation, repeated cross-validation and bootstrap, multi-algorithm comparison and plotting are time-consuming but rule-based steps that a scientific agent can run. The research question, prediction time point and interpretation remain the researcher's decisions; the checklist below lists what the researcher must check.
Example instruction: "Here is my cohort data cohort.csv. The outcome is 30-day death and the prediction time point is 24 hours after admission. First calculate the sample size with pmsampsize, then use spline logistic regression as the baseline and compare LASSO, random forest and XGBoost. Report AUC, calibration intercept and slope, and DCA using 5×5 nested cross-validation, draw a nomogram, and list the methods items TRIPOD+AI requires."
The agent runs the following steps in an isolated cloud computer. Scikit-learn, statsmodels and pandas are preinstalled, and the agent installs R packages in the project. The agent reviews the results adversarially and checks whether any leakage step is present.
- 01
Check the data
Check the variable types, the proportion missing, and any variables that only exist after the prediction time point.
- 02
Calculate the sample size
Run pmsampsize and record the inputs and outputs.
- 03
Keep the steps in one loop
Put imputation, scaling, selection and tuning in the same Pipeline or bootstrap loop.
- 04
Check stability
Check the stability of the LASSO variable sets over 100 seeds.
- 05
Produce outputs
Output nested cross-validation results for each model, calibration curves, decision curves, the nomogram and SHAP plots, and a TRIPOD+AI table.
- The outcome definition and prediction time point fit the clinical setting
- All candidate variables are available at the prediction time point
- The DCA threshold range is reasonable
- The external validation data are truly independent
- The clinical interpretation of the results holds
Model choice
The table lists common methods by data situation. For tabular clinical data with a modest number of variables, a regression model is usually the starting point.
A baseline model is a simple model fitted first and used for comparison with the other methods. The order is: first build a baseline with logistic or Cox regression with splines.
If a machine learning model does not clearly beat the baseline in discrimination and calibration under nested cross-validation or external validation, report the baseline model.
When a reviewer asks why machine learning was used, this comparison is the answer. The evidence is in the explanation section.
| Method | When it fits | Key hyperparameters (starting points) | Probability output | Common misuse |
|---|---|---|---|---|
| Logistic / Cox regression (with splines) | Tabular clinical data, modest number of variables, a nomogram and interpretable coefficients are needed | 3–5 spline knots | Usually well calibrated | Dichotomising continuous variables; stepwise selection |
| LASSO / elastic net | Many candidates or high-dimensional expression data; a sparse model is needed | lambda (inner CV), alpha | Shrunken; calibration slope close to 1 | Two-step refit that removes shrinkage; seed picking |
| Random forest | Complex interactions and non-linearity, large samples | mtry (R default √p), ntree ≥ 500, minimum node size | With minimum node size 1, probabilities are pushed to the extremes and training AUC approaches 1 | Reporting training performance with predict(rf, newdata = training data) |
| XGBoost | Large samples, many variables, interactions | learning_rate 0.01–0.1, max_depth 2–4, min_child_weight, subsample, early stopping | Usable with the default logloss objective; distorted after scale_pos_weight | Fitting a small sample with the defaults learning_rate 0.3 and max_depth 6 |
| SVM | Moderate samples, continuous features, ranking only | C, gamma (RBF kernel); scaling is required | scikit-learn probability=True uses internal 5-fold Platt scaling; predict and predict_proba can disagree | Treating decision_function as a probability on a calibration plot |
Sample size and class imbalance
The table gives the approach for each situation and the reporting requirement.
The AUC only looks at ranking, so its meaning is the same whether 5% or 50% of patients have the outcome. The main problem with imbalance is low sensitivity at a threshold of 0.5. This can be solved by choosing a threshold that fits the clinical need, without changing the training data.
Riley et al. (2021) showed that penalised methods are themselves unstable in small samples and cannot replace an adequate sample size.
When resampling is required, the correct way to write SMOTE is in the troubleshooting section. The XGBoost rows follow its official tuning notes.
| Situation | Approach | What to report |
|---|---|---|
| Sample smaller than the pmsampsize result | Reduce candidate parameters: merge rare categories, drop variables a priori based on the literature, use fewer spline knots; use penalised regression; discuss it | Report the calculated requirement and the gap to the actual sample size, and the bootstrap-corrected calibration slope |
| Rare outcome, most cases | No resampling; choose a threshold for high and low risk that fits the clinical need | State that no resampling was done (TRIPOD+AI item 13) |
| Resampling is required, such as SMOTE or undersampling | Put the sampler only inside the training folds, using imblearn's Pipeline; then recalibrate on data with the original distribution | State whether it was used, why, how, and how it was recalibrated (TRIPOD+AI item 13) |
| XGBoost, AUC only | Balance the class weights with scale_pos_weight | Report the weight setting |
| XGBoost, correct predicted probabilities | Do not rebalance the data; set max_delta_step to a finite value (e.g. 1) to help convergence | Report the max_delta_step setting |
Validation methods
The same model can be validated in different ways, and the strength of the conclusion differs. The table compares common internal validation methods.
When you have independent data from another time or region, do external validation. In external validation, the coefficients, cut-offs and risk-group boundaries are fixed on the development set and then applied to the new data unchanged.
Without external data, use bootstrap optimism correction (200 or more resamples, repeating every modelling step each time) or nested cross-validation for internal validation. Report the corrected AUC, calibration slope and calibration curve.
State in the limitations that no external validation was done. A validation set split at random from the same data is internal validation.
Another set of samples from the same platform and lab in GEO can serve as a supplement, but its source is close to the development set, so it generalises less.
Validating gene data across platforms
When the development data come from TCGA RNA-seq and the validation data from a GEO array, the same coefficients are applied to expression values on different scales, so the absolute risk scores are not comparable. A common approach is to z-score each gene within each cohort. Discrimination (C-index, time-dependent AUC) can then be evaluated. Calibration needs the baseline risk re-estimated in the new cohort, and this must be reported in the paper.
| Method | Procedure | When to use | Problems |
|---|---|---|---|
| Random split (e.g. 70:30) | One split into training and validation sets | Very large samples (Harrell considers it unstable below about 20,000 patients) | Results change with the seed; small validation sets give wide CIs; wastes development data |
| k-fold cross-validation | Every observation is used for validation once | Evaluating one fixed pipeline | A single 10-fold run depends on the fold assignment |
| Repeated k-fold cross-validation | Repeat 10-fold several times and average | When a stable estimate is needed | Harrell notes that about 100 repeats of 10-fold are needed to match the bootstrap |
| Bootstrap optimism correction | Redo every modelling step in each bootstrap sample, evaluate on the original data, average the optimism | Regression models, rms workflows; all data used for development | Selection and tuning must be redone every time, which is computationally heavy |
| Nested cross-validation | Inner loop tunes, outer loop estimates performance | Machine learning models with hyperparameters; comparing algorithms | The outer estimate describes the whole modelling pipeline, not one final model |
Explainability
SHAP splits each prediction into the contribution of each feature, which suits showing what a tree model has learned. The SHAP documentation has a dedicated article titled "Be careful when interpreting predictive models in search of causal insights".
import shap # 0.52
explainer = shap.TreeExplainer(xgb_model) # xgb_model: a fitted XGBClassifier
sv = explainer(X_test) # compute on the test set or outer folds, not the training set
shap.plots.beeswarm(sv) # for binary outcomes the x-axis is in log-odds, not probability
shap.plots.scatter(sv[:, "age"], color=sv) # dependence plot: non-linearity and interactionsUnits and the data used
For binary XGBoost models, TreeExplainer returns contributions on the log-odds scale by default; the values cannot be read directly as probability changes. Compute on the test set or outer folds; on the training set, noise learned through overfitting also appears as an "important feature".
Correlated features share credit
Two highly correlated variables (such as creatinine and urea nitrogen) split their SHAP values, so ranking alone understates both, and their order can swap with another random seed. Discuss correlated variables as a group.
Conclusions SHAP cannot support
A high SHAP value does not mean that changing the variable changes the outcome, so it cannot be written up as a "risk factor" or "therapeutic target". When SHAP rankings disagree across algorithms, their intersection is not a "robust biomarker" either. SHAP explains the model; it cannot fix a model that fails validation.
Reporting
State the SHAP version, explainer type, background data and the dataset on which values were computed. Place SHAP plots after the validation results, as a description of a validated model.
Survival outcomes
When the outcome has both whether it occurs and when it occurs, model it with Cox regression. Survival models also need internal validation, calibration and external validation, and the time point must be reported clearly.
For LASSO-Cox, give y as a Surv object, set family to "cox", and set type.measure to "C". The code is in the reference section.
The time point of a Cox nomogram must be the same as u in calibrate.
u and time.inc in calibrate.cph
u is the time point at which calibration is assessed; use the same value and time unit as time.inc in cph (days in pbc; 1,826 days is about 5 years). With cmethod = "KM", m is the number of patients per group, grouped by predicted survival; the default cmethod = "hare" requires the polspline package.
C-index versus time-dependent AUC
Harrell's C depends on the censoring distribution, so with long follow-up and heavy censoring it is hard to compare across studies; Uno's C (timewt = "n/G2" in survival::concordance) depends less on censoring. Time-dependent AUC (timeROC) answers whether the model separates people with and without an event by year t; report clinically meaningful time points such as 1, 3 and 5 years with 95% CI (iid = TRUE).
Proportional hazards assumption
If the global cox.zph test gives P < 0.05, inspect the Schoenfeld residual plots to find the offending variables, and handle them with stratification or time interactions. In large samples the test flags small departures, so rely mainly on the residual plots.
Forest plots
A forest plot shows the HR or OR with 95% CI for each variable in a multivariable Cox or logistic model. survminer::ggforest takes a coxph object and needs data passed as well; the forestplot package allows custom table columns. A forest plot shows associations and says nothing about each variable's contribution to predictive performance.
Concepts and judgment
Explanation
EPV ≥ 10 (at least 10 events per variable) comes from Peduzzi et al. (1996), a simulation of bias in regression coefficients. It does not take the outcome incidence or the expected model performance into account.
A simulation by van Smeden et al. (2019) found that EPV has only a weak relation to the prediction error of the model on new data.
Riley et al. (2020) proposed in the BMJ a method that calculates the sample size from a target precision. TRIPOD+AI item 10 asks authors to explain how the sample size was determined and why it is adequate.
The three Riley criteria
For binary and time-to-event outcomes, take the largest sample size across three criteria: expected shrinkage ≥ 0.9 (overfitting under control); difference between apparent and adjusted Nagelkerke R² ≤ 0.05; overall risk (intercept) estimated within ±0.05. Continuous outcomes have an additional residual-variance criterion. In the reference table, the shrinkage criterion is binding in every case.
Count candidate parameters, not selected variables
parameters is the total number of candidate parameters before selection: a 5-level factor counts as 4, a 4-knot spline as 3, and planned interactions count too. If LASSO keeps 12 of 30 parameters, the sample size is still calculated for 30.
Where the C statistic comes from
cstatistic is the C of a published model for the same outcome, ideally externally validated or optimism-adjusted; the function uses it to approximate the Cox-Snell R². The reference table shows that lowering the expected C from 0.80 to 0.70 raises the requirement from 1,136 to 2,732. Without a reference value, use a conservative, lower C.
Machine learning needs more data
van der Ploeg et al. (2014) simulated from three clinical cohorts: logistic regression reached a stable AUC at roughly 20 to 50 EPV, while random forest, SVM and neural networks needed more than 10 times that, and still showed clear optimism above 200 EPV. pmsampsize gives a lower bound for regression models.
Sample size for external validation
The older rule was at least 100 events and 100 non-events, and 200 of each for a smoothed calibration curve. In the Riley et al. (BMJ 2024) example (prevalence 0.43, C = 0.77), keeping the 95% CI width of the calibration slope within 0.3 alone required 949 patients and 408 events. pmvalsampsize in R and Stata performs the calculation.
Explanation
In high-dimensional expression data, variables far outnumber samples, so the LASSO result is less stable than the measured results in the reference section.
Highly correlated genes can substitute for each other, so LASSO often keeps just one gene from a co-expressed group, chosen at random.
Reporting a single "feature gene list" then means little. A better approach is to report bootstrap selection frequencies, or to use an elastic net (alpha between 0 and 1) so that correlated genes enter together.
The standardize parameter
Keep the default standardize = TRUE. glmnet standardises each column internally before penalising and returns coefficients on the original scale, so there is no need to scale beforehand. Turning standardisation off makes the penalty unequal across units and changes the variable set (12 became 8 in the reference table). Dummy variables are standardised too, which makes rare categories harder to select; penalty.factor can adjust them separately if needed.
lambda.min or lambda.1se
lambda.min minimises cross-validated error and keeps more variables with slightly better prediction; lambda.1se is the largest lambda within one standard error of the minimum and gives a sparser model. For prediction, the two usually perform similarly on new data; state the choice in the methods and keep it fixed. Switching to 1se to make the list look shorter, or to min to get a target gene selected, is a post hoc choice.
Explanation
Four levels of calibration
Van Calster et al. (BMC Medicine 2019) define mean calibration (intercept), weak calibration (intercept and slope), moderate calibration (smoothed calibration curve) and strong calibration (agreement for every covariate pattern, unattainable in practice). With small samples, intercept and slope are enough; with adequate samples, add the smoothed curve.
Do not judge calibration by the Hosmer-Lemeshow test
The same paper notes that the H-L test uses artificial risk groups, its P value says nothing about the direction or size of miscalibration, and it has low power; in large samples it flags trivial deviations. Report the calibration intercept, slope and curve instead.
DCA thresholds and reading the curve
Net benefit = sensitivity × prevalence − (1 − specificity) × (1 − prevalence) × pt/(1 − pt), where pt is the threshold probability. Vickers et al. (2019) describe two common misreadings: using the decision curve to pick the threshold (the threshold range should come first, from the harms and benefits of the intervention), and not comparing with both "treat all" and "treat none". If the model is best only over part of the range, limit the conclusion to that range.
High AUC does not imply high net benefit
Net benefit reflects both discrimination and calibration. When resampling or overfitting inflates risks, net benefit at common thresholds can fall below "treat all" even if AUC is unchanged. Compute DCA from externally validated or cross-validated predictions.
When external validation looks worse
Look at discrimination and calibration separately. A small drop in AUC with an off calibration intercept points to a different baseline risk, which an intercept update can fix; a calibration slope well below 1 points to overfitting at development, addressed by logistic recalibration of intercept and slope. TRIPOD+AI item 12f asks how the model was updated.
Explanation
Christodoulou et al. (2019) systematically reviewed 282 comparisons of logistic regression with machine learning from 71 studies.
In the 145 comparisons with low risk of bias, the difference in logit(AUC) was 0.00 (95% CI −0.18 to 0.18). In the 137 with high risk of bias, machine learning was higher by 0.34, which the authors attributed to flawed validation.
79% of the studies did not evaluate calibration.
Reference and appendix
Reference
Every step that uses the outcome or the data distribution is part of model development and must be redone within each training fold or bootstrap sample during internal validation. Missing one step makes the validation optimistic.
A diagnostic model predicts whether a condition is present now; a prognostic model predicts whether an outcome will occur within some future time. The prediction time point and the usable variables differ between the two.
The PROBAST predictors domain asks whether all predictors are available at the time the model is intended to be used, and rates risk of bias as high when they are not.
| Step | Recommended practice | Redone in each resample? | Common error |
|---|---|---|---|
| Define the prediction question | State the target population, prediction time point, outcome and horizon; use only variables available at the prediction time point | — | Using post-operative or follow-up information to predict a pre-operative decision |
| Sample size | Calculate with pmsampsize from the number of candidate parameters and report it in the methods | — | Reporting EPV only, or computing EPV from the variables finally selected |
| Missing data | Multiple imputation or in-model handling; fit the imputation model on training data only | Yes | Dropping incomplete cases without reporting the proportion |
| Continuous variables | Keep them continuous; model non-linearity with restricted cubic splines (rcs) | — | Dichotomising at the median or an "optimal" ROC cut-off |
| Variable selection | LASSO, or pre-specification from literature and clinical knowledge | Yes | Selecting on all data and then splitting into training and validation sets |
| Scaling | Fit scaling parameters on the training fold and apply them to the test fold | Yes | Scaling all data at once |
| Class imbalance | Usually leave it; if corrected, apply only to training folds and recalibrate | Yes | Running SMOTE before the split |
| Tuning | Choose hyperparameters with inner cross-validation | Yes (nested) | Using one cross-validation both to tune and to report performance |
| Internal validation | Bootstrap optimism correction or nested cross-validation | — | Reporting training AUC only; a random 70:30 split in a modest sample |
| Evaluation | Discrimination + calibration + DCA, each with 95% CI | — | AUC only; the Hosmer-Lemeshow test in place of a calibration curve |
| External validation | Temporally or geographically independent data with coefficients and cut-offs held fixed | — | Refitting coefficients or re-deriving cut-offs in the validation set |
| Reporting | TRIPOD+AI 27 items; share code | — | Not reporting the tuning grid, random seeds and software versions |
Reference
cv.glmnet assigns folds at random. Its help page states that "the results of cv.glmnet are random, since the folds are selected at random" and that users can reduce this randomness by running cv.glmnet many times and averaging the error curves. The table below, from one dataset, shows how large the seed effect is.
Measured results on the SUPPORT data (1,000 patients, 253 in-hospital deaths, 30 candidate parameters) are shown below.
| Approach | Variables selected | Distinct variable sets | Notes |
|---|---|---|---|
| lambda.min, 100 random seeds | 19–21 | 3 | lambda.min ranged 0.00566–0.00989 |
| lambda.1se, 100 random seeds | 10–18 (median 12) | 7 | The most frequent set appeared 37 times; lambda.1se ranged 0.0157–0.0399 |
| Error curve averaged over 100 fold assignments | lambda.min 21; lambda.1se 12 | 1 | The result no longer depends on a single seed |
| 100 bootstrap resamples, lambda.1se | — | 98 | scoma, pafi and alb selected 100 times; hrt and bili 99; crea 98; age 56; urine 51 |
| Same folds, standardize = FALSE | 8 (12 when TRUE) | — | Variables with wide ranges (such as urine output) are kept more easily; the composition changes |
Reference
| Measure | Question answered | R | Python | Interpretation |
|---|---|---|---|---|
| AUC / C statistic with 95% CI | Does the model separate people with and without the outcome? | pROC::roc, ci.auc (DeLong) | sklearn.metrics.roc_auc_score + bootstrap CI | 0.5 is chance; a lower value at external validation than at development is common and must be reported |
| Comparing two AUCs | Is the new model better? | pROC::roc.test (paired DeLong) | Bootstrap CI of the difference | For nested models (new model = old model + new variables), Demler et al. (2012) showed the DeLong test has incorrect size |
| Calibration intercept (calibration-in-the-large) | Does the mean predicted risk equal the observed rate? | rms::val.prob | statsmodels logistic regression with logit(p) as offset | Target 0; negative means overestimation |
| Calibration slope | Are predictions too extreme? | rms::val.prob | Logistic regression with logit(p) as the only covariate | Target 1; below 1 means overfitting and predictions that are too extreme |
| Smoothed calibration curve | Do predictions agree with observations across risk levels? | rms::val.prob, calibrate | sklearn CalibrationDisplay (binned) | About 200 events and 200 non-events are needed for stability |
| Brier score | Overall error of probability predictions | rms::val.prob | sklearn brier_score_loss | Depends on prevalence; use it to compare models within one dataset |
| Decision curve (DCA) | Over a reasonable threshold range, is deciding with the model better than treating all or none? | dcurves::dca | No official Python dcurves; compute from the formula | Fix the threshold range in advance from the clinical context |
Reference
library(pmsampsize) # 1.1.3
pmsampsize(type = "b", cstatistic = 0.70, parameters = 30, prevalence = 0.253)
#> Final 2732, 692 events, EPP = 23.04
# Time-to-event: Cox-Snell R2 0.10, 15 parameters, event rate 0.08 per person-year, 3-year horizon, mean follow-up 4 years
pmsampsize(type = "s", csrsquared = 0.10, parameters = 15, rate = 0.08,
timepoint = 3, meanfup = 4)
#> Final 1274, 408 events, EPP = 27.18| Inputs | Required sample size | Events | EPP (events per parameter) | Binding criterion |
|---|---|---|---|---|
| Prevalence 0.253, C = 0.80, 30 parameters | 1136 | 288 | 9.58 | Shrinkage ≥ 0.9 |
| Prevalence 0.253, C = 0.70, 30 parameters | 2732 | 692 | 23.04 | Shrinkage ≥ 0.9 |
| Prevalence 0.10, C = 0.80, 10 parameters | 762 | 77 | 7.62 | Shrinkage ≥ 0.9 |
| Survival: Cox-Snell R² = 0.10, 15 parameters, event rate 0.08/year, 3 years, mean follow-up 4 years | 1274 | 408 | 27.18 | Shrinkage ≥ 0.9 and precision of 3-year risk |
Reference
TRIPOD+AI (Collins et al., BMJ 2024;385:e078378) has 27 items, covers regression and machine learning models, and supersedes TRIPOD 2015. PROBAST+AI (Moons et al., BMJ 2025;388:e082505) assesses risk of bias, with 16 signalling questions for model development and 18 for model evaluation, and supersedes PROBAST 2019. Check your manuscript against both before submission.
| TRIPOD+AI item | Requirement | Writing tip |
|---|---|---|
| 7 Data preparation | Pre-processing and quality checks, and whether they were similar across groups | State at which step and on which data scaling, batch correction and outlier handling were fitted |
| 10 Sample size | How the study size was arrived at, separately for development and evaluation | Give the pmsampsize inputs and output |
| 11 Missing data | How missing data were handled and why | Report missingness per variable and the imputation model |
| 12a Data use | How the data were used and partitioned | State the internal validation method, number of folds, repeats and bootstrap samples |
| 12b Predictor handling | Functional form, transformation, standardisation | Whether splines were used and whether any variable was dichotomised |
| 12c Model and tuning | Model type, rationale, all model-building steps including hyperparameter tuning, and internal validation method | List the tuning grid, inner cross-validation settings and final hyperparameters |
| 12e Performance measures | Measures and plots for discrimination, calibration and clinical utility | AUC or C-index, calibration intercept and slope, calibration curve, DCA |
| 12f Model updating | For example recalibration | State any intercept or slope update at external validation |
| 13 Class imbalance | Whether used, why, how, and any subsequent recalibration | If none, write "no resampling was performed" |
| 14 Fairness | Approaches to model fairness and rationale | Report performance in key subgroups such as sex and age |
| 18c–18f Open science | Protocol, registration, data and code availability | Post code in a public repository with software versions and random seeds |
| 23a Model performance | Performance estimates with confidence intervals, including key subgroups | Give a 95% CI for every measure |
Reference
The code below uses the survival::pbc data. The outcome is death, and liver transplant is treated as censored.
library(survival); library(glmnet); library(rms); library(timeROC)
d <- na.omit(subset(pbc, !is.na(trt),
select = c(time, status, age, albumin, bili, copper, protime, ast, edema, stage)))
d$death <- as.integer(d$status == 2) # 2 = death; 1 = transplant, treated as censored
d$status <- NULL
# LASSO-Cox: y can be a Surv object (supported since glmnet 4.1)
X <- model.matrix(~ . - time - death, d)[, -1]
set.seed(2026)
cvc <- cv.glmnet(X, Surv(d$time, d$death), family = "cox", type.measure = "C")
coef(cvc, s = "lambda.1se")
# Cox nomogram: surv = TRUE and time.inc equal to the u used later in calibrate
dd <- datadist(d); options(datadist = "dd")
fit <- cph(Surv(time, death) ~ log(bili) + albumin + age + protime + edema,
data = d, x = TRUE, y = TRUE, surv = TRUE, time.inc = 1826)
cox.zph(fit) # proportional hazards assumption
sv <- Survival(fit)
plot(nomogram(fit, fun = list(function(lp) sv(1826, lp)), funlabel = "5-year survival"))
set.seed(2026)
cal <- calibrate(fit, u = 1826, cmethod = "KM", m = 50, B = 200) # the default cmethod = "hare" needs the polspline package
plot(cal)
# Time-dependent ROC and C-index
lp <- predict(fit) # linear predictor; higher means higher risk
tr <- timeROC(T = d$time, delta = d$death, marker = lp, cause = 1,
times = c(730, 1826), iid = TRUE)
tr$AUC; confint(tr)
concordance(Surv(time, death) ~ lp, data = d, reverse = TRUE) # Harrell's C
concordance(Surv(time, death) ~ lp, data = d, reverse = TRUE, timewt = "n/G2") # Uno's CReference
rms validate and calibrate default to B = 40, which varies noticeably between seeds; B = 200 or more is common in papers. For stepwise selection, validate(fit, B = 200, bw = TRUE) repeats backward elimination inside each bootstrap sample; LASSO has no such argument, so write the loop yourself as in the code below.
library(glmnet); library(pROC)
auc_of <- function(p, y) as.numeric(auc(roc(y, p, direction = "<", quiet = TRUE))) # explicit direction
fit_lasso <- function(X, y) cv.glmnet(X, y, family = "binomial", nfolds = 10)
p_of <- function(cv, X) predict(cv, X, s = "lambda.1se", type = "response")[, 1]
cv0 <- fit_lasso(X, y)
apparent <- auc_of(p_of(cv0, X), y) # apparent AUC: same data for fitting and evaluation
set.seed(2026)
opt <- replicate(200, {
i <- sample(nrow(X), replace = TRUE)
cvb <- fit_lasso(X[i, ], y[i]) # selection and lambda choice are redone in every bootstrap sample
auc_of(p_of(cvb, X[i, ]), y[i]) - auc_of(p_of(cvb, X), y)
})
c(apparent = apparent, optimism = mean(opt), corrected = apparent - mean(opt))Reference
scikit-learn's LogisticRegression applies an L2 penalty with C = 1 by default. When a paper's "logistic regression" baseline is fitted with scikit-learn 1.8 or later, set C = np.inf for an unpenalised model. From 1.8 the penalty argument is deprecated and scheduled for removal in 1.10; L1 is written l1_ratio = 1, and the penalty = "l1" in older tutorials raises a deprecation warning.
In R, predict(rf) without newdata returns out-of-bag (OOB) predictions, which are close to unbiased; predict(rf, newdata = training data) returns predictions from all trees, and the training AUC approaches 1. When reporting "training performance" for a random forest, state which one was used.
In scikit-learn, passing an integer random_state to a cross-validation splitter gives every model the same folds, so folds can be compared one by one; passing an integer to an estimator (such as a random forest) gives every fold the same random state. The documentation recommends integers for splitters and, when comparing algorithms, a RandomState instance or no value for estimators.
Reference
The points below come from Zhihu columns, "Xiaobai Xue Tongji" articles republished by Mediecogroup, and a bioinformatics tutorial on cnblogs, checked against English methodological literature and software documentation. Templated CSDN tutorials and an article with fabricated reviewer comments were excluded.
The V in EPV means parameters
Jin Shuai (Zhihu, 2022) and Xiaobai Xue Tongji (Mediecogroup, 2024) both stress that a multi-category variable corresponds to several dummy parameters and that non-linear and interaction terms also count; some simulations suggest 20 to 50 EPP. This matches the definition of parameters in the pmsampsize documentation.
Reference numbers for external validation
Jin Shuai cites Pavlou et al. (2021): with C between 0.64 and 0.85 and event rates between 0.05 and 0.30, keeping the standard error of C at validation below 0.025 needs 60 to 170 events; Snell et al. (2021) recommend at least 200 events. This points the same way as Riley 2024: the 100-event rule is too low.
A fixed 0.05 margin is not always appropriate
When introducing the Riley method, Xiaobai Xue Tongji notes that an intercept margin of 0.05 and an R² difference of 0.05 are generic settings, that applying them uniformly is not reasonable, and that clinical knowledge and prior literature should guide them. For example, when the outcome rate is only 5%, an overall risk margin of ±0.05 is as large as the rate itself.
Three errors in a TCGA LASSO tutorial
A cnblogs TCGA LASSO tutorial says "if the result is not ideal, change the seed" and states that cv.glmnet uses 20 folds by default. The default nfolds in cv.glmnet is 10, and picking seeds is data snooping (see the LASSO section). The tutorial is titled as a survival model but uses family = "binomial"; it should use a Surv object with family = "cox".
glmnet defaults to lambda.1se
The Zhihu column "Thoughts on LASSO regression and feature selection" (2020) notes that glmnet uses 1se by default when predicting, which matches the default of s in the predict.cv.glmnet help. Readers who copied coef(cvfit) should check which lambda they actually reported.
Troubleshooting by error or symptom
Each entry is titled with the symptom or error message a reader sees, and the cause and fix sit together. The rms error text is taken from the stop() calls in rms 8.1.1 source.
Training AUC is 0.95, but validation AUC is only 0.70.
Cause: The model is overfitted, or a step has inflated the training result, for example scaling or selection done before the split.
Fix: Check that selection, scaling, imputation and resampling all happen inside the training folds. Report nested cross-validation or bootstrap-corrected results in the paper, not the training AUC.
Differential analysis, LASSO or univariable tests were run on all the data before splitting or cross-validation, and the AUC is clearly high.
Cause: Selection used the outcome of the test samples, which is selection bias. In a scikit-learn example with 200 samples and 10,000 pure-noise features, selecting 25 features with SelectKBest(k=25) before cross-validation gave accuracy 0.76, when the correct value is 0.5. Ambroise and McLachlan (2002) repeated the procedure on colon cancer data with randomly permuted labels: under selection bias the cross-validation error was close to 0, while correct external cross-validation gave 0.40–0.45.
Fix: Put the selection inside a Pipeline or inside each training fold. The independent validation set takes no part in the modelling at any stage.
Scaling, imputation or batch correction was done on all the data before the samples were split.
Cause: Means, variances or imputation information from the test samples entered the training. The size of the bias depends on the data.
Fix: Fit the scaler and the imputation model on the training folds, then apply them to the test fold.
SMOTE or undersampling was done before the split, and the cross-validation score is higher than the score on the held-out data.
Cause: Synthetic samples carry information from the test set. In the imbalanced-learn official example, cross-validation after sampling gave a balanced accuracy of 0.724, while the held-out data gave 0.698; with the sampler inside a Pipeline the two values were 0.732 and 0.727.
Fix: Keep the sampler only inside the training folds, and use imblearn.pipeline.Pipeline. The correct way to write it is in the code below.
from imblearn.pipeline import Pipeline # the imblearn Pipeline; the sklearn Pipeline does not accept samplers
from imblearn.over_sampling import SMOTE
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import StratifiedKFold, cross_val_score
pipe = Pipeline([("sc", StandardScaler()),
("smote", SMOTE(random_state=0)), # applied to each training fold only; test folds keep the original distribution
("clf", LogisticRegression(max_iter=1000))])
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=0)
print(cross_val_score(pipe, X, y, cv=cv, scoring="roc_auc").mean())
# Predicted probabilities are inflated after resampling; recalibrate on data with the original distribution before reporting risks (TRIPOD+AI item 13)The same cross-validation was used both for tuning and for reporting performance, and the result is clearly better than on independent data.
Cause: Tuning picked the hyperparameters that did best in this cross-validation, so the error estimate is optimistic. Varma and Simon (2006) found, on simulated data with no real signal, that after tuning 18.5% of the training sets had a cross-validation error below 30%.
Fix: Use nested cross-validation instead: the inner loop tunes, and the outer loop estimates performance.
LASSO selects different variables each time the same data are run.
Cause: cv.glmnet assigns folds at random, and different seeds can give different variable sets. In this page's measurements over 100 seeds, lambda.1se gave 7 different variable sets.
Fix: Fix foldid and make it public so the analysis can be reproduced. Then average the error curve over many fold assignments, or report bootstrap selection frequencies to show stability. The code below gives the stability check and the averaged error curve.
# Selection stability: one cross-validation per seed for 100 seeds, count how often each variable is selected
sel <- sapply(1:100, function(s) {
set.seed(s)
b <- coef(cv.glmnet(X, y, family = "binomial", nfolds = 10), s = "lambda.1se")[-1, 1]
b != 0
})
sort(rowSums(sel), decreasing = TRUE) # selection frequency
length(unique(apply(sel, 2, paste, collapse = ""))) # number of distinct variable sets
# Reduce fold randomness: average the CV error curves of 100 fold assignments on one lambda sequence
lam <- glmnet(X, y, family = "binomial")$lambda
cvm <- sapply(1:100, function(s) {
set.seed(s)
cv.glmnet(X, y, family = "binomial", lambda = lam,
foldid = sample(rep(1:10, length.out = nrow(X))))$cvm
})
lam[which.min(rowMeans(cvm))] # lambda.min on the averaged curveSeveral seeds were tried, and only the run whose variables looked best was kept.
Cause: Picking a seed amounts to choosing the most attractive of several variable sets, which is data snooping.
Fix: Fix foldid and make it public in the supplement; or average the error curve over many fold assignments; or report bootstrap selection frequencies.
The text says lambda.min, but the result of coef(cvfit) is different.
Cause: The default value of the s argument in predict.cv.glmnet and coef is "lambda.1se". Many tutorials say lambda.min in the text but write coef(cvfit) without s in the code.
Fix: Always write s explicitly in the code.
After LASSO selects variables, an unpenalised logistic or Cox regression is fitted, and variables with P ≥ 0.05 are removed in another round.
Cause: The second step removes the shrinkage from LASSO, so the coefficients become large again. The variables were chosen by the data, so the P values and confidence intervals of the second step no longer have their nominal meaning (Heinze et al., 2018).
Fix: For prediction, use the LASSO coefficients directly. If unshrunken coefficients are needed, use relax = TRUE in glmnet, and put both steps inside the bootstrap validation.
Only the variables with univariable P < 0.05 were passed into LASSO.
Cause: Univariable screening misses predictors hidden by confounding, and it forces the later validation to repeat this step (Sun et al., 1996). Whether the analysis avoided selecting predictors by univariable analysis is one of the signalling questions in the PROBAST analysis domain.
Fix: Set the candidate variables in advance from the literature and clinical knowledge, and put all of them into LASSO.
The number of selected variables changes clearly after setting standardize = FALSE.
Cause: The penalty treats variables in different units unequally. Variables with a large range (such as urine output) are more likely to be kept, and dummy variables are affected too, so rare categories are harder to select.
Fix: Keep the default standardize = TRUE. If dummy variables need separate handling, adjust them with penalty.factor.
The analysis sample is much smaller than the raw data, and the methods do not report the proportion missing.
Cause: Deleting incomplete cases directly, without reporting the proportion deleted, introduces bias.
Fix: Count the proportion missing for each variable, fill the gaps with multiple imputation, and describe the handling in the methods.
A continuous variable was split into two groups at the median or at the ROC optimal cut-off before modelling.
Cause: Dichotomising loses information contained in the continuous variable.
Fix: Keep continuous variables continuous, and model non-linear relations with restricted cubic splines (rcs).
SMOTE or undersampling was used, and the calibration curve is clearly off the diagonal.
Cause: Resampling changes the outcome proportion of the training data, so the predicted probabilities are generally too high.
Fix: Recalibrate on data with the original distribution, and state this in the paper (TRIPOD+AI item 13).
The training-set AUC of a random forest is close to 1.
Cause: In R, predict(rf) without newdata returns out-of-bag (OOB) predictions, which are nearly unbiased. With newdata = the training set it returns predictions from all trees, and the AUC then approaches 1.
Fix: Report the OOB or cross-validated results. When reporting training-set performance, state which kind of prediction was used.
XGBoost is fitted with its default hyperparameters on a small sample: learning_rate 0.3 and max_depth 6.
Cause: This is one of the common misuses listed in the algorithm choice table.
Fix: Tune the learning rate and tree depth inside the inner cross-validation, using the starting points in the algorithm choice table.
For an SVM with probability=True, predict and predict_proba give different results.
Cause: The probabilities come from an internal 5-fold Platt calibration, which may disagree with the class decision made by predict.
Fix: When probabilities are needed, use predict_proba and evaluate its calibration. Do not plot a calibration curve from decision_function as if it were a probability.
A warning that the penalty argument is deprecated appears when running penalty="l1" in scikit-learn 1.8 or later.
Cause: LogisticRegression uses an L2 penalty with C=1 by default. The penalty parameter has been deprecated since 1.8 and is planned for removal in 1.10.
Fix: Write L1 as l1_ratio=1. For an unpenalised logistic baseline, set C=np.inf.
The paper reports only the AUC, and a reviewer says calibration and clinical utility are missing.
Cause: The AUC alone cannot show whether predicted probabilities are accurate or whether decisions give net benefit. TRIPOD+AI item 12e asks for discrimination, calibration and clinical utility.
Fix: Add the calibration intercept, the calibration slope, a smoothed calibration curve and DCA, with 95% CIs.
Only the P value of the Hosmer-Lemeshow test is reported, and the reviewer asks for other calibration measures.
Cause: The H-L test groups the data arbitrarily, its P value does not show the direction or size of the miscalibration, and its power is low. In large samples it is over-sensitive to tiny deviations.
Fix: Report the calibration intercept, the calibration slope and the calibration curve.
Reviewer comment: the 30% randomly split from the same dataset is called "external validation".
Cause: A part split at random has the same source as the development set, so it is not independent data.
Fix: If independent data can be found, do temporal or geographic validation. If not, use bootstrap correction or nested cross-validation as internal validation, do not write "validated the generalisability of the model" in the title or abstract, and state the limitation.
The cut-off is re-derived on the validation set, the coefficients are refitted, or the validation set is split at its median into risk groups, and the result is reported as validation.
Cause: This is re-modelling on the validation set, so it cannot be called validation.
Fix: Fix the coefficients, cut-offs and risk-group boundaries on the development set, then apply them unchanged to the validation data.
roc() is called without direction, and the AUC of a resampling result is high.
Cause: The direction of pROC defaults to "auto". With resampling or randomisation, this inflates the AUC.
Fix: Set direction = "<" or ">" explicitly.
Several records from the same patient fall into both the training and the test set, and the test performance is very high.
Cause: The model memorises individual characteristics, so the test performance is inflated.
Fix: Split by patient, for example with GroupKFold.
LASSO, SVM-RFE and random forest were each run on the same GEO dataset, the intersection gave 3 to 5 genes, and the ROC drawn on the same dataset has an AUC often above 0.9.
Cause: All three algorithms saw the outcome of every sample, and the intersection only reduces the number of genes, so selection bias remains. The random-label experiment of Ambroise and McLachlan shows that pure noise can also give an error close to 0 in this kind of pipeline.
Fix: Put the whole pipeline (differential analysis, the three algorithms, the intersection, the model) inside every round of the outer cross-validation or bootstrap, and report the outer performance and each gene's selection frequency. Alternatively, in an independent cohort (from a different centre or time, preferably a different platform), fix the genes, coefficients and cut-offs and only predict and evaluate.
The coefficients from TCGA are applied directly to GEO array data, and the absolute values of the risk scores cannot be compared.
Cause: Different platforms have expression values on different scales, so the same coefficients give outputs that are not comparable across them.
Fix: Z-score each gene within each cohort, then evaluate discrimination. Calibration needs the baseline risk re-estimated in the new cohort, and this must be reported in the paper.
Patients are split into high- and low-risk groups at the training-set median risk, a Kaplan-Meier curve is drawn, and the log-rank P value between groups is used as evidence of predictive accuracy.
Cause: A median split loses information, and the log-rank P value between groups does not measure predictive accuracy.
Fix: Report the C-index, the time-dependent AUC and calibration on the continuous risk score.
The title says survival model, but the code fits death or not with family = "binomial".
Cause: This discards the information on follow-up time.
Fix: Give y as a Surv object, set family to "cox", and set type.measure to "C".
A tutorial says cv.glmnet uses 20 folds by default and suggests that "if the result is not ideal, you can change the seed".
Cause: The default nfolds in cv.glmnet is 10. Changing the seed is data snooping.
Fix: Write nfolds explicitly, fix foldid, and report stability. See the LASSO section.
variable xxx does not have limits defined in fit or with datadist
Cause: datadist was not set before fitting, or it was built from a different data frame from the one used for modelling, or the formula contains dat$x.
Fix: Run dd <- datadist(dat); options(datadist = "dd") first, write only column names in the formula, and use the data = argument.
did not use surv=TRUE for cph( )
Cause: calibrate and the survival estimates need the model to store the survival estimates.
Fix: Fit with cph(..., surv = TRUE, x = TRUE, y = TRUE, time.inc = u).
fit did not use x=TRUE,y=TRUE
Cause: validate and calibrate need the design matrix and the outcome.
Fix: Add x = TRUE, y = TRUE to lrm or cph.
when lp.at is not specified you must specify x=TRUE in the fit
Cause: The nomogram needs the design matrix to set the range of the linear predictor.
Fix: Add x = TRUE when fitting.
Reviewer comment: what is the basis of the sample size? The EPV is only 5.
Cause: The paper cites only EPV ≥ 10 and does not calculate the sample size from a target precision.
Fix: Give the Riley method result. If the sample is too small, state that the number of candidate parameters was reduced and penalised regression was used, and report the bootstrap-corrected calibration slope.
Reviewer comment: why use machine learning, and was it compared with logistic regression?
Cause: The paper gives no comparison with a baseline model.
Fix: Report the discrimination, calibration and DCA of a baseline logistic or Cox model with splines under the same nested cross-validation. If the difference is small, say so, and explain the reason for the choice, such as interpretability or deployment.
Reviewer comment: are the feature genes just a product of overfitting?
Cause: The paper reports only the selection result, without the stability under resampling or independent validation.
Fix: Report the selection frequencies under resampling, show the performance of the whole selection pipeline in the outer loop, and show the performance of the fixed model in an independent cohort. Functional experiments answer biological questions and do not replace validation of predictive performance.
The variables ranked highest in the SHAP plot are not important in independent data.
Cause: SHAP was computed on the training set, where the noise learned through overfitting also appears as important features.
Fix: Compute SHAP on the test set or on the outer folds.
The paper describes a variable with a high SHAP value as a "risk factor" or a "therapeutic target".
Cause: SHAP shows the correlations the model uses, and cannot support conclusions about the effect of an intervention.
Fix: Describe only the contribution within the model, and do not write it as a causal conclusion.
References
- Collins GS, et al. TRIPOD+AI statement. BMJ 2024;385:e078378 — 27-item reporting checklist; items 7, 10–14, 18 and 23a
- Moons KGM, et al. PROBAST+AI. BMJ 2025;388:e082505 — Risk of bias and applicability; 16 development and 18 evaluation signalling questions
- Wolff RF, et al. PROBAST. Ann Intern Med 2019;170:51-58 — Original risk-of-bias tool; bias from univariable selection and dichotomisation
- Riley RD, et al. Calculating the sample size required for developing a clinical prediction model. BMJ 2020;368:m441 — Criteria and steps for development sample size
- pmsampsize 1.1.3 reference manual (CRAN) — Argument definitions and examples; cstatistic should be optimism-adjusted
- Riley RD, et al. Evaluation of clinical prediction models (part 3): sample size for external validation. BMJ 2024;384:e074821 — Four criteria for external validation sample size and the 949-patient example
- van Smeden M, et al. Sample size for binary logistic prediction models: beyond events per variable criteria. Stat Methods Med Res 2019 — EPV is weakly related to prediction error
- Peduzzi P, et al. A simulation study of the number of events per variable in logistic regression analysis. J Clin Epidemiol 1996 — Origin of EPV ≥ 10
- van der Ploeg T, Austin PC, Steyerberg EW. Modern modelling techniques are data hungry. BMC Med Res Methodol 2014 — EPV needed by random forest, SVM and neural networks
- Riley RD, et al. Penalization and shrinkage methods produced unreliable clinical prediction models especially when sample size was small. J Clin Epidemiol 2021 — Uncertainty of penalty parameters in small samples
- Christodoulou E, et al. A systematic review shows no performance benefit of machine learning over logistic regression. J Clin Epidemiol 2019 — 282 comparisons; no difference at low risk of bias
- Heinze G, Wallisch C, Dunkler D. Variable selection – a review and recommendations for the practicing statistician. Biom J 2018 — Post-selection inference and the two-step problem
- Sun GW, Shook TL, Kay GL. Inappropriate use of bivariable analysis to screen risk factors. J Clin Epidemiol 1996 — Problems with univariable screening
- glmnet documentation: An Introduction to glmnet — Default standardize; definitions of lambda.min and lambda.1se
- van den Goorbergh R, et al. The harm of class imbalance corrections for risk prediction models. JAMIA 2022 — Undersampling, oversampling and SMOTE harm calibration without improving AUC
- imbalanced-learn: Common pitfalls and recommended practices — Resampling leakage example and Pipeline use
- scikit-learn: Common pitfalls and recommended practices — Feature-selection leakage example (0.76 vs 0.5) and random_state advice
- Ambroise C, McLachlan GJ. Selection bias in gene extraction on the basis of microarray gene-expression data. PNAS 2002 — Near-zero cross-validated error under selection bias with permuted labels
- Varma S, Simon R. Bias in error estimation when using cross-validation for model selection. BMC Bioinformatics 2006 — Bias of tuned cross-validation error and nested cross-validation
- Harrell F. Split-Sample Model Validation (blog) — Split-sample instability below about 20,000; about 100 repeats of 10-fold match the bootstrap
- Van Calster B, et al. Calibration: the Achilles heel of predictive analytics. BMC Med 2019 — Calibration hierarchy, intercept and slope, against the H-L test, 200 events
- Vickers AJ, van Calster B, Steyerberg EW. A simple, step-by-step guide to interpreting decision curve analysis. Diagn Progn Res 2019 — Net benefit formula and common misreadings
- Demler OV, Pencina MJ, D'Agostino RB. Misuse of DeLong test to compare AUCs for nested models. Stat Med 2012 — Comparing AUCs of nested models
- XGBoost documentation: Notes on Parameter Tuning — AUC versus probability under class imbalance
- scikit-learn documentation: Support Vector Machines — Platt scaling with probability=True and inconsistencies
- SHAP documentation: Be careful when interpreting predictive models in search of causal insights — SHAP and causal interpretation
- R-help: help with nomogram function (reply by Harrell) — datadist errors and $ in formulas
- Practitioner post: Jin Shuai, minimum sample size for developing and validating clinical prediction models (Zhihu, Chinese) — Parameter counting and external validation sample size
- Practitioner post: Xiaobai Xue Tongji, how to estimate sample size for clinical prediction models (Mediecogroup, Chinese) — Chinese explanation of EPP and the Riley criteria
- Practitioner post: TCGA analysis workflow 3.3, survival model with LASSO (cnblogs, Chinese) — Seed and fold claims that need correction
- Practitioner post: Thoughts on LASSO regression and feature selection (Zhihu, Chinese) — glmnet defaults to lambda.1se