From 9a6dd448fc36b804c0ef65af44bcd48e88e3f057 Mon Sep 17 00:00:00 2001 From: ielbadisy Date: Sun, 15 Nov 2026 05:13:14 +0000 Subject: [PATCH] Add bootvalidate() for optimism, .632 and .632+ bootstrap validation --- DESCRIPTION | 2 +- NAMESPACE | 2 + NEWS.md | 7 + R/bootvalidate.R | 211 +++++++++++++++++++++++++++++ man/bootvalidate.Rd | 90 ++++++++++++ tests/testthat/test-bootvalidate.R | 66 +++++++++ 6 files changed, 377 insertions(+), 1 deletion(-) create mode 100644 R/bootvalidate.R create mode 100644 man/bootvalidate.Rd create mode 100644 tests/testthat/test-bootvalidate.R diff --git a/DESCRIPTION b/DESCRIPTION index 7c81e79..53de553 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -39,7 +39,7 @@ Imports: stats, utils, ggplot2, functionals, grDevices, tools, randomForest, gbm, C50, kknn, earth, naivebayes, mda, ada, pls, partykit, dbarts, xgboost, lightgbm, densemlp, fastgbm Suggests: testthat (>= 3.1.0), knitr, rmarkdown, roxygen2, gggenes, - ggfittext, pROC + ggfittext, pROC, rms VignetteBuilder: knitr Config/testthat/edition: 3 NeedsCompilation: no diff --git a/NAMESPACE b/NAMESPACE index aa16e3d..cb87ca4 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -21,6 +21,7 @@ S3method(plot,funcml_surrogate) S3method(plot,funcml_tune) S3method(predict,funcml_fit) S3method(print,funcml_ale) +S3method(print,funcml_bootvalidate) S3method(print,funcml_calibration) S3method(print,funcml_compare) S3method(print,funcml_dca) @@ -60,6 +61,7 @@ export(aucci) export(aucweighted) export(balanced_accuracy) export(balancedaccuracy) +export(bootvalidate) export(brier) export(calibration_curve) export(calibrationcurve) diff --git a/NEWS.md b/NEWS.md index 32c648a..c4bc545 100644 --- a/NEWS.md +++ b/NEWS.md @@ -1,5 +1,12 @@ # funcml 0.9.11 +* New `bootvalidate()` for bootstrap internal validation of any learner. + It returns the apparent performance, the Harrell optimism-corrected + estimate (as `rms::validate()`), the leave-one-out bootstrap (OOB) + estimate, and the Efron `.632` and Efron-Tibshirani `.632+` estimates + for each metric, with per-replicate values and the bootstrap indices. + With the same seed the optimism-corrected values match `rms::validate()` + for `lrm` and `ols` fits. * `kknn` treated `k` as the largest k of a leave-one-out search, so the fitted model could use fewer neighbours than asked. `k` is now the exact number of neighbours. The kernel, fixed at `"optimal"` before, is now the diff --git a/R/bootvalidate.R b/R/bootvalidate.R new file mode 100644 index 0000000..538b392 --- /dev/null +++ b/R/bootvalidate.R @@ -0,0 +1,211 @@ +#' Bootstrap validation: optimism correction, .632 and .632+. +#' +#' Internal validation of a learner by the bootstrap. Each of the `B` +#' replicates draws `n` rows with replacement, fits the learner on them, and +#' scores the fit on three sets of rows: the bootstrap sample itself, the +#' original data, and the out-of-bag (OOB) rows not drawn. +#' +#' With `app` the apparent performance (the learner fitted and scored on all +#' rows), the returned estimates are: +#' +#' * Optimism correction (Harrell, Lee and Mark 1996), as in +#' `rms::validate()`: `optimism = mean_b(boot_b - orig_b)` and +#' `corrected = app - optimism`. +#' * Leave-one-out bootstrap `oob = mean_b(oob_b)`, the OOB metric averaged +#' over replicates. +#' * `.632` (Efron 1983): `0.368 * app + 0.632 * oob`. +#' * `.632+` (Efron and Tibshirani 1997): `(1 - w) * app + w * oob'` with +#' `w = 0.632 / (1 - 0.368 * R)`, relative overfitting rate +#' `R = (oob' - app) / (gamma - app)` (set to 0 when `oob` is no worse than +#' `app`, or `gamma` is no worse than `app`), and `oob'` the OOB value +#' capped at `gamma`. The no-information value `gamma` is the metric +#' computed on every pairing of an observed outcome with an apparent +#' prediction (a random sample of 250,000 pairings when `n^2` exceeds +#' that). Higher-is-better metrics (`auc`, `accuracy`, `rsq`, ...) are +#' handled on the corresponding loss scale, so "worse" means lower. +#' +#' The OOB metric is computed per replicate and averaged, which for +#' non-additive metrics (`auc`, `ece`) is the usual approximation of the +#' per-observation leave-one-out bootstrap. +#' +#' @param data Data frame. +#' @param formula Model formula. +#' @param model Learner id. +#' @param spec Optional hyperparameter list. +#' @param B Number of bootstrap replicates. +#' @param metrics Character vector of metric names. Defaults to +#' `c("rmse", "mse", "rsq")` for regression and +#' `c("auc", "brier", "logloss", "accuracy")` for classification. +#' @param seed Optional seed for the bootstrap draws. +#' @param ncores Optional number of CPU cores for the replicates. +#' @param ... Passed to [fit()]. +#' @return A `funcml_bootvalidate` object: a list with `summary` (one row +#' per metric: `apparent`, `optimism`, `corrected`, `oob`, `est632`, +#' `est632plus`, `gamma`, `n_boot`), `replicates` (one row per replicate +#' and metric with the `boot`, `orig` and `oob` values), `indices` (the +#' bootstrap row indices of each replicate), `n_failed`, `task` and +#' `model`. +#' @references +#' Harrell FE, Lee KL, Mark DB (1996). Multivariable prognostic models. +#' Statistics in Medicine 15, 361-387. +#' +#' Efron B, Tibshirani R (1997). Improvements on cross-validation: the .632+ +#' bootstrap method. Journal of the American Statistical Association 92, +#' 548-560. +#' @examples +#' bv <- bootvalidate(mtcars, mpg ~ wt + hp, model = "glm", B = 20, seed = 1) +#' bv +#' @export +bootvalidate <- function(data, formula, model, spec = NULL, B = 200, + metrics = NULL, seed = NULL, ncores = NULL, ...) { + if (!is.numeric(B) || length(B) != 1L || !is.finite(B) || B < 2) { + stop("`B` must be a single number of at least 2.", call. = FALSE) + } + B <- as.integer(B) + ncores <- .validate_ncores(ncores) + .check_no_missing_model_vars( + formula, data, + outcome_only = isTRUE(funcml_registry(model)$supports$na) && is.null(list(...)$na_action), + caller = "bootvalidate" + ) + y_all <- stats::model.response(stats::model.frame(formula, data, na.action = stats::na.pass)) + task <- infer_task(y_all) + if (task == "classification") { + y_all <- factor(y_all) + } + if (is.null(metrics)) { + metrics <- if (task == "regression") c("rmse", "mse", "rsq") else c("auc", "brier", "logloss", "accuracy") + } + n <- nrow(data) + + if (!is.null(seed)) set.seed(seed) + draw <- function() { + repeat { + idx <- sample.int(n, n, replace = TRUE) + ok <- length(unique(idx)) < n + if (task == "classification") { + ok <- ok && all(table(y_all[idx]) > 0) && all(table(y_all[-unique(idx)]) > 0) + } + if (ok) return(idx) + } + } + indices <- lapply(seq_len(B), function(b) draw()) + + full_fit <- fit(formula, data, model, spec = spec, ...) + app_scored <- .bv_score(full_fit, data, y_all, task, metrics) + apparent <- app_scored$values + gamma <- .bv_noinfo(y_all, app_scored, task, metrics) + + reps <- .funcml_map(seq_len(B), function(b) { + idx <- indices[[b]] + oob <- setdiff(seq_len(n), idx) + boot_data <- data[idx, , drop = FALSE] + fb <- tryCatch(fit(formula, boot_data, model, spec = spec, ...), error = function(e) NULL) + if (is.null(fb)) { + return(NULL) + } + data.frame( + replicate = b, + metric = metrics, + boot = .bv_score(fb, boot_data, y_all[idx], task, metrics)$values, + orig = .bv_score(fb, data, y_all, task, metrics)$values, + oob = .bv_score(fb, data[oob, , drop = FALSE], y_all[oob], task, metrics)$values, + stringsAsFactors = FALSE + ) + }, ncores = ncores) + n_failed <- sum(vapply(reps, is.null, logical(1))) + replicates <- .rbind_dt(reps) + if (!nrow(replicates)) { + stop("All bootstrap fits failed.", call. = FALSE) + } + + summary_df <- .rbind_dt(lapply(seq_along(metrics), function(j) { + m <- metrics[j] + r <- replicates[replicates$metric == m, , drop = FALSE] + est <- .bv_estimates(apparent[j], r$boot, r$orig, r$oob, gamma[j], metric_direction(m)) + data.frame(metric = m, as.data.frame(as.list(est)), n_boot = nrow(r), stringsAsFactors = FALSE) + })) + + out <- list( + summary = summary_df, + replicates = replicates, + indices = indices, + n_failed = n_failed, + task = task, + model = model, + call = match.call() + ) + class(out) <- "funcml_bootvalidate" + out +} + +#' @export +print.funcml_bootvalidate <- function(x, digits = 4L, ...) { + cat(sprintf( + " model: %s | task: %s | B = %d (failed: %d)\n", + x$model, x$task, max(x$summary$n_boot), x$n_failed + )) + print(.round_numeric_df(x$summary, digits = digits)) + invisible(x) +} + +# Score a fitted model on `newdata`; keeps the predictions for the +# no-information rate. +.bv_score <- function(fit_obj, newdata, truth, task, metrics) { + prob_metrics <- c("logloss", "brier", "auc", "auc_weighted", "ece", "mce") + if (task == "regression") { + pred <- as.numeric(predict(fit_obj, newdata = newdata, type = "response")) + vals <- vapply(metrics, function(m) .loss(truth, pred, task, m), numeric(1)) + return(list(values = unname(vals), pred = pred, prob = NULL)) + } + if (any(metrics %in% prob_metrics)) { + prob <- as.matrix(predict(fit_obj, newdata = newdata, type = "prob")) + if (is.null(colnames(prob))) colnames(prob) <- fit_obj$levels + pred <- factor(fit_obj$levels[max.col(prob, ties.method = "first")], levels = fit_obj$levels) + } else { + prob <- NULL + pred <- factor(predict(fit_obj, newdata = newdata, type = "class"), levels = fit_obj$levels) + } + vals <- vapply(metrics, function(m) .loss(truth, pred, task, m, prob_matrix = prob), numeric(1)) + list(values = unname(vals), pred = pred, prob = prob) +} + +# No-information value: the metric on outcomes paired with predictions at +# random (all n^2 pairings, or a random sample of them for large n). +.bv_noinfo <- function(truth, scored, task, metrics, max_pairs = 250000L) { + n <- length(truth) + if (as.numeric(n)^2 <= max_pairs) { + i <- rep(seq_len(n), times = n) + j <- rep(seq_len(n), each = n) + } else { + i <- sample.int(n, max_pairs, replace = TRUE) + j <- sample.int(n, max_pairs, replace = TRUE) + } + prob <- if (is.null(scored$prob)) NULL else scored$prob[j, , drop = FALSE] + vapply(metrics, function(m) { + suppressWarnings(.loss(truth[i], scored$pred[j], task, m, prob_matrix = prob)) + }, numeric(1), USE.NAMES = FALSE) +} + +.bv_estimates <- function(app, boot, orig, oob, gamma, direction) { + optimism <- mean(boot - orig) + oob_mean <- mean(oob) + # .632+ on the loss scale (larger = worse). + s <- if (identical(direction, "min")) 1 else -1 + a <- s * app + e1 <- s * oob_mean + g <- s * gamma + e1p <- min(e1, g) + R <- if (e1 > a && g > a) (e1p - a) / (g - a) else 0 + R <- min(max(R, 0), 1) + w <- 0.632 / (1 - 0.368 * R) + c( + apparent = app, + optimism = optimism, + corrected = app - optimism, + oob = oob_mean, + est632 = 0.368 * app + 0.632 * oob_mean, + est632plus = s * ((1 - w) * a + w * e1p), + gamma = gamma + ) +} diff --git a/man/bootvalidate.Rd b/man/bootvalidate.Rd new file mode 100644 index 0000000..30fcd9b --- /dev/null +++ b/man/bootvalidate.Rd @@ -0,0 +1,90 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/bootvalidate.R +\name{bootvalidate} +\alias{bootvalidate} +\title{Bootstrap validation: optimism correction, .632 and .632+.} +\usage{ +bootvalidate( + data, + formula, + model, + spec = NULL, + B = 200, + metrics = NULL, + seed = NULL, + ncores = NULL, + ... +) +} +\arguments{ +\item{data}{Data frame.} + +\item{formula}{Model formula.} + +\item{model}{Learner id.} + +\item{spec}{Optional hyperparameter list.} + +\item{B}{Number of bootstrap replicates.} + +\item{metrics}{Character vector of metric names. Defaults to +\code{c("rmse", "mse", "rsq")} for regression and +\code{c("auc", "brier", "logloss", "accuracy")} for classification.} + +\item{seed}{Optional seed for the bootstrap draws.} + +\item{ncores}{Optional number of CPU cores for the replicates.} + +\item{...}{Passed to \code{\link[=fit]{fit()}}.} +} +\value{ +A \code{funcml_bootvalidate} object: a list with \code{summary} (one row +per metric: \code{apparent}, \code{optimism}, \code{corrected}, \code{oob}, \code{est632}, +\code{est632plus}, \code{gamma}, \code{n_boot}), \code{replicates} (one row per replicate +and metric with the \code{boot}, \code{orig} and \code{oob} values), \code{indices} (the +bootstrap row indices of each replicate), \code{n_failed}, \code{task} and +\code{model}. +} +\description{ +Internal validation of a learner by the bootstrap. Each of the \code{B} +replicates draws \code{n} rows with replacement, fits the learner on them, and +scores the fit on three sets of rows: the bootstrap sample itself, the +original data, and the out-of-bag (OOB) rows not drawn. +} +\details{ +With \code{app} the apparent performance (the learner fitted and scored on all +rows), the returned estimates are: +\itemize{ +\item Optimism correction (Harrell, Lee and Mark 1996), as in +\code{rms::validate()}: \code{optimism = mean_b(boot_b - orig_b)} and +\code{corrected = app - optimism}. +\item Leave-one-out bootstrap \code{oob = mean_b(oob_b)}, the OOB metric averaged +over replicates. +\item \code{.632} (Efron 1983): \code{0.368 * app + 0.632 * oob}. +\item \verb{.632+} (Efron and Tibshirani 1997): \verb{(1 - w) * app + w * oob'} with +\code{w = 0.632 / (1 - 0.368 * R)}, relative overfitting rate +\verb{R = (oob' - app) / (gamma - app)} (set to 0 when \code{oob} is no worse than +\code{app}, or \code{gamma} is no worse than \code{app}), and \verb{oob'} the OOB value +capped at \code{gamma}. The no-information value \code{gamma} is the metric +computed on every pairing of an observed outcome with an apparent +prediction (a random sample of 250,000 pairings when \code{n^2} exceeds +that). Higher-is-better metrics (\code{auc}, \code{accuracy}, \code{rsq}, ...) are +handled on the corresponding loss scale, so "worse" means lower. +} + +The OOB metric is computed per replicate and averaged, which for +non-additive metrics (\code{auc}, \code{ece}) is the usual approximation of the +per-observation leave-one-out bootstrap. +} +\examples{ +bv <- bootvalidate(mtcars, mpg ~ wt + hp, model = "glm", B = 20, seed = 1) +bv +} +\references{ +Harrell FE, Lee KL, Mark DB (1996). Multivariable prognostic models. +Statistics in Medicine 15, 361-387. + +Efron B, Tibshirani R (1997). Improvements on cross-validation: the .632+ +bootstrap method. Journal of the American Statistical Association 92, +548-560. +} diff --git a/tests/testthat/test-bootvalidate.R b/tests/testthat/test-bootvalidate.R new file mode 100644 index 0000000..d174c68 --- /dev/null +++ b/tests/testthat/test-bootvalidate.R @@ -0,0 +1,66 @@ +test_that("bootvalidate() optimism correction matches rms::validate()", { + skip_if_not_installed("rms") + set.seed(3) + n <- 150 + d <- data.frame(x1 = rnorm(n), x2 = rnorm(n), x3 = rnorm(n), x4 = rnorm(n)) + d$y <- factor(rbinom(n, 1, plogis(0.8 * d$x1 - 0.5 * d$x2))) + f <- y ~ x1 + x2 + x3 + x4 + bv <- bootvalidate(d, f, model = "glm", B = 60, seed = 1, metrics = c("auc", "brier")) + # rms draws its bootstrap samples with the same sample() call, so with the + # same seed both use the same replicates (no redraw happened here). + fr <- rms::lrm(f, data = d, x = TRUE, y = TRUE) + set.seed(1) + v <- rms::validate(fr, B = 60) + s <- bv$summary + expect_equal(s$apparent[s$metric == "auc"], 0.5 + v["Dxy", "index.orig"] / 2, tolerance = 1e-6) + expect_equal(s$optimism[s$metric == "auc"], v["Dxy", "optimism"] / 2, tolerance = 1e-6) + expect_equal(s$corrected[s$metric == "auc"], 0.5 + v["Dxy", "index.corrected"] / 2, tolerance = 1e-6) + expect_equal(s$corrected[s$metric == "brier"], v["B", "index.corrected"], tolerance = 1e-6) + + o <- rms::ols(mpg ~ wt + hp + qsec, data = mtcars, x = TRUE, y = TRUE) + set.seed(2) + vo <- rms::validate(o, B = 50) + bvr <- bootvalidate(mtcars, mpg ~ wt + hp + qsec, model = "glm", B = 50, seed = 2, + metrics = c("mse", "rsq")) + expect_equal(bvr$summary$corrected, unname(vo[c("MSE", "R-square"), "index.corrected"]), + tolerance = 1e-6) +}) + +test_that("bootvalidate() .632 and .632+ follow the hand formulas", { + bv <- bootvalidate(mtcars, mpg ~ wt + hp + qsec, model = "glm", B = 30, seed = 5, + metrics = c("mse", "rsq")) + # replicates can be rebuilt by hand from the stored indices + idx <- bv$indices[[4]] + oob <- setdiff(seq_len(nrow(mtcars)), idx) + g <- stats::lm(mpg ~ wt + hp + qsec, data = mtcars[idx, ]) + r4 <- bv$replicates[bv$replicates$replicate == 4 & bv$replicates$metric == "mse", ] + expect_equal(r4$boot, mean(stats::residuals(g)^2)) + expect_equal(r4$orig, mean((mtcars$mpg - stats::predict(g, mtcars))^2)) + expect_equal(r4$oob, mean((mtcars$mpg[oob] - stats::predict(g, mtcars[oob, ]))^2)) + + full <- stats::lm(mpg ~ wt + hp + qsec, data = mtcars) + y <- mtcars$mpg + yhat <- stats::fitted(full) + app <- mean((y - yhat)^2) + gamma <- mean(outer(y, yhat, "-")^2) + rr <- bv$replicates[bv$replicates$metric == "mse", ] + err1 <- mean(rr$oob) + R <- (min(err1, gamma) - app) / (gamma - app) + w <- 0.632 / (1 - 0.368 * R) + s <- bv$summary[bv$summary$metric == "mse", ] + expect_equal(s$gamma, gamma) + expect_equal(s$est632, 0.368 * app + 0.632 * err1) + expect_equal(s$est632plus, (1 - w) * app + w * min(err1, gamma)) + expect_equal(s$corrected, app - mean(rr$boot - rr$orig)) + # higher-is-better metric: .632+ lies between apparent and no-information + sr <- bv$summary[bv$summary$metric == "rsq", ] + expect_lt(sr$est632plus, sr$apparent) + expect_gt(sr$est632plus, sr$gamma) +}) + +test_that("bootvalidate() checks inputs and missing values", { + expect_error(bootvalidate(mtcars, mpg ~ wt, model = "glm", B = 1), "B") + d <- mtcars + d$wt[1] <- NA + expect_error(bootvalidate(d, mpg ~ wt, model = "glm", B = 5), "bootvalidate") +})