diff --git a/R/pred_measure-compute.R b/R/pred_measure-compute.R index 7479533e..a8b9a39f 100644 --- a/R/pred_measure-compute.R +++ b/R/pred_measure-compute.R @@ -111,6 +111,11 @@ do_pred_measure <- function( if (length(dim(ylp_test)) == 3) { ylp_test <- llarray_to_matrix(ylp_test) } + dims <- .pred_measure_dims( + source = source, y = y, ypred = ypred, mupred = mupred, ylp = ylp, + ylp_test = ylp_test, psis_object = psis_object, loo = loo, + kfold = kfold, predperf = predperf + ) measures <- .prepare_measures( measures, predperf, supported_measures_list, source @@ -118,19 +123,11 @@ do_pred_measure <- function( .validate_control(control, measures) needs_elpd <- .any_needs_elpd(measures) if (source == "loo") { - if (is.null(predperf)) { - if (!is.null(loo) && is.null(loo$psis_object)) { - cli::cli_abort(c( - "No {.field psis_object} found in {.arg loo}.", - "i" = "Did you run {.code loo(..., save_psis = TRUE)}?" - )) - } - .warn_posthoc(loo, measures) - } else { - if (is.null(psis_object) && !is.null(predperf$psis_object)) { - cli::cli_inform("Using psis_object for LOO CV from `predperf`") - psis_object <- predperf$psis_object - } + if (is.null(predperf) && !is.null(loo) && is.null(loo$psis_object)) { + cli::cli_abort(c( + "No {.field psis_object} found in {.arg loo}.", + "i" = "Did you run {.code loo(..., save_psis = TRUE)}?" + )) } checkmate::assert_null(ylp_test) } else if (source == "insample") { @@ -157,6 +154,12 @@ do_pred_measure <- function( ylp = ylp, r_eff = 1 ) + posthoc <- if (is.null(predperf)) { + .detect_posthoc(loo) + } else { + attr(predperf, "posthoc") + } + .warn_posthoc(posthoc, measures) } log_weights <- if (!is.null(psis_object)) psis_object$log_weights else NULL @@ -249,19 +252,19 @@ do_pred_measure <- function( save_psis = save_psis ) - .add_attributes( + predperf_res <- .add_attributes( save_psis, predperf_res, - y, - ypred, - mupred, - ylp, - ylp_test, + dims, kfold, loo, predperf, source ) + if (source == "loo") { + attr(predperf_res, "posthoc") <- posthoc + } + predperf_res } # internal helper functions --------------------------------------------------- @@ -292,13 +295,12 @@ do_pred_measure <- function( #' measures use `psis_object$log_weights` with the original draws in `ypred` #' and `mupred`, so their values are not corrected. #' -#' @param loo A [loo::loo()] result with a `psis_object`. +#' @param method Method names from `.detect_posthoc()`, or `NULL`. #' @param measures Measure entries from `.prepare_measures()`. #' #' @return `NULL`, invisibly. Called for the warning. #' @noRd -.warn_posthoc <- function(loo, measures) { - method <- .detect_posthoc(loo) +.warn_posthoc <- function(method, measures) { if (is.null(method)) { return(invisible(NULL)) } @@ -327,7 +329,8 @@ do_pred_measure <- function( #' \item If both `psis_object` and `loo` are provided, return `psis_object` #' after verifying it matches `loo$psis_object`. #' \item Extract from `loo$psis_object` when `loo` is provided. -#' \item Use the supplied `psis_object`. +#' \item Use the supplied `psis_object` after verifying it matches the +#' weights stored in `predperf`. #' \item Reuse `predperf$psis_object` when accumulating measures. #' \item Reuse `predperf$log_weights` when only the weights were stored #' (`save_psis = FALSE`); the result carries no `diagnostics`. @@ -354,21 +357,18 @@ do_pred_measure <- function( ) { # psis_object + loo are both provided -> return psis_object if (!is.null(psis_object) && !is.null(loo)) { - psis_equal_loo <- isTRUE(all.equal( - psis_object$log_weights, - loo$psis_object$log_weights - )) - if (!psis_equal_loo) { - cli::cli_abort( - "Provided `psis_object` and `loo$psis_object` are not identical." - ) - } + .check_psis_match(psis_object, loo$psis_object$log_weights, "loo") return(psis_object) # loo is provided } else if (!is.null(loo)) { return(loo$psis_object) # psis_object is provided } else if (!is.null(psis_object)) { + log_weights <- predperf$log_weights + if (is.null(log_weights)) { + log_weights <- predperf$psis_object$log_weights + } + .check_psis_match(psis_object, log_weights, "predperf") return(psis_object) # predperf with psis_object is provided } else if (!is.null(predperf$psis_object)) { @@ -391,6 +391,28 @@ do_pred_measure <- function( )) }} +#' Check that a `psis_object` matches the stored PSIS results +#' +#' Compares the log weights. Without stored log weights there is no check. +#' +#' @param psis_object The supplied `psis` object. +#' @param log_weights Stored log weights, or `NULL`. +#' @param arg Name of the argument that holds the stored results. +#' +#' @return `NULL`, invisibly. Called for the error. +#' @noRd +.check_psis_match <- function(psis_object, log_weights, arg) { + if (is.null(log_weights)) { + return(invisible(NULL)) + } + if (!isTRUE(all.equal(psis_object$log_weights, log_weights))) { + cli::cli_abort( + "{.arg psis_object} does not match the PSIS results in {.arg {arg}}." + ) + } + invisible(NULL) +} + #' Extract estimate and SE from a measure result #' #' `.create_measure_structure()` gives every builtin measure an `estimates` @@ -756,7 +778,7 @@ do_pred_measure <- function( #' measure object. #' #' When updating an existing result (`predperf` is not `NULL`), copies attributes -#' from `predperf` and refreshes `dims` from newly supplied input matrices. +#' from `predperf`. #' Merges `measure_info` from the prior result with any new entries supplied on #' `predperf_res` (from \code{.build_pred_measure()}). #' When `save_psis = FALSE`, clears any stored `psis_object` from the prior @@ -770,12 +792,7 @@ do_pred_measure <- function( #' @param save_psis Logical; when `FALSE` and accumulating, clears stored #' `psis_object` from the prior result. #' @param predperf_res List returned by \code{.build_pred_measure()}. -#' @param y Vector of observed values; used indirectly via matrix `dims`. -#' @param ypred Matrix of posterior predictive draws; used to set `dims`. -#' @param mupred Matrix of posterior expected values; used to set `dims`. -#' @param ylp Matrix of pointwise log predictive densities; used to set `dims`. -#' @param ylp_test Matrix of holdout log predictive densities; sets `dims` for -#' `source = "test"`. +#' @param dims Number of draws and observations from `.pred_measure_dims()`. #' @param kfold Optional `kfold` object whose attributes are inherited. #' @param loo Optional [loo::loo()] object whose attributes are inherited. #' @param predperf Existing object when accumulating measures, or `NULL`. @@ -788,11 +805,7 @@ do_pred_measure <- function( .add_attributes <- function( save_psis, predperf_res, - y, - ypred, - mupred, - ylp, - ylp_test, + dims, kfold, loo, predperf, @@ -809,16 +822,6 @@ do_pred_measure <- function( predperf, setdiff(names(attributes(predperf)), "names") ) - - dims <- if (!is.null(ypred)) { - dim(ypred) - } else if (!is.null(mupred)) { - dim(mupred) - } else if (!is.null(ylp)) { - dim(ylp) - } else { - attr(predperf, "dims") - } attr(predperf_res, "dims") <- dims measure_info <- attr(predperf, "measure_info") if (is.null(measure_info)) { @@ -850,17 +853,8 @@ do_pred_measure <- function( test = , # fall through (same as insample) insample = predperf_res ) - - if (source %in% c("insample", "test") || - (is.null(attr(predperf_res, "dims")) && !is.null(ylp))){ - # make attribute names consistent between pred_measure classes - if (source == "test") { - attr(predperf_res, "dims") <- attr(ylp_test, "dim") - } else { - attr(predperf_res, "dims") <- attr(ylp, "dim") - } - } - + attr(predperf_res, "dims") <- dims + classes <- c( switch( source, diff --git a/R/pred_measure-helpers.R b/R/pred_measure-helpers.R index 0fd9ea0d..f1fd0e4a 100644 --- a/R/pred_measure-helpers.R +++ b/R/pred_measure-helpers.R @@ -76,12 +76,11 @@ .measure_entry_custom <- function(fun, name = NULL) { if (is.null(name)) { name <- attr(fun, "measure_name", exact = TRUE) - if (is.null(name) || length(name) != 1L || !nzchar(name)) { - stop( - "A custom measure needs a name. Create it with ", - "custom_measure(fun, name = \"my_metric\").", - call. = FALSE - ) + if (!checkmate::test_string(name, min.chars = 1L)) { + cli::cli_abort(c( + "A custom measure needs a name: a single non-empty string.", + "i" = "Create it with {.code custom_measure(fun, name = \"my_metric\")}." + )) } } else { attr_name <- attr(fun, "measure_name", exact = TRUE) @@ -94,6 +93,12 @@ )) } } + if (name %in% c(supported_measures_list, "p")) { + cli::cli_abort(c( + "Custom measure name {.val {name}} is reserved.", + "i" = "Built-in measure names and {.val p} cannot name a custom measure." + )) + } loss <- attr(fun, "measure_loss", exact = TRUE) if (is.null(loss)) { @@ -309,6 +314,74 @@ invisible(res) } +#' Validate the `psis_object` argument +#' +#' @param psis_object Object to validate, or `NULL`. +#' +#' @return `NULL`, invisibly, on success. +#' @noRd +.validate_psis_object <- function(psis_object) { + if (is.null(psis_object) || is.psis(psis_object)) { + return(invisible(NULL)) + } + cli::cli_abort(c( + "{.arg psis_object} must be a {.cls psis} object, not {.obj_type_friendly {psis_object}}.", + "i" = if (is.loo(psis_object)) { + "Pass a {.cls loo} object to {.arg loo} in {.fn loo_pred_measure}." + } + )) +} + +#' Number of draws and observations of the inputs +#' +#' Reads `S` and `N` from every input and from the stored `dims` of +#' `predperf`. For `source = "test"`, the training `ylp` has another `N` and +#' is not read. +#' +#' @inheritParams pred_measure_params +#' +#' @return Integer vector `c(S, N)`. `S` is `NA` when no input has draws. +#' @noRd +.pred_measure_dims <- function( + source, y, ypred, mupred, ylp, ylp_test, psis_object, loo, kfold, predperf +) { + draws <- list( + ypred = ypred, + mupred = mupred, + ylp = if (source != "test") ylp, + ylp_test = ylp_test, + psis_object = psis_object$log_weights + ) + draws <- Filter(function(x) length(dim(x)) >= 2L, draws) + stored <- attr(predperf, "dims") + sizes <- list( + draws = c( + predperf = stored[1], + loo = dim(loo)[1], + vapply(draws, nrow, integer(1L)) + ), + observations = c( + predperf = stored[2], + loo = dim(loo)[2], + kfold = nrow(kfold$pointwise), + y = if (!is.null(y)) length(y), + vapply(draws, ncol, integer(1L)) + ) + ) + sizes <- lapply(sizes, function(n) n[!is.na(n)]) + for (what in names(sizes)) { + n <- sizes[[what]] + if (length(unique(n)) > 1L) { + inputs <- paste0("{.arg ", names(n), "}: ", n) + cli::cli_abort(c( + "The inputs do not agree on the number of {what}.", + stats::setNames(inputs, rep("x", length(n))) + )) + } + } + unname(c(sizes$draws[1], sizes$observations[1])) +} + #' Validate a numeric matrix argument #' #' @description diff --git a/R/pred_measure.R b/R/pred_measure.R index f4cfeaa8..dfb83f1c 100644 --- a/R/pred_measure.R +++ b/R/pred_measure.R @@ -226,6 +226,7 @@ loo_pred_measure <- function( save_psis = FALSE, control = list() ) { + .validate_psis_object(psis_object) do_pred_measure( y = y, ypred = ypred, @@ -494,6 +495,7 @@ pred_measure <- function( "i" = "Got an object of class {.cls {class(predperf)[1]}}." )) } + .validate_psis_object(psis_object) do_pred_measure( y = y, @@ -553,7 +555,7 @@ custom_measure <- function( fun, name, se_diff_fun = NULL, loss = FALSE ) { if (!is.function(fun)) { - stop("'fun' must be a function.", call. = FALSE) + cli::cli_abort("{.arg fun} must be a function.") } attr(fun, "measure_name") <- name attr(fun, "measure_loss") <- loss diff --git a/R/print.R b/R/print.R index f8089a3a..c69656a9 100644 --- a/R/print.R +++ b/R/print.R @@ -336,13 +336,12 @@ convert_old_object <- function(x, digits = 1, ...) { #' @export print.pred_measure <- function(x, digits = NULL, ...) { dims <- attr(x, "dims") - if (is.null(dims) && !is.null(x$log_weights)) { - dims <- dim(x$log_weights) - } source <- .pred_measure_source_label(x) cat("\n") - if (!is.null(dims) && length(dims) == 2) { + if (length(dims) == 2 && is.na(dims[1])) { + cat(sprintf("Computed from %s observations.\n", dims[2])) + } else if (length(dims) == 2) { cat( sprintf( "Computed from %s posterior draws and %s observations.\n", diff --git a/tests/testthat/test_compare.R b/tests/testthat/test_compare.R index ee4937f8..75dceef8 100644 --- a/tests/testthat/test_compare.R +++ b/tests/testthat/test_compare.R @@ -1740,6 +1740,23 @@ test_that("model_compare compares kfold_pred_measure objects", { colnames(comp))) }) +test_that("model_compare compares loo_pred_measure objects made from a psis_object", { + res <- .compare_src_res() + set.seed(4321) + p1 <- loo_pred_measure( + psis_object = res$loo$psis_object, y = res$y, mupred = res$mupred, + measures = "rmse" + ) + p2 <- loo_pred_measure( + psis_object = res$loo$psis_object, y = res$y, + mupred = .jitter_mupred(res$mupred, 3), measures = "rmse" + ) + expect_no_error( + comp <- suppressMessages(model_compare(list(m1 = p1, m2 = p2))) + ) + expect_s3_class(comp, "compare.loo") +}) + test_that("model_compare compares test_pred_measure objects", { res_cv <- readRDS("data-for-tests/test_data_sleep_cv.Rds") set.seed(4321) diff --git a/tests/testthat/test_pred_measure.R b/tests/testthat/test_pred_measure.R index 218424dc..12501ff2 100644 --- a/tests/testthat/test_pred_measure.R +++ b/tests/testthat/test_pred_measure.R @@ -121,6 +121,17 @@ test_that(".get_psis_object() accepts loo and psis_object together", { ) }) +test_that(".get_psis_object() errors if psis_object does not match loo", { + other <- res$loo$psis_object + other$log_weights <- other$log_weights[rev(seq_len(nrow(other$log_weights))), ] + expect_error( + .get_psis_object( + ylp = NULL, loo = res$loo, predperf = NULL, psis_object = other + ), + regexp = "does not match" + ) +}) + ## .merge_matrix() --------------------------- test_that(".merge_matrix() works as expected", { @@ -303,6 +314,137 @@ test_that("pred_measure() keeps dims when the update has no matrix input", { expect_equal(attr(updated, "dims"), attr(predperf_loo, "dims")) }) +test_that("dims is c(S, N) for every source", { + S <- nrow(res$ylp) + N <- length(res$y) + insample <- insample_pred_measure( + y = res$y, mupred = res$mupred, measures = "rmse" + ) + expect_equal(attr(insample, "dims"), c(S, N)) + from_psis <- loo_pred_measure( + psis_object = res$loo$psis_object, y = res$y, mupred = res$mupred, + measures = "rmse" + ) + expect_equal(attr(from_psis, "dims"), c(S, N)) + + kfold_only <- kfold_pred_measure(kfold = res$kfold) + expect_equal(attr(kfold_only, "dims"), c(NA, N)) + expect_output(print(kfold_only), "Computed from 53 observations") + updated <- pred_measure( + y = res$y, mupred = res$mupred, predperf = kfold_only, measures = "rmse" + ) + expect_equal(attr(updated, "dims"), c(S, N)) +}) + +test_that("a vector mupred or ypred passes the dims check", { + expect_message( + insample_pred_measure( + y = res$y, mupred = colMeans(res$mupred), measures = "mae" + ), + "Coercing" + ) + expect_error( + insample_pred_measure(y = res$y, ypred = res$ypred[1, ], measures = "rps"), + "`ypred` must be a numeric matrix or array" + ) +}) + +test_that("pred_measure inputs must agree on the number of draws and observations", { + expect_error( + insample_pred_measure(y = res$y, ylp = t(res$ylp)), + regexp = "number of observations" + ) + expect_error( + insample_pred_measure( + y = res$y, ypred = res$ypred[1:100, ], mupred = res$mupred, + measures = c("rmse", "rps") + ), + regexp = "number of draws" + ) + predperf_loo <- loo_pred_measure( + loo = res$loo, y = res$y, mupred = res$mupred, measures = "r2" + ) + expect_error( + pred_measure( + y = res$y, ypred = res$ypred[1:100, ], predperf = predperf_loo, + measures = "rps" + ), + regexp = "number of draws" + ) +}) + +test_that("loo_pred_measure() and pred_measure() error if psis_object is not a psis object", { + expect_error( + loo_pred_measure(ylp = res$ylp, psis_object = res$loo), + regexp = "must be a object.*loo_pred_measure" + ) + predperf_loo <- loo_pred_measure(loo = res$loo) + expect_error( + pred_measure(predperf = predperf_loo, psis_object = list()), + regexp = "must be a object" + ) +}) + +test_that("pred_measure() errors if psis_object does not match the stored weights", { + predperf_loo <- loo_pred_measure( + loo = res$loo, y = res$y, mupred = res$mupred, measures = "r2" + ) + other <- res$loo$psis_object + other$log_weights <- other$log_weights[rev(seq_len(nrow(other$log_weights))), ] + expect_error( + pred_measure( + y = res$y, mupred = res$mupred, predperf = predperf_loo, + psis_object = other, measures = "mae" + ), + regexp = "does not match" + ) + updated <- pred_measure( + y = res$y, mupred = res$mupred, predperf = predperf_loo, + psis_object = res$loo$psis_object, measures = "mae" + ) + expect_true("mae_loo" %in% rownames(updated$estimates)) +}) + +test_that("pred_measure() checks psis_object only when the user passes one", { + predperf_loo <- loo_pred_measure( + loo = res$loo, y = res$y, mupred = res$mupred, measures = "r2", + save_psis = TRUE + ) + local_mocked_bindings(.check_psis_match = function(...) stop("checked")) + expect_no_error( + pred_measure( + predperf = predperf_loo, y = res$y, mupred = res$mupred, measures = "mae" + ) + ) +}) + +test_that("loo_pred_measure() errors for a loo without psis_object and a psis_object", { + loo_nosave <- res$loo + loo_nosave$psis_object <- NULL + expect_error( + loo_pred_measure( + loo = loo_nosave, psis_object = res$loo$psis_object, + y = res$y, mupred = res$mupred, measures = c("elpd", "r2") + ), + regexp = "No psis_object found" + ) +}) + +test_that("pred_measure() warns for non-elpd measures after moment matching", { + loo_mm <- res$loo + attr(loo_mm, "posthoc") <- "moment_match" + expect_no_warning( + predperf_mm <- loo_pred_measure(loo = loo_mm, measures = "elpd") + ) + expect_equal(attr(predperf_mm, "posthoc"), "moment_match") + expect_warning( + pred_measure( + y = res$y, mupred = res$mupred, predperf = predperf_mm, measures = "mae" + ), + regexp = "moment_match" + ) +}) + test_that("pred_measure() reuses stored log_weights when save_psis = FALSE", { predperf_loo <- loo_pred_measure( loo = res$loo, y = res$y, mupred = res$mupred, ylp = res$ylp, diff --git a/tests/testthat/test_pred_measure_helpers.R b/tests/testthat/test_pred_measure_helpers.R index 3b7f81d8..1f5e03e9 100644 --- a/tests/testthat/test_pred_measure_helpers.R +++ b/tests/testthat/test_pred_measure_helpers.R @@ -84,14 +84,25 @@ test_that("custom_measure() sets the attributes", { }) test_that("custom_measure() errors on invalid input", { - expect_error(custom_measure("x", name = "m"), regexp = "'fun' must be a function") + expect_error(custom_measure("x", name = "m"), regexp = "must be a function") expect_error(custom_measure(function(y) NULL, name = "m", loss = NA), regexp = "declare loss") expect_error(custom_measure(function(y) NULL, name = "m", se_diff_fun = "median"), regexp = "Invalid") - for (bad in list("", NULL, c("a", "b"))) { + for (bad in list("", NULL, c("a", "b"), 1, NA_character_)) { expect_error(custom_measure(function(y) NULL, name = bad), regexp = "needs a name") } }) +test_that("custom_measure() errors on a reserved name", { + for (reserved in c("elpd", "rmse", "srps", "p")) { + expect_error( + custom_measure(function(y) NULL, name = reserved), + regexp = "is reserved" + ) + } + f <- function(y, mupred) list(estimate = 1, se = 0, pointwise = y) + expect_error(.normalize_measure(list(elpd = f)), regexp = "is reserved") +}) + # .prepare_measures() ----------------------------------------------- test_that(".prepare_measures() errors on invalid built-in names", {