Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
133 changes: 84 additions & 49 deletions R/performance_accuracy.R
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -41,12 +44,13 @@ performance_accuracy <- function(
k = 5,
n = 1000,
ci = 0.95,
verbose = TRUE
verbose = TRUE,
metric = NULL
) {
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)
Expand All @@ -56,18 +60,27 @@ 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

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, ])
Expand All @@ -85,21 +98,13 @@ 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

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
Expand All @@ -117,13 +122,20 @@ performance_accuracy <- function(
response <- lapply(cv, function(.x) {
as.data.frame(model_data[.x$test, ])[[resp.name]]
})
}

accuracy <- mapply(
function(.x, .y) {
stats::cor(.x, .y, use = "pairwise.complete.obs")
},
predictions,
response
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 <- simplify2array(
Map(stats::cor, predictions, response, use = "pairwise.complete.obs"),
higher = FALSE
)
}
} else if (info$is_binomial) {
Expand All @@ -136,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"))
Expand All @@ -155,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
Expand All @@ -187,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
)
}

Expand Down Expand Up @@ -268,9 +286,26 @@ 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_)
}
score <- 1 - error / total
if (!is.finite(score)) {
return(NA_real_)
}
score
}

.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) {
Expand Down
32 changes: 19 additions & 13 deletions man/performance_accuracy.Rd

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

79 changes: 79 additions & 0 deletions tests/testthat/test-performance_accuracy.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
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
)
})

test_that("a fold R2 that overflows is treated as missing", {
expect_identical(.performance_accuracy_r2(c(1, 1), c(0, 1e-155)), NA_real_)
})
Loading