| Title: | Mixed-Effect Extreme Gradient Boosting for Longitudinal Data |
|---|---|
| Description: | Fits mixed-effects extreme gradient boosting models for Gaussian, binary and clustered right-censored survival outcomes. Combines subject-specific random effects with boosted trees and optional penalised linear terms using 'xgboost' and 'glmnet'. Provides within-subject cross-fitting, predictor screening, approximate variance-component estimation, conditional prediction and simulation utilities. Builds on extreme gradient boosting by Chen and Guestrin (2016) <doi:10.1145/2939672.2939785> and mixed-effects gradient boosting by Olaniran et al. (2025) <doi:10.1038/s41598-025-16526-z>. |
| Authors: | Oyebayo Ridwan Olaniran [aut, cre] (ORCID: <https://orcid.org/0000-0001-7342-8639>), Saheed Kunle Ajibade [aut], Samuel Adewale Aderoju [aut] |
| Maintainer: | Oyebayo Ridwan Olaniran <[email protected]> |
| License: | GPL-2 |
| Version: | 1.0.0 |
| Built: | 2026-12-05 20:00:44 UTC |
| Source: | https://github.com/cran/MEXGB |
Uses a large pilot sample (only the active predictors need to be generated) to find the
multiplier of the standardised fixed effect such that the population
(fixed-effect) discrimination equals target:
binomial: the expected AUC of for the outcome
, computed exactly from the event
probabilities (no sampling of ); for each the intercept is solved so that
the mean event probability equals prevalence. The prevalence therefore also enters the AUC.
cox: the expected concordance index of for event times from the frailty model,
with (independent of the baseline hazard).
The target is solved on the finite pilot sample using uniroot; achieved
discrimination describes that pilot, not an exact population guarantee. Unattainable
targets issue a warning. Independent simulation replicates need not attain the target exactly.
calibrateSim( family = c("binomial", "cox"), target, prevalence = 0.5, linear = TRUE, rel_p = 6, time_points = 10, rho_W = 0.6, rho_Z = 0.6, random_sd_intercept = sqrt(0.5), random_sd_slope = sqrt(3), pilot_n = 300, pilot_seed = 1, max_signal = 50 )calibrateSim( family = c("binomial", "cox"), target, prevalence = 0.5, linear = TRUE, rel_p = 6, time_points = 10, rho_W = 0.6, rho_Z = 0.6, random_sd_intercept = sqrt(0.5), random_sd_slope = sqrt(3), pilot_n = 300, pilot_seed = 1, max_signal = 50 )
family |
|
target |
Target AUC (binomial) or concordance (cox), in [0.5, 1). |
prevalence |
binomial target event rate. |
linear, rel_p, time_points, rho_W, rho_Z, random_sd_intercept, random_sd_slope
|
as in |
pilot_n |
number of pilot individuals. |
pilot_seed |
seed of the pilot sample (the global random-number stream is left untouched). |
max_signal |
upper bound of the search for |
list with signal (), intercept (, binomial),
f_mean, f_sd (standardisation of ), achieved (discrimination at the
solution) and target.
calibrateSim("binomial", target = 0.85, prevalence = 0.5, linear = FALSE, pilot_n = 50)calibrateSim("binomial", target = 0.85, prevalence = 0.5, linear = FALSE, pilot_n = 50)
Fits a flexible fixed effect and subject-specific random effects to Gaussian, binary or clustered right-censored survival data. The fixed component combines optional penalised linear terms with extreme gradient boosting, following Chen and Guestrin (2016) doi:10.1145/2939672.2939785.
MEXGB( X, Y, id, Z, iter = 100, ntree = 5000, time, shrinkage = 0.1, interaction.depth = 1, n.minobsinnode = 5, lambda = 1, alpha = 0, gamma = 0, subsample = 1, colsample_bytree = 1, min_child_weight = NULL, family = c("gaussian", "binomial", "cox"), delta = 0.001, stall_iter = 5, eps = 1e-06, crossfit = 5, init = c("auto", "lmm", "zero"), dispersion = c("auto", "additive", "multiplicative", "none"), inner = 50, inner_tol = 1e-04, calibrate = TRUE, calibrate_binomial = TRUE, tree_method = "auto", linear = "auto", lin_alpha = 1, lin_relax = TRUE, screen = c("auto", "none"), screen_iter = 2, zfixed = TRUE, heldout_blup = TRUE, heldout_dscale = TRUE, heldout_offset = TRUE, ntree_select = c("cv", "fixed"), criterion = c("laplace", "working"), estep = c("laplace", "pql"), nthread = 1, seed = 1, verbose = TRUE )MEXGB( X, Y, id, Z, iter = 100, ntree = 5000, time, shrinkage = 0.1, interaction.depth = 1, n.minobsinnode = 5, lambda = 1, alpha = 0, gamma = 0, subsample = 1, colsample_bytree = 1, min_child_weight = NULL, family = c("gaussian", "binomial", "cox"), delta = 0.001, stall_iter = 5, eps = 1e-06, crossfit = 5, init = c("auto", "lmm", "zero"), dispersion = c("auto", "additive", "multiplicative", "none"), inner = 50, inner_tol = 1e-04, calibrate = TRUE, calibrate_binomial = TRUE, tree_method = "auto", linear = "auto", lin_alpha = 1, lin_relax = TRUE, screen = c("auto", "none"), screen_iter = 2, zfixed = TRUE, heldout_blup = TRUE, heldout_dscale = TRUE, heldout_offset = TRUE, ntree_select = c("cv", "fixed"), criterion = c("laplace", "working"), estep = c("laplace", "pql"), nthread = 1, seed = 1, verbose = TRUE )
X |
Finite numeric predictor matrix, with one row per observation and unique column names if supplied. Missing values must be handled before fitting. |
Y |
[vector]: A vector containing the output trajectories (numeric for |
id |
[vector]: Is the vector of the identifiers for the different trajectories. |
Z |
[matrix]: A |
iter |
[numeric]: Maximal number of iterations of the algorithm. The default is set to |
ntree |
Positive integer maximum number of boosting rounds in each fold model. Default 5000. With CV, the selected count may be zero; the full-data count is scaled by V/(V-1) and can exceed this fold-model limit. With fixed selection, exactly ntree rounds are used. |
time |
[vector]: Is the vector of the measurement times associated with the trajectories in |
shrinkage |
[numeric]: a shrinkage parameter applied to each tree in the expansion (the |
interaction.depth |
[numeric]: The maximum depth of each tree (the |
n.minobsinnode |
Leaf-size control mapped to the minimum Hessian weight in a leaf. Default 5. This equals an observation count for Gaussian loss; for other families it is a heuristic, not a guaranteed minimum leaf count. |
lambda |
[numeric]: L2 penalty on the leaf weights ( |
alpha |
[numeric]: L1 penalty on the leaf weights ( |
gamma |
[numeric]: Minimum loss reduction (complexity charge per leaf) required to make a split ( |
subsample |
[numeric]: Row subsampling rate of each tree. Default 1 (deterministic, as |
colsample_bytree |
[numeric]: Column subsampling rate of each tree; useful when |
min_child_weight |
[numeric]: Optional override of the minimum Hessian weight in a leaf. If |
family |
[character]: |
delta |
[numeric]: The algorithm stops when the relative difference in log likelihood between two iterations is smaller than |
stall_iter |
Positive integer: the EM stops when the selection criterion has not
improved for |
eps |
[numeric]: Lower bound for the PQL working weights (binary and cox outcomes). Default |
crossfit |
Number of within-subject folds: 0 (disabled) or an integer from 2 to the number of observations. Default 5. Empty folds, insufficient training rows, binary training folds with one class, and survival training folds without events are rejected. Change seed, reduce folds, or provide more data if necessary. With crossfit = 0 the linear part is not fitted (linear = TRUE gives a warning). |
init |
[character]: Starting values of the EM. |
dispersion |
[character]: residual structure of the PQL working model of binary and cox
outcomes: |
inner |
[numeric]: maximum number of E-step iterations per boosting refit (default 50). The
BLUP / variance-component updates (and, for binary and cox outcomes, the PQL linearisation)
are cheap, so they are iterated to convergence (relative change < |
inner_tol |
[numeric]: convergence tolerance of the inner iterations (default 1e-4). |
calibrate |
[logical]: Enable calibration for binary and Cox cross-fitted models. For Cox: rescale the boosted fixed effect by
its out-of-fold calibration slope (Cox model of the outcome on the out-of-fold linear predictor,
offset |
calibrate_binomial |
Logical; additionally enable binary calibration when calibrate is TRUE. Default TRUE. |
tree_method |
[character]: |
linear |
[logical or |
lin_alpha |
[numeric]: elastic-net mixing parameter of the linear part (1 = lasso). |
lin_relax |
[logical]: also consider relaxed-lasso versions of the linear part (blend of the lasso and of the unpenalised refit on its active set), chosen out of fold. Default |
screen |
[character]: |
screen_iter |
[numeric]: number of EM iterations at which the screening decision is (re)made (default 2: the ranking is reconsidered after the initial random-effect updates). |
zfixed |
[logical]: estimate population coefficients |
heldout_blup |
[logical]: Gaussian with cross-fitting (default |
heldout_dscale |
[logical]: Gaussian with |
heldout_offset |
[logical]: with |
ntree_select |
[character]: |
criterion |
[character]: binary / cox outcomes. |
estep |
Binary/Cox variance update. "laplace" (default) follows PQL with optimization of the approximate criterion; "pql" retains the PQL update. The Laplace-style Cox criterion uses a Poisson working representation. If the optimizer stops at its iteration limit its result is used and the code is recorded in laplace_diagnostics; if it fails (error or non-finite criterion) the PQL update is retained with a warning. These approximations do not establish inferential guarantees. |
nthread |
[numeric]: Number of threads used by |
seed |
Non-negative integer seed for the folds and for supported XGBoost versions. Default 1. With XGBoost 1.x, stochastic tree fitting also uses the caller's R random-number stream. |
verbose |
[boolean]: If TRUE, MEXGB will print out number of iterations to achieve convergence. Default is TRUE. |
The implementation is motivated by mixed-effects tree ensembles, including Hajjem et al. (2014) doi:10.1080/00949655.2012.741599 and Capitaine et al. (2021) doi:10.1177/0962280220946080. It extends the EM/BLUP approach with within-subject cross-fitting, optional linear terms, predictor screening, calibration and approximate non-Gaussian variance-component updates.
The conditional linear predictor is
Gaussian responses use an identity link and independent residual errors given the random effects; binary responses use a logit link; survival responses use a proportional-hazards model with a Breslow baseline hazard. The survival implementation supports clustered right-censored event times, not start-stop records or a longitudinal time-varying-covariate survival likelihood.
Gaussian variance updates use BLUP/EM calculations. Binary and survival updates use PQL, optionally followed by a Laplace-style approximation. The Cox update uses a Poisson working representation and is an approximation rather than a claim of equivalence to a full joint frailty likelihood implementation. Failed Laplace optimization retains the PQL update and records diagnostics.
Cross-fitting distributes observations within subjects. It supports tuning for additional observations from represented subjects, not independent evaluation on unseen subjects or future-time forecasting. Reusing folds for adaptive selection is not external validation. Use an independent test set or nested validation matched to the prediction task for performance reporting. Gaussian screening and covariance shrinkage use a subject-clustered standard-error threshold as a selection heuristic, not a hypothesis test. The returned fit may be an earlier selected iteration rather than the final attempted iteration; the baseline hazard is computed from the returned fit.
A fitted MEXGB model which is a list of the following elements:
forest: List containing the selected booster (possibly NULL), linear coefficients, intercept and predictor indices.
random_effects : Predictions of random effects for different trajectories.
id_btilde: Identifiers of individuals associated with the predictions random_effects.
var_random_effects: Estimation of the variance covariance matrix of random effects.
sigma: Estimation of the residual variance parameter (gaussian) the PQL dispersion ( for dispersion = "multiplicative", when selected; for "additive"; 1 for "none", the default for binomial).
time: The vector of the measurement times associated with the trajectories in Y,Z and X.
LL: Minus twice the approximate log-likelihood criterion at each attempted iteration, up to an additive constant; its definition depends on family and criterion.
id: Vector of the identifiers for the different trajectories.
OOB: Training error of the fitted boosting at each iteration (mean squared error for gaussian, mean deviance for binomial, -2 partial log-likelihood per observation for cox).
importance: Normalised mean absolute combined SHAP and linear contributions when a linear component exists; otherwise normalised split gain. All entries are zero if there is no contribution.
baseline: (cox only) Breslow cumulative baseline hazard (time, cumhaz).
family, converged, n_iter, best_iter: Outcome family and iteration diagnostics.
feature_names, z_names: Training design column names.
ntree, nrounds: Requested fold-model limit and selected full-model tree count.
beta_z: Population coefficients for Z.
laplace_diagnostics: Per-iteration convergence flag, optimizer code and message (NULL when no Laplace update was attempted).
heldout_loss, d_scale: Gaussian held-out loss and selected covariance scale by iteration.
set.seed(1) d <- simLong(n = 8, p = 6, time_points = 4) X <- as.matrix(d[paste0("Var", 1:6)]) Z <- as.matrix(d[c("RandomIntercept", "RandomSlope")]) fit <- MEXGB(X, d$Y, d$id, Z, time = d$time, ntree = 10, iter = 2, inner = 2, crossfit = 2, linear = FALSE, screen = "none", verbose = FALSE) head(predict(fit, X, Z, d$id, d$time)) summary(fit) # Small binary and clustered survival fits; PQL keeps examples inexpensive. db <- simLong(8, 6, time_points = 4, family = "binomial") Xb <- as.matrix(db[paste0("Var", 1:6)]) fb <- MEXGB(Xb, db$Y, db$id, Z, time = db$time, family = "binomial", ntree = 10, iter = 2, inner = 2, crossfit = 0, linear = FALSE, screen = "none", estep = "pql", verbose = FALSE) head(predict(fb, Xb, Z, db$id, db$time)) ds <- simLong(8, 6, time_points = 4, family = "cox", censoring = 0) Xs <- as.matrix(ds[paste0("Var", 1:6)]) fs <- MEXGB(Xs, cbind(ds$Y, ds$status), ds$id, Z, time = ds$time, family = "cox", ntree = 10, iter = 2, inner = 2, crossfit = 0, linear = FALSE, screen = "none", estep = "pql", verbose = FALSE) predict(fs, Xs[1:2, ], Z[1:2, ], ds$id[1:2], ds$time[1:2], type = "survival", times = c(0, 1))set.seed(1) d <- simLong(n = 8, p = 6, time_points = 4) X <- as.matrix(d[paste0("Var", 1:6)]) Z <- as.matrix(d[c("RandomIntercept", "RandomSlope")]) fit <- MEXGB(X, d$Y, d$id, Z, time = d$time, ntree = 10, iter = 2, inner = 2, crossfit = 2, linear = FALSE, screen = "none", verbose = FALSE) head(predict(fit, X, Z, d$id, d$time)) summary(fit) # Small binary and clustered survival fits; PQL keeps examples inexpensive. db <- simLong(8, 6, time_points = 4, family = "binomial") Xb <- as.matrix(db[paste0("Var", 1:6)]) fb <- MEXGB(Xb, db$Y, db$id, Z, time = db$time, family = "binomial", ntree = 10, iter = 2, inner = 2, crossfit = 0, linear = FALSE, screen = "none", estep = "pql", verbose = FALSE) head(predict(fb, Xb, Z, db$id, db$time)) ds <- simLong(8, 6, time_points = 4, family = "cox", censoring = 0) Xs <- as.matrix(ds[paste0("Var", 1:6)]) fs <- MEXGB(Xs, cbind(ds$Y, ds$status), ds$id, Z, time = ds$time, family = "cox", ntree = 10, iter = 2, inner = 2, crossfit = 0, linear = FALSE, screen = "none", estep = "pql", verbose = FALSE) predict(fs, Xs[1:2, ], Z[1:2, ], ds$id[1:2], ds$time[1:2], type = "survival", times = c(0, 1))
Predictions combine the boosted fixed effect with the predicted random effects of the individuals seen during training. For individuals that were not in the training sample the random effects are set to zero while retaining the population coefficients of Z. For binary and survival outcomes this is conditional prediction at zero random effects, not integration over the random-effects distribution.
## S3 method for class 'MEXGB' predict( object, X, Z, id, time, type = c("response", "link", "survival"), times = NULL, ... )## S3 method for class 'MEXGB' predict( object, X, Z, id, time, type = c("response", "link", "survival"), times = NULL, ... )
object |
: a |
X |
[matrix]: matrix of the fixed effects for the new observations to be predicted. |
Z |
[matrix]: matrix of the random effects for the new observations to be predicted. |
id |
[vector]: vector of the identifiers of the new observations to be predicted. |
time |
[vector]: vector of the time measurements of the new observations to be predicted. |
type |
[character]: |
times |
[vector]: time points for |
... |
: low levels arguments (ignored; kept for compatibility with |
Numeric prediction vector, or a matrix with observations in rows and requested times in columns for survival predictions.
# See MEXGB() for fitted-model prediction examples.# See MEXGB() for fitted-model prediction examples.
Print a fitted MEXGB model
## S3 method for class 'MEXGB' print(x, ...)## S3 method for class 'MEXGB' print(x, ...)
x |
A fitted MEXGB model. |
... |
Unused. |
The model, invisibly.
Simulates the design of the MEXGB papers. Each of the n individuals is observed at
time_points equally spaced occasions rescaled to . The p
fixed-effect predictors of every observation are drawn from with AR(1)
correlation ; only the first six are active.
linear: .
nonlinear: .
A correlated random intercept and slope with
, , enters through
.
family="gaussian": with
within-subject AR(1) errors .
family="binomial": ,
, where is the standardised fixed effect.
The signal strength and intercept are either supplied (signal,
intercept) or calibrated by calibrateSim so that the pilot-sample expected fixed-effect
AUC approximates target_auc and the event rate equals prevalence. Without a target the
original design is used (, solved so that the mean event probability equals
prevalence).
family="cox": frailty Cox model with Weibull baseline,
, ;
is supplied or calibrated so that the population (fixed-effect) concordance index
approximates target_c. Exponential censoring is calibrated on the realised sample,
so its rate is sample-dependent and is not an independently fixed censoring DGP.
Rows represent clustered event times, not repeated records of a single terminal event.
simLong( n, p, rel_p = 6, time_points = 10, rho_W = 0.6, rho_Z = 0.6, random_sd_intercept = sqrt(0.5), random_sd_slope = sqrt(3), noise_sd = 0.5, linear = TRUE, family = c("gaussian", "binomial", "cox"), target_auc = NULL, prevalence = 0.5, target_c = NULL, signal = NULL, intercept = NULL, censoring = 0.3, weibull_shape = 1.5, weibull_scale = 1, pilot_n = 300, pilot_seed = 1, calibration = NULL )simLong( n, p, rel_p = 6, time_points = 10, rho_W = 0.6, rho_Z = 0.6, random_sd_intercept = sqrt(0.5), random_sd_slope = sqrt(3), noise_sd = 0.5, linear = TRUE, family = c("gaussian", "binomial", "cox"), target_auc = NULL, prevalence = 0.5, target_c = NULL, signal = NULL, intercept = NULL, censoring = 0.3, weibull_shape = 1.5, weibull_scale = 1, pilot_n = 300, pilot_seed = 1, calibration = NULL )
n |
Integer number of individuals, at least 2. |
p |
Positive integer number of predictors ( |
rel_p |
[numeric]: Number of relevant predictors in the linear model (coefficients recycled from |
time_points |
Integer number of realizations per individual, at least 2. The default value is |
rho_W |
AR(1) correlation strictly between -1 and 1, among predictors and within-subject errors. The default value is |
rho_Z |
Correlation between -1 and 1 (inclusive) between the random intercept and slope. The default value is |
random_sd_intercept |
[numeric]: Standard deviation of the random intercept. Default |
random_sd_slope |
[numeric]: Standard deviation of the random slope. Default |
noise_sd |
[numeric]: Residual standard deviation |
linear |
[boolean]: If TRUE, the linear fixed effect is simulated, otherwise the nonlinear one. |
family |
[character]: |
target_auc |
[numeric]: binary only; target AUC in [0.5, 1) of the fixed effect (e.g. 0.85). |
prevalence |
Binary target event rate strictly between 0 and 1 (default 0.5). |
target_c |
[numeric]: cox only; target concordance in [0.5, 1) of the fixed effect (e.g. 0.75). |
signal, intercept
|
[numeric]: optional fixed values of |
censoring |
Cox target censored fraction in [0, 1) (default 0.3). |
weibull_shape, weibull_scale
|
[numeric]: cox only; Weibull baseline |
pilot_n |
[numeric]: number of individuals in the pilot sample used by the calibration (default 300). |
pilot_seed |
[numeric]: seed of the pilot sample (the calibration is therefore identical across replicates and does not disturb the random-number stream). |
calibration |
[list]: optional output of |
A data frame with n*time_points rows and p+5 columns (p+6 for Cox) containing the following elements:
id: vector of the individual IDs.
time: vector of the time realizations (rescaled to [0,1]).
Y: vector of the outcomes variable (observed survival time for cox).
RandomIntercept: vector of the Random Intercept design (ones).
RandomSlope: vector of the Random Slope design (time).
Vars : Remainder columns corresponding to the fixed effect variables.
status : (cox only, last column) event indicator.
The true fixed effect, the true linear predictor (binary, cox), the true random effects and the
calibration are returned as attributes f, eta, b and calibration.
set.seed(1) data = simLong(n = 20, p = 6, rel_p = 6, time_points = 10, rho_W = 0.6, rho_Z = 0.6, random_sd_intercept = sqrt(0.5), random_sd_slope = sqrt(3), noise_sd = 0.5, linear = FALSE) # Generate the data head(data) # first six rows of the data. # binary outcome with population AUC 0.85 and prevalence 0.3 datab <- simLong(n = 20, p = 6, time_points = 10, linear = FALSE, family = "binomial", target_auc = 0.85, prevalence = 0.3) mean(datab$Y); attr(datab, "calibration") # clustered survival outcome with concordance 0.75 and 30% censoring datas <- simLong(n = 20, p = 6, time_points = 10, linear = TRUE, family = "cox", random_sd_intercept = sqrt(0.5), random_sd_slope = sqrt(0.5), target_c = 0.75, censoring = 0.3, pilot_n = 50) mean(datas$status)set.seed(1) data = simLong(n = 20, p = 6, rel_p = 6, time_points = 10, rho_W = 0.6, rho_Z = 0.6, random_sd_intercept = sqrt(0.5), random_sd_slope = sqrt(3), noise_sd = 0.5, linear = FALSE) # Generate the data head(data) # first six rows of the data. # binary outcome with population AUC 0.85 and prevalence 0.3 datab <- simLong(n = 20, p = 6, time_points = 10, linear = FALSE, family = "binomial", target_auc = 0.85, prevalence = 0.3) mean(datab$Y); attr(datab, "calibration") # clustered survival outcome with concordance 0.75 and 30% censoring datas <- simLong(n = 20, p = 6, time_points = 10, linear = TRUE, family = "cox", random_sd_intercept = sqrt(0.5), random_sd_slope = sqrt(0.5), target_c = 0.75, censoring = 0.3, pilot_n = 50) mean(datas$status)
Relative influence of the predictors in a fitted MEXGB model.
## S3 method for class 'MEXGB' summary(object, top = NULL, ...)## S3 method for class 'MEXGB' summary(object, top = NULL, ...)
object |
: a |
top |
[numeric]: number of predictors to return (default all predictors with non-zero influence). |
... |
: not used. |
A data frame with columns var and rel.inf (percentage of the total
contribution), sorted by decreasing influence. With a linear component, importance
combines mean absolute SHAP and centred linear contributions; without one it
uses split gain. An empty data frame is returned when all contributions are zero.