Skip to content
Merged
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
124 changes: 59 additions & 65 deletions R/pred_measure-compute.R
Original file line number Diff line number Diff line change
Expand Up @@ -111,26 +111,23 @@ 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
)
.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") {
Expand All @@ -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
Expand Down Expand Up @@ -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 ---------------------------------------------------
Expand Down Expand Up @@ -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))
}
Expand Down Expand Up @@ -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`.
Expand All @@ -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)) {
Expand All @@ -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`
Expand Down Expand Up @@ -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
Expand All @@ -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`.
Expand All @@ -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,
Expand All @@ -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)) {
Expand Down Expand Up @@ -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,
Expand Down
85 changes: 79 additions & 6 deletions R/pred_measure-helpers.R
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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)) {
Expand Down Expand Up @@ -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
Expand Down
4 changes: 3 additions & 1 deletion R/pred_measure.R
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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
Expand Down
7 changes: 3 additions & 4 deletions R/print.R
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
Loading
Loading