Package {MEXGB}


Type: Package
Title: Mixed-Effect Extreme Gradient Boosting for Longitudinal Data
Version: 1.0.0
Maintainer: Oyebayo Ridwan Olaniran <rid4stat@yahoo.com>
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>.
License: GPL-2
Encoding: UTF-8
Depends: R (≥ 4.1.0)
Imports: stats, utils, xgboost (≥ 1.7.0), MASS, survival, glmnet
Suggests: testthat (≥ 3.0.0), knitr, rmarkdown
VignetteBuilder: knitr
Config/testthat/edition: 3
NeedsCompilation: no
RoxygenNote: 7.3.1
Packaged: 2026-11-12 23:51:23 UTC; agent
Author: Oyebayo Ridwan Olaniran ORCID iD [aut, cre], Saheed Kunle Ajibade [aut], Samuel Adewale Aderoju [aut]
Repository: CRAN
Date/Publication: 2026-12-05 14:50:10 UTC

Mixed Effect Extreme Gradient Boosting (MEXGB) Algorithm

Description

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.

Usage

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
)

Arguments

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 family="gaussian"; 0/1 for family="binomial"). For family="cox" a two-column matrix (observed time, event indicator 0/1) or a right-censored survival::Surv object. Counting-process and interval-censored responses are rejected.

id

[vector]: Is the vector of the identifiers for the different trajectories.

Z

[matrix]: A N x q matrix containing the q predictor of the random effects.

iter

[numeric]: Maximal number of iterations of the algorithm. The default is set to iter=100

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 Y,Z and X.

shrinkage

[numeric]: a shrinkage parameter applied to each tree in the expansion (the xgboost learning rate eta). Default 0.1 (MEXGB <= 0.4: 0.05).

interaction.depth

[numeric]: The maximum depth of each tree (the xgboost parameter max_depth). The default value is set to 1.

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 (xgboost parameter lambda). Default 1.

alpha

[numeric]: L1 penalty on the leaf weights (xgboost parameter alpha). Default 0.

gamma

[numeric]: Minimum loss reduction (complexity charge per leaf) required to make a split (xgboost parameter gamma). Default 0.

subsample

[numeric]: Row subsampling rate of each tree. Default 1 (deterministic, as bag.fraction = 1 in MEGB).

colsample_bytree

[numeric]: Column subsampling rate of each tree; useful when p >> n. Default 1.

min_child_weight

[numeric]: Optional override of the minimum Hessian weight in a leaf. If NULL (default) it is n.minobsinnode for family="gaussian" and n.minobsinnode/4 for binary and Cox outcomes (a heuristic; for binary outcomes the Bernoulli Hessian is at most 1/4).

family

[character]: "gaussian" (continuous outcome, default), "binomial" (binary outcome) or "cox" (right-censored time-to-event outcome; mixed-effects (frailty) Cox model).

delta

[numeric]: The algorithm stops when the relative difference in log likelihood between two iterations is smaller than delta. The default value is set to 0.001

stall_iter

Positive integer: the EM stops when the selection criterion has not improved for stall_iter consecutive iterations and returns the best iteration (a safeguard for stochastic boosting). Inf disables it. Default 5. Selection uses the Gaussian held-out loss when available, otherwise the chosen likelihood criterion.

eps

[numeric]: Lower bound for the PQL working weights (binary and cox outcomes). Default 1e-6.

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. "auto" (default): "zero" for family = "gaussian", "lmm" otherwise. "lmm": the random effects, their covariance and the residual variance of the mixed model with a constant fixed effect (PQL for binary outcomes; ignored for family = "cox"); "zero": b_i=0, D=I, \sigma^2=1 (MEXGB 0.2).

dispersion

[character]: residual structure of the PQL working model of binary and cox outcomes: "none" V_i=Z_iDZ_i'+W_i^{-1} (MEXGB 0.2); "multiplicative" V_i=Z_iDZ_i'+\phi W_i^{-1} (as MASS::glmmPQL); "additive" V_i=Z_iDZ_i'+\tau^2I+W_i^{-1} (\tau^2: variance of the out-of-fold error of the linear predictor). "auto" (default): "multiplicative" for family = "cox" with the cross-fitted E-step and calibrate = FALSE, "none" otherwise. All families stop and return the best iteration if the likelihood becomes non-finite.

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) for the current fixed effect before the next boosting refit. inner = 1 gives one step per refit (MEXGB <= 0.3), which stops far from the fixed point because variance-component EM converges slowly.

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 Zb), in the E-step and in prediction (default TRUE). Calibration may improve stability when the fixed-effect predictor is overdispersed; slopes are restricted to [0.05, 1.5].

calibrate_binomial

Logical; additionally enable binary calibration when calibrate is TRUE. Default TRUE.

tree_method

[character]: xgboost tree construction algorithm. "auto" (default) uses the exact greedy algorithm (as gbm) up to 10000 observations and the histogram algorithm above.

linear

[logical or "auto"]: "auto" (default): for family = "gaussian" the fixed effect with and without the linear part is fitted at the first screen_iter M-steps (on all predictors) and the one with the smaller out-of-fold loss is kept, when p>\sqrt{N} (with fewer predictors the linear part is always kept); for the other families "auto" means TRUE. If TRUE the fixed effect is f(x)=a+x^\top\beta+T(x): a penalised linear part (glmnet, elastic-net mixing lin_alpha, lambda and the relaxation chosen on the cross-fitting folds by the out-of-fold deviance) plus boosted trees T grown on top of it. When the signal is linear the out-of-fold selection keeps few or no trees; when it is not, the trees capture the remainder. FALSE: trees only (MEXGB <= 0.4).

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 TRUE. At prediction the linear part is clamped to the range of its fitted values on the training data, so that the unpenalised refit cannot extrapolate for rare predictor values.

screen

[character]: "auto" (default): at the first EM iteration the trees are refitted on the K top-ranked predictors (split gain) of every fold model, K in c(5, 10, 20, 40), and the predictor set (all or top K) with the smallest out-of-fold loss is kept for the following iterations. The ranking of each fold is computed from that fold's own model, so feature ranking excludes the validation rows; selection still requires independent performance evaluation. "none": all predictors.

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 \beta_z for the columns of Z (default TRUE), so that the random effects are deviations with mean zero: the model is f(x)+z^\top\beta_z+z^\top b_i. Without them a population trend in a column of Z that f does not capture is absorbed by the mean of the random effects and inflates D. For family = "cox" the intercept of \beta_z is not identified and is fixed at 0.

heldout_blup

[logical]: Gaussian with cross-fitting (default TRUE): in every out-of-fold loss the random effects of a held-out row are predicted from the other folds' rows of the same individual only (as for a new measurement), and the returned iteration is the one with the smallest held-out squared error when heldout_dscale is also TRUE. This is a tuning criterion, not an unbiased performance estimate.

heldout_dscale

[logical]: Gaussian with heldout_blup = TRUE (default TRUE): after every E-step D is scaled by the factor c in {0, 1/16, 1/8, 1/4, 1/2, 1} that minimises the held-out out-of-fold squared error, used only when it is better than c = 1 by a paired z statistic above 2 (a selection heuristic, not a hypothesis test; c = 1 keeps the EM estimate).

heldout_offset

[logical]: with heldout_blup = TRUE (default TRUE), use the held-out random-effect prediction as the offset of the held-out rows in the out-of-fold losses of the M-step (number of trees, linear part, screening). Not used at the first iteration with init = "zero", where the offset is zero for every row.

ntree_select

[character]: "cv" (default): the number of trees is chosen at every EM iteration as the minimiser of the out-of-fold loss on the cross-fitting folds (0 trees allowed; ntree is then the maximum); "fixed": always ntree trees (MEXGB <= 0.4).

criterion

[character]: binary / cox outcomes. "laplace" (default): the EM is monitored with the Laplace approximation of the marginal log-likelihood, which is comparable between iterations; "working": the PQL working likelihood (MEXGB <= 0.4), which changes with the linearisation point and made the best-iteration rule return early iterations.

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 xgboost. Default 1.

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.

Details

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

\eta_{ij}=f(x_{ij})+z_{ij}^{\top}\beta_z+z_{ij}^{\top}b_i,\quad b_i\sim N(0,D).

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.

Value

A fitted MEXGB model which is a list of the following elements:

Examples

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))


Title

Description

Title

Usage

bay(bhat, Bhat, Z, id, sigmahat)

Update of the random-effects covariance under the PQL working model (internal).

Description

Same as bay with the residual covariance \sigma^2 I replaced by W^{-1}.

Usage

bay_pql(bhat, Bhat, Z, id, w)

Breslow estimator of the cumulative baseline hazard (internal).

Description

Breslow estimator of the cumulative baseline hazard (internal).

Usage

breslow(time, status, eta, at = time)

Arguments

time, status

observed times and event indicators.

eta

linear predictors (log relative hazards).

at

times at which the cumulative baseline hazard is returned (default time).

Value

list with the distinct event times time, the cumulative baseline hazard cumhaz at those times and cumhaz_at evaluated at at.


Calibrate the signal strength (and intercept) of the binary / survival simulation.

Description

Uses a large pilot sample (only the active predictors need to be generated) to find the multiplier \kappa of the standardised fixed effect f^* such that the population (fixed-effect) discrimination equals target:

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.

Usage

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
)

Arguments

family

"binomial" or "cox".

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 simLong.

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 \kappa.

Value

list with signal (\kappa), intercept (c_0, binomial), f_mean, f_sd (standardisation of f), achieved (discrimination at the solution) and target.

Examples

calibrateSim("binomial", target = 0.85, prevalence = 0.5, linear = FALSE, pilot_n = 50)

Folds of the cross-fitted E-step (internal).

Description

The observations of every individual are spread as evenly as possible over V folds, so every individual keeps observations in every training part. Drawn under a private seed; the caller's random-number stream is left untouched.

Usage

cf_make_folds(id, V, seed = 1)

Cox partial log-likelihood with Breslow ties (internal).

Description

Cox partial log-likelihood with Breslow ties (internal).

Usage

cox_partial_loglik(time, status, eta)

Expected AUC of a score for Bernoulli outcomes with known probabilities (internal).

Description

E[AUC]\approx\sum_{i\ne j}p_i(1-p_j)1(s_i>s_j)/\sum_{i\ne j}p_i(1-p_j).

Usage

expected_auc(s, prob)

Expected concordance of a score under a proportional-hazards model (internal).

Description

E[C]=\sum_{s_i>s_j}h_i/(h_i+h_j)/\#\{s_i>s_j\} with h=\exp(\eta).

Usage

expected_cindex(s, eta)

Population (fixed-effect) prediction of a MEXGB model on the link scale (internal).

Description

Population (fixed-effect) prediction of a MEXGB model on the link scale (internal).

Usage

fixedMEXGB(object, X)

-2 x Laplace approximation of the marginal log-likelihood (internal).

Description

\ell_{La}=\sum_i[\log p(y_i\mid\eta_i)-\frac12\hat b_i^\top D^{-1}\hat b_i -\frac12\log|I+DZ_i^\top W_iZ_i|] with \eta=\hat f+Z\hat b at the posterior modes \hat b_i; binomial: Bernoulli log-likelihood, W=\mu(1-\mu); cox: Breslow partial log-likelihood, W=\hat\Lambda_0(t)e^\eta (Poisson representation).

Usage

laplace_crit(family, Y, status, f, zb, b, D, Z, indiv_list, eps = 1e-06)

Laplace E-step: D maximising the Laplace-approximate marginal likelihood (internal).

Description

Laplace E-step: D maximising the Laplace-approximate marginal likelihood (internal).

Usage

laplace_estep(
  family,
  Y,
  status,
  f,
  b,
  D,
  Z,
  indiv_list,
  eps = 1e-06,
  centre = FALSE,
  int_col = integer(0)
)

Title

Description

Title

Usage

logV(Y, f, Z, time, id, B, gamma, sigma)

PQL working -2 log-likelihood (internal).

Description

Same as logV with the residual covariance \sigma^2 I replaced by W^{-1}.

Usage

logV_pql(Y, f, Z, id, B, w)

Fixed effect (link scale, before calibration) of a fitted M-step model (internal).

Description

Fixed effect (link scale, before calibration) of a fitted M-step model (internal).

Usage

mexgb_fixed_predict(model, X)

Importance of the predictors: mean absolute contribution to the fixed effect (internal). Tree part: SHAP contributions of xgboost; linear part: beta_j (x_j - mean x_j).

Description

Importance of the predictors: mean absolute contribution to the fixed effect (internal). Tree part: SHAP contributions of xgboost; linear part: beta_j (x_j - mean x_j).

Usage

mexgb_importance(model, X)

Penalised linear part fitted with glmnet on the cross-fitting folds (internal). Returns the full-data and fold-specific linear predictors (intercept included for gaussian / binomial) at the lambda with the smallest out-of-fold loss.

Description

Penalised linear part fitted with glmnet on the cross-fitting folds (internal). Returns the full-data and fold-specific linear predictors (intercept included for gaussian / binomial) at the lambda with the smallest out-of-fold loss.

Usage

mexgb_linear(
  X,
  Y,
  status,
  offset,
  family,
  cf_fold,
  alpha = 1,
  nlambda = 40,
  offset_oof = NULL,
  lambda_min_ratio = 0.01,
  relax = TRUE,
  gammas = c(0, 0.5, 1),
  relax_df_max = 30
)

Loss of a linear predictor on a set of rows (internal). gaussian: sum of squared errors; binomial: sum of log-losses; cox: minus the log partial likelihood (Breslow) of the rows (risk sets within the rows).

Description

Loss of a linear predictor on a set of rows (internal). gaussian: sum of squared errors; binomial: sum of log-losses; cox: minus the log partial likelihood (Breslow) of the rows (risk sets within the rows).

Usage

mexgb_loss(family, y, status, eta)

The M-step of MEXGB 0.5 (internal).

Description

The M-step of MEXGB 0.5 (internal).

Usage

mexgb_mstep(
  X,
  Y,
  status,
  offset,
  family,
  params,
  ntree,
  cf_fold,
  f0 = 0,
  linear = FALSE,
  lin_alpha = 1,
  ntree_select = c("cv", "fixed"),
  min_trees = 0,
  grid_step = 10,
  stall_rounds = 200,
  ntree_scale = NULL,
  lin_relax = FALSE,
  screen = "none",
  screen_sets = NULL,
  screen_sizes = c(5, 10, 20, 40),
  offset_oof = NULL
)

Value

list with fixed_full (fitted fixed effect on the link scale, offset excluded, all rows), fixed_cf (cross-fitted fixed effect), model (what fixedMEXGB needs to predict) and nrounds.


One EM step of the additive PQL working model (internal).

Description

Working model for the cross-fitted E-step of binary / cox outcomes: r_i=\tilde y_i-\hat f_i=Z_ib_i+e_i+\epsilon_i, b_i\sim N(0,D), e_i\sim N(0,\tau^2I) (out-of-fold error of the linear predictor), \epsilon_i\sim N(0,W_i^{-1}) (PQL working error), so V_i=Z_iDZ_i'+\tau^2I+W_i^{-1}. E-step at the current (D,\tau^2): BLUPs and conditional moments of b_i and e_i; M-step: D=n^{-1}\sum_i E(b_ib_i'), \tau^2=N^{-1}\sum_i E(e_i'e_i). Returns the BLUPs, the updated parameters and the -2 working log-likelihood (up to a constant) at the updated parameters.

Usage

pql_em_additive(r, Z, D, tau2, w, indiv_list)

Predict with a fitted MEXGB model.

Description

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.

Usage

## S3 method for class 'MEXGB'
predict(
  object,
  X,
  Z,
  id,
  time,
  type = c("response", "link", "survival"),
  times = NULL,
  ...
)

Arguments

object

: a MEXGB output of the MEXGB function.

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]: "response" (default; identity for gaussian, probability for binomial, relative hazard exp(\eta) for cox), "link" (linear predictor; log relative hazard for cox) or "survival" (cox only: matrix of predicted survival probabilities S(t|x)=\exp\{-\Lambda_0(t)e^{\eta}\} at times, with the Breslow baseline estimated from the returned fit).

times

[vector]: time points for type = "survival" (default: the distinct training event times).

...

: low levels arguments (ignored; kept for compatibility with predict.MEGB).

Value

Numeric prediction vector, or a matrix with observations in rows and requested times in columns for survival predictions.

Examples

# See MEXGB() for fitted-model prediction examples.


Print a fitted MEXGB model

Description

Print a fitted MEXGB model

Usage

## S3 method for class 'MEXGB'
print(x, ...)

Arguments

x

A fitted MEXGB model.

...

Unused.

Value

The model, invisibly.


Posterior modes of the random effects given D (internal).

Description

Newton iterations on the penalised log-likelihood \sum_j\log p(y_{ij}\mid f_{ij}+z_{ij}^\top b_i)-\frac12 b_i^\top D^{-1}b_i, written as BLUPs of the working variate (binomial: logistic; cox: Poisson representation with the Breslow baseline recomputed at every step).

Usage

re_modes(
  family,
  Y,
  status,
  f,
  b,
  D,
  Z,
  indiv_list,
  eps = 1e-06,
  centre = FALSE,
  int_col = integer(0),
  maxit = 50,
  tol = 1e-07
)

Title

Description

Title

Usage

sig(sigma, id, Z, epsilon, Btilde)

Simulate Low/High Dimensional and Linear/Nonlinear Longitudinal dataset (continuous, binary or survival).

Description

Simulates the design of the MEXGB papers. Each of the n individuals is observed at time_points equally spaced occasions t_{ij} rescaled to [0,1]. The p fixed-effect predictors of every observation are drawn from N_p(0,\Sigma_W) with AR(1) correlation (\Sigma_W)_{gg'}=\rho_W^{|g-g'|}; only the first six are active.

A correlated random intercept and slope b_i\sim N_2(0,D) with D_{11}=\tau_0^2, D_{22}=\tau_1^2, D_{12}=\rho_Z\tau_0\tau_1 enters through z_{ij}=(1,t_{ij}).

Usage

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
)

Arguments

n

Integer number of individuals, at least 2.

p

Positive integer number of predictors (p >= 6 for the nonlinear model).

rel_p

[numeric]: Number of relevant predictors in the linear model (coefficients recycled from c(2,-2,1.5,-1.5,1,-1)). The default value is rel_p=6. The nonlinear model always uses the first six predictors.

time_points

Integer number of realizations per individual, at least 2. The default value is time_points=10.

rho_W

AR(1) correlation strictly between -1 and 1, among predictors and within-subject errors. The default value is rho_W=0.6.

rho_Z

Correlation between -1 and 1 (inclusive) between the random intercept and slope. The default value is rho_Z=0.6.

random_sd_intercept

[numeric]: Standard deviation of the random intercept. Default \sqrt{0.5}.

random_sd_slope

[numeric]: Standard deviation of the random slope. Default \sqrt{3}.

noise_sd

[numeric]: Residual standard deviation \sigma (continuous outcome). The default value is noise_sd=0.5.

linear

[boolean]: If TRUE, the linear fixed effect is simulated, otherwise the nonlinear one.

family

[character]: "gaussian" (default), "binomial" or "cox".

target_auc

[numeric]: binary only; target AUC in [0.5, 1) of the fixed effect (e.g. 0.85). NULL = no calibration.

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). NULL = \kappa=1.

signal, intercept

[numeric]: optional fixed values of \kappa and c_0 (override calibration).

censoring

Cox target censored fraction in [0, 1) (default 0.3).

weibull_shape, weibull_scale

[numeric]: cox only; Weibull baseline \nu (default 1.5) and \lambda (default 1).

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 calibrateSim; when supplied it is used as is (no re-calibration), which keeps the data-generating process identical across simulation replicates and avoids repeating the pilot computation.

Value

A data frame with n*time_points rows and p+5 columns (p+6 for Cox) containing the following elements:

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.

Examples

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.

Description

Relative influence of the predictors in a fitted MEXGB model.

Usage

## S3 method for class 'MEXGB'
summary(object, top = NULL, ...)

Arguments

object

: a MEXGB output of the MEXGB function.

top

[numeric]: number of predictors to return (default all predictors with non-zero influence).

...

: not used.

Value

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.


Fit one xgboost regression ensemble (internal).

Description

Fit one xgboost regression ensemble (internal).

Usage

xgbfit(X, label, weight = NULL, params, ntree)

Fit one Cox-partial-likelihood xgboost ensemble with an offset (internal).

Description

label is the xgboost survival label (time for events, -time for censored observations); the offset (random-effect contribution) enters as base_margin.

Usage

xgbfit_cox(X, label, offset, params, ntree)

Fit one logistic xgboost ensemble with an offset (internal).

Description

The offset (random-effect contribution plus the constant f0) enters as the xgboost base_margin; base_score = 0.5 makes the global bias zero on the logit scale, so predict(..., outputmargin = TRUE) on a matrix returns the tree sum only.

Usage

xgbfit_logit(X, Y, offset, params, ntree)

Relative influence from an xgboost model (internal).

Description

Relative influence from an xgboost model (internal).

Usage

xgbimportance(forest, feature_names)