From 97002a8ed54038125be6b5281247dac128387a8c Mon Sep 17 00:00:00 2001 From: Josh <39366189+M-Colley@users.noreply.github.com> Date: Fri, 4 Dec 2026 01:41:00 +0000 Subject: [PATCH 1/2] Add held-out R2 to performance_accuracy --- DESCRIPTION | 2 +- NEWS.md | 2 + R/performance_accuracy.R | 72 ++++++++++++++------- man/performance_accuracy.Rd | 32 +++++---- tests/testthat/test-performance_accuracy.R | 75 ++++++++++++++++++++++ 5 files changed, 147 insertions(+), 36 deletions(-) create mode 100644 tests/testthat/test-performance_accuracy.R diff --git a/DESCRIPTION b/DESCRIPTION index df18383f2..188a04f2f 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -1,7 +1,7 @@ Type: Package Package: performance Title: Assessment of Regression Models Performance -Version: 0.20.0.23 +Version: 0.20.0.24 Authors@R: c(person(given = "Daniel", family = "Lüdecke", diff --git a/NEWS.md b/NEWS.md index d04d8940e..de2701e0c 100644 --- a/NEWS.md +++ b/NEWS.md @@ -2,6 +2,8 @@ ## Changes +* `performance_accuracy()` can report held-out R2 for linear models with `metric = "r2"` (#364). + * New function `test_clusters()` uses the `matchednull` package to compare a selected cluster count with the counts obtained from matched-null data that keep the observed margins and approximately the observed correlations. It diff --git a/R/performance_accuracy.R b/R/performance_accuracy.R index 75a4f5aa1..29d083995 100644 --- a/R/performance_accuracy.R +++ b/R/performance_accuracy.R @@ -12,25 +12,28 @@ #' compute the accuracy values. #' @param n Number of bootstrap-samples. #' @param verbose Toggle warnings. +#' @param metric Score for linear models. `"correlation"` uses Pearson +#' correlation, and `"r2"` uses held-out R2 with `method = "cv"`. The default +#' (`NULL`) selects Pearson correlation for linear models and AUC for logistic +#' models. #' @inheritParams performance_pcp #' -#' @return A list with three values: The `Accuracy` of the model predictions, -#' i.e. the proportion of accurately predicted values from the model, its -#' standard error, `SE`, and the `Method` used to compute the accuracy. +#' @return A list containing the mean score (`Accuracy`), its standard deviation +#' across resamples (`SE`), the interval level and empirical limits +#' (`CI`, `CI_low`, `CI_high`), and the score used (`Method`). #' -#' @details For linear models, the accuracy is the correlation coefficient -#' between the actual and the predicted value of the outcome. For logistic -#' regression models, the accuracy corresponds to the AUC-value, calculated with -#' the [`bayestestR::auc()`]-function. +#' @details With `metric = "r2"`, each cross-validation fold uses the sum of +#' squared prediction errors and the sum of squared deviations from the +#' observed response mean in the test fold. The score is one minus the ratio +#' of these sums, so negative held-out R2 is possible. Summaries use folds +#' with finite scores. Folds with constant responses have undefined R2. #' -#' The accuracy is the mean value of multiple correlation resp. AUC-values, -#' which are either computed with cross-validation or non-parametric -#' bootstrapping (see argument `method`). The standard error is the standard -#' deviation of the computed correlation resp. AUC-values. +#' @seealso [performance_cv()] for R2 computed from pooled fold predictions. #' #' @examples #' model <- lm(mpg ~ wt + cyl, data = mtcars) #' performance_accuracy(model) +#' performance_accuracy(model, metric = "r2") #' #' model <- glm(vs ~ wt + mpg, data = mtcars, family = "binomial") #' performance_accuracy(model) @@ -41,7 +44,8 @@ performance_accuracy <- function( k = 5, n = 1000, ci = 0.95, - verbose = TRUE + verbose = TRUE, + metric = NULL ) { method <- insight::validate_argument(method, c("cv", "boot")) @@ -56,10 +60,19 @@ performance_accuracy <- function( info <- insight::model_info(model, verbose = verbose) + if (!is.null(metric)) { + metric <- insight::validate_argument(metric, c("correlation", "r2")) + if (!info$is_linear) { + insight::format_error("`metric` is available for linear models.") + } + } + use_r2 <- identical(metric, "r2") + if (use_r2 && method != "cv") { + insight::format_error('`metric = "r2"` requires `method = "cv"`.') + } + # accuracy for linear models if (info$is_linear) { - measure <- "Correlation between observed and predicted" - # check if bootstrapping or cross validation is requested if (method == "boot") { # accuracy linear models with bootstrapping @@ -85,14 +98,6 @@ performance_accuracy <- function( response <- lapply(bootstr, function(.x) { as.data.frame(model_data[.x, ])[[resp.name]] }) - - accuracy <- mapply( - function(.x, .y) { - stats::cor(.x, .y, use = "pairwise.complete.obs") - }, - predictions, - response - ) } else { # accuracy linear models with cross validation @@ -117,7 +122,17 @@ performance_accuracy <- function( response <- lapply(cv, function(.x) { as.data.frame(model_data[.x$test, ])[[resp.name]] }) + } + if (use_r2) { + measure <- "Cross-validated R2" + accuracy <- vapply( + seq_along(predictions), + function(i) .performance_accuracy_r2(predictions[[i]], response[[i]]), + numeric(1L) + ) + } else { + measure <- "Correlation between observed and predicted" accuracy <- mapply( function(.x, .y) { stats::cor(.x, .y, use = "pairwise.complete.obs") @@ -268,6 +283,19 @@ print.performance_accuracy <- function(x, ...) { # utilities ------------------------ +.performance_accuracy_r2 <- function(predicted, observed) { + valid <- is.finite(predicted) & is.finite(observed) + predicted <- predicted[valid] + observed <- observed[valid] + + total <- sum((observed - mean(observed))^2) + error <- sum((observed - predicted)^2) + if (total == 0 || !is.finite(total) || !is.finite(error)) { + return(NA_real_) + } + 1 - error / total +} + .crossv_kfold <- function(model_data, k = 5) { n <- nrow(model_data) folds <- sample(rep(1:k, length.out = n)) diff --git a/man/performance_accuracy.Rd b/man/performance_accuracy.Rd index 152e2c355..b24027b16 100644 --- a/man/performance_accuracy.Rd +++ b/man/performance_accuracy.Rd @@ -10,7 +10,8 @@ performance_accuracy( k = 5, n = 1000, ci = 0.95, - verbose = TRUE + verbose = TRUE, + metric = NULL ) } \arguments{ @@ -28,31 +29,36 @@ compute the accuracy values.} \item{ci}{The level of the confidence interval.} \item{verbose}{Toggle warnings.} + +\item{metric}{Score for linear models. \code{"correlation"} uses Pearson +correlation, and \code{"r2"} uses held-out R2 with \code{method = "cv"}. The default +(\code{NULL}) selects Pearson correlation for linear models and AUC for logistic +models.} } \value{ -A list with three values: The \code{Accuracy} of the model predictions, -i.e. the proportion of accurately predicted values from the model, its -standard error, \code{SE}, and the \code{Method} used to compute the accuracy. +A list containing the mean score (\code{Accuracy}), its standard deviation +across resamples (\code{SE}), the interval level and empirical limits +(\code{CI}, \code{CI_low}, \code{CI_high}), and the score used (\code{Method}). } \description{ This function calculates the predictive accuracy of linear or logistic regression models. } \details{ -For linear models, the accuracy is the correlation coefficient -between the actual and the predicted value of the outcome. For logistic -regression models, the accuracy corresponds to the AUC-value, calculated with -the \code{\link[bayestestR:auc]{bayestestR::auc()}}-function. - -The accuracy is the mean value of multiple correlation resp. AUC-values, -which are either computed with cross-validation or non-parametric -bootstrapping (see argument \code{method}). The standard error is the standard -deviation of the computed correlation resp. AUC-values. +With \code{metric = "r2"}, each cross-validation fold uses the sum of +squared prediction errors and the sum of squared deviations from the +observed response mean in the test fold. The score is one minus the ratio +of these sums, so negative held-out R2 is possible. Summaries use folds +with finite scores. Folds with constant responses have undefined R2. } \examples{ model <- lm(mpg ~ wt + cyl, data = mtcars) performance_accuracy(model) +performance_accuracy(model, metric = "r2") model <- glm(vs ~ wt + mpg, data = mtcars, family = "binomial") performance_accuracy(model) } +\seealso{ +\code{\link[=performance_cv]{performance_cv()}} for R2 computed from pooled fold predictions. +} diff --git a/tests/testthat/test-performance_accuracy.R b/tests/testthat/test-performance_accuracy.R new file mode 100644 index 000000000..e0aecf16a --- /dev/null +++ b/tests/testthat/test-performance_accuracy.R @@ -0,0 +1,75 @@ +test_that("performance_accuracy reports held-out R2 when requested", { + model <- lm(mpg ~ wt + cyl, data = mtcars) + + set.seed(44) + folds <- .crossv_kfold(mtcars, k = 5) + scores <- vapply( + folds, + function(fold) { + training_model <- update(model, data = mtcars[fold$train, ]) + test_data <- mtcars[fold$test, ] + observed <- test_data$mpg + predicted <- predict(training_model, newdata = test_data) + 1 - mean((predicted - observed)^2) / mean((observed - mean(observed))^2) + }, + numeric(1) + ) + + set.seed(44) + accuracy <- performance_accuracy(model, ci = 0.8, metric = "r2") + + expect_lt(min(scores), 0) + expect_identical(accuracy$Method, "Cross-validated R2") + expect_equal(accuracy$Accuracy, mean(scores), tolerance = 1e-12) + expect_equal(accuracy$SE, sd(scores), tolerance = 1e-12) + expect_equal( + c(accuracy$CI_low, accuracy$CI_high), + unname(quantile(scores, c(0.1, 0.9))), + tolerance = 1e-12 + ) + + set.seed(44) + cv <- performance_cv(model, method = "k_fold", stack = FALSE, metrics = "R2") + expect_equal(accuracy$Accuracy, cv$R2, tolerance = 1e-12) + expect_equal(accuracy$SE, cv$R2_SE, tolerance = 1e-12) +}) + +test_that("the explicit correlation and the existing default agree", { + model <- lm(mpg ~ wt + cyl, data = mtcars) + for (method in c("cv", "boot")) { + set.seed(44) + default <- performance_accuracy(model, method, 5, 10, 0.8, FALSE) + set.seed(44) + correlation <- performance_accuracy(model, method, 5, 10, 0.8, FALSE, "correlation") + expect_identical(correlation, default) + } +}) + +test_that("performance_accuracy handles undefined fold R2 and validates the metric", { + model <- lm(mpg ~ wt + cyl, data = mtcars) + set.seed(44) + accuracy <- performance_accuracy(model, k = nrow(mtcars), metric = "r2") + expect_true(all(is.na(c( + accuracy$Accuracy, + accuracy$SE, + accuracy$CI_low, + accuracy$CI_high + )))) + + expect_error( + performance_accuracy(model, method = "boot", metric = "r2"), + 'method = "cv"', + fixed = TRUE + ) + expect_error( + performance_accuracy(model, metric = "unknown"), + "Invalid option for argument", + fixed = TRUE + ) + binomial <- glm(vs ~ wt + mpg, data = mtcars, family = "binomial") + expect_error( + performance_accuracy(binomial, metric = "r2"), + "linear models", + fixed = TRUE + ) +}) From e12d3dbf375265908b88ef2f81f99a2593ab2c18 Mon Sep 17 00:00:00 2001 From: Josh <39366189+M-Colley@users.noreply.github.com> Date: Fri, 4 Dec 2026 03:54:05 +0000 Subject: [PATCH 2/2] Resolve changed-file lint in performance_accuracy --- R/performance_accuracy.R | 57 +++++++++++++++++++++------------------- 1 file changed, 30 insertions(+), 27 deletions(-) diff --git a/R/performance_accuracy.R b/R/performance_accuracy.R index 29d083995..fec7f6021 100644 --- a/R/performance_accuracy.R +++ b/R/performance_accuracy.R @@ -49,8 +49,8 @@ performance_accuracy <- function( ) { method <- insight::validate_argument(method, c("cv", "boot")) - # get formula from model fit - formula <- stats::formula(model) + # Refitting may look up an original formula argument named `formula`. + formula <- stats::formula(model) # nolint: object_overwrite_linter. # get name of response resp.name <- insight::find_response(model) @@ -80,7 +80,7 @@ performance_accuracy <- function( bootstr <- replicate(n, sample(nrow(model_data), replace = TRUE), simplify = FALSE) models <- lapply(bootstr, function(.x) { - text <- utils::capture.output({ + utils::capture.output({ model_upd <- stats::update(model, data = model_data[.x, ]) }) # stats::lm(formula, data = model_data[.x, ]) @@ -104,7 +104,7 @@ performance_accuracy <- function( cv <- .crossv_kfold(model_data, k = k) models <- lapply(cv, function(.x) { - text <- utils::capture.output({ + utils::capture.output({ model_upd <- stats::update(model, data = model_data[.x$train, ]) }) model_upd @@ -133,12 +133,9 @@ performance_accuracy <- function( ) } else { measure <- "Correlation between observed and predicted" - accuracy <- mapply( - function(.x, .y) { - stats::cor(.x, .y, use = "pairwise.complete.obs") - }, - predictions, - response + accuracy <- simplify2array( + Map(stats::cor, predictions, response, use = "pairwise.complete.obs"), + higher = FALSE ) } } else if (info$is_binomial) { @@ -151,7 +148,7 @@ performance_accuracy <- function( bootstr <- replicate(n, sample(nrow(model_data), replace = TRUE), simplify = FALSE) models <- lapply(bootstr, function(.x) { - text <- utils::capture.output({ + utils::capture.output({ model_upd <- stats::update(model, data = model_data[.x, ]) }) # stats::glm(formula, data = model_data[.x, ], family = stats::binomial(link = "logit")) @@ -170,20 +167,23 @@ performance_accuracy <- function( .recode_to_zero(as.data.frame(model_data[.x, ])[[resp.name]]) }) - accuracy <- mapply( - function(.x, .y) { - roc <- performance_roc(x = .x, predictions = .y) - bayestestR::area_under_curve(roc$Specificity, roc$Sensitivity) - }, - response, - predictions + accuracy <- simplify2array( + Map( + function(.x, .y) { + roc <- performance_roc(x = .x, predictions = .y) + bayestestR::area_under_curve(roc$Specificity, roc$Sensitivity) + }, + response, + predictions + ), + higher = FALSE ) } else { # accuracy linear models with cross validation cv <- .crossv_kfold(model_data, k = k) models <- lapply(cv, function(.x) { - text <- utils::capture.output({ + utils::capture.output({ model_upd <- stats::update(model, data = model_data[.x$train, ]) }) model_upd @@ -202,13 +202,16 @@ performance_accuracy <- function( .recode_to_zero(as.data.frame(model_data[.x$test, ])[[resp.name]]) }) - accuracy <- mapply( - function(.x, .y) { - roc <- performance_roc(x = .x, predictions = .y) - bayestestR::area_under_curve(roc$Specificity, roc$Sensitivity) - }, - response, - predictions + accuracy <- simplify2array( + Map( + function(.x, .y) { + roc <- performance_roc(x = .x, predictions = .y) + bayestestR::area_under_curve(roc$Specificity, roc$Sensitivity) + }, + response, + predictions + ), + higher = FALSE ) } @@ -298,7 +301,7 @@ print.performance_accuracy <- function(x, ...) { .crossv_kfold <- function(model_data, k = 5) { n <- nrow(model_data) - folds <- sample(rep(1:k, length.out = n)) + folds <- sample(rep_len(1:k, n)) idx <- seq_len(n) fold_idx <- split(idx, folds) fold <- function(test) {