diff --git a/R/E_loo.R b/R/E_loo.R index 3f783205..66875b5b 100644 --- a/R/E_loo.R +++ b/R/E_loo.R @@ -5,19 +5,21 @@ #' smoothing procedure. The expectations estimated by the `E_loo()` function #' assume that the PSIS approximation is working well. #' **A small [Pareto k][pareto-k-diagnostic] estimate is necessary, -#' but not sufficient, for `E_loo()` to give reliable estimates**. If the -#' `log_ratios` argument is provided, `E_loo()` also computes a function -#' specific Pareto k diagnostic, which must also be small for a reliable -#' estimate. See more details below. +#' but not sufficient, for `E_loo()` to give reliable estimates**. `E_loo()` +#' also computes a function specific Pareto k diagnostic, which must also be +#' small for a reliable estimate. This diagnostic is more accurate if the +#' `log_ratios` argument is provided. See more details below. #' #' @export #' @param x A numeric vector or matrix. #' @param psis_object An object returned by [psis()]. #' @param log_ratios Optionally, a vector or matrix (the same dimensions as `x`) -#' of raw (not smoothed) log ratios. If working with log-likelihood values, -#' the log ratios are the **negative** of those values. If `log_ratios` is -#' specified we are able to compute more accurate [Pareto k][pareto-k-diagnostic] -#' diagnostics specific to `E_loo()`. +#' of the raw (not smoothed) log ratios from which `psis_object` was computed. +#' If working with log-likelihood values, the log ratios are the **negative** +#' of those values. If `log_ratios` is specified we are able to compute more +#' accurate [Pareto k][pareto-k-diagnostic] diagnostics specific to `E_loo()`. +#' `NA`, `NaN` and `Inf` values give an error. `-Inf` values (zero ratios) +#' are allowed. #' @param type The type of expectation to compute. The options are #' `"mean"`, `"variance"`, `"sd"`, and `"quantile"`. #' @param probs For computing quantiles, a vector of probabilities. @@ -44,9 +46,7 @@ #' For the matrix method it will be a vector of length `ncol(x)` #' containing estimates of the shape parameter \eqn{k} of the #' generalized Pareto distribution. For the default/vector method, -#' the estimate is a scalar. If `log_ratios` is not specified when -#' calling `E_loo()`, the smoothed log-weights are used to estimate -#' Pareto-k's, which may produce optimistic estimates. +#' the estimate is a scalar. #' #' For `type="mean"`, `type="var"`, and `type="sd"`, the returned Pareto-k is #' usually the maximum of the Pareto-k's for the left and right tail of \eqn{hr} @@ -54,6 +54,11 @@ #' \eqn{h=x} for `type="mean"` and \eqn{h=x^2} for `type="var"` and `type="sd"`. #' If \eqn{h} is binary, constant, or not finite, or if `type="quantile"`, the #' returned Pareto-k is the Pareto-k for the right tail of \eqn{r}. +#' +#' The Pareto-k for the right tail of \eqn{r} is the Pareto-k of +#' `psis_object`. If `log_ratios` is not specified when calling `E_loo()`, +#' the smoothed log-weights are used to estimate the Pareto-k's for the tails +#' of \eqn{hr}, which may produce optimistic estimates. #' } #' } #' @@ -113,6 +118,9 @@ E_loo.default <- length(x) == dim(psis_object)[1], is.null(log_ratios) || (length(x) == length(log_ratios)) ) + if (!is.null(log_ratios)) { + validate_ll(log_ratios) + } type <- match.arg(type) E_fun <- .E_fun(type) w <- as.vector(weights(psis_object, log = FALSE)) @@ -121,7 +129,7 @@ E_loo.default <- if (is.null(log_ratios)) { # Use of smoothed ratios gives slightly optimistic - # Pareto-k's, but these are still better than nothing + # Pareto-k's for h * r, but these are still better than nothing log_ratios <- weights(psis_object, log = TRUE) } h <- switch( @@ -150,6 +158,9 @@ E_loo.matrix <- identical(dim(x), dim(psis_object)), is.null(log_ratios) || identical(dim(x), dim(log_ratios)) ) + if (!is.null(log_ratios)) { + validate_ll(log_ratios) + } type <- match.arg(type) E_fun <- .E_fun(type) fun_val <- numeric(1) @@ -169,7 +180,7 @@ E_loo.matrix <- if (is.null(log_ratios)) { # Use of smoothed ratios gives slightly optimistic - # Pareto-k's, but these are still better than nothing + # Pareto-k's for h * r, but these are still better than nothing log_ratios <- weights(psis_object, log = TRUE) } h <- switch( @@ -256,31 +267,34 @@ E_loo.matrix <- #' Compute function-specific k-hat diagnostics #' #' @noRd +#' @param psis_object An object returned by `psis()`. It provides the k-hat +#' estimates for the ratios and the tail lengths. #' @param log_ratios Vector or matrix of raw (not smoothed) log ratios with the #' same dimensions as `x`. If working with log-likelihood values, the log #' ratios are the negative of those values. -#' @return Vector (of length `NCOL(x)`) of k-hat estimates. +#' @return Vector (of length `NCOL(log_ratios)`) of k-hat estimates. #' E_loo_khat <- function(x, psis_object, log_ratios, ...) { UseMethod("E_loo_khat") } #' @export E_loo_khat.default <- function(x, psis_object, log_ratios, ...) { - .E_loo_khat_i(x, log_ratios, attr(psis_object, "tail_len")) + .E_loo_khat_i( + x, + log_ratios, + attr(psis_object, "tail_len"), + pareto_k_values(psis_object) + ) } #' @export E_loo_khat.matrix <- function(x, psis_object, log_ratios, ...) { tail_lengths <- attr(psis_object, "tail_len") + khat_r <- pareto_k_values(psis_object) .collect_warnings( - if (is.null(x)) { - sapply(seq_len(ncol(log_ratios)), function(i) { - .E_loo_khat_i(x, log_ratios[, i], tail_lengths[i]) - }) - } else { - sapply(seq_len(ncol(log_ratios)), function(i) { - .E_loo_khat_i(x[, i], log_ratios[, i], tail_lengths[i]) - }) - } + sapply(seq_len(ncol(log_ratios)), function(i) { + # x[, i] is NULL if x is NULL + .E_loo_khat_i(x[, i], log_ratios[, i], tail_lengths[i], khat_r[i]) + }) ) } @@ -291,28 +305,25 @@ E_loo_khat.matrix <- function(x, psis_object, log_ratios, ...) { #' @param log_ratios_i S-vector of log_ratios, log(r(theta)), for a single #' observation. #' @param tail_len_i Integer tail length used for fitting GPD. +#' @param khat_r_i Scalar k-hat estimate for the right tail of r(theta), as +#' computed by `psis()`. #' @return Scalar h-specific k-hat estimate. #' -.E_loo_khat_i <- function(x_i, log_ratios_i, tail_len_i) { - h_theta <- x_i - r_theta <- exp(log_ratios_i - max(log_ratios_i)) - khat_r <- posterior::pareto_khat(r_theta, tail = "right", ndraws_tail = tail_len_i) - if (is.list(khat_r)) { # retain compatiblity with older posterior that returned a list - khat_r <- khat_r$khat - } - if (is.null(x_i) || is_constant(x_i) || length(unique(x_i))==2 || +.E_loo_khat_i <- function(x_i, log_ratios_i, tail_len_i, khat_r_i) { + if (is.null(x_i) || is_constant(x_i) || length(unique(x_i)) == 2 || anyNA(x_i) || any(is.infinite(x_i))) { - khat_r - } else { - khat_hr <- posterior::pareto_khat(h_theta * r_theta, tail = "both", ndraws_tail = tail_len_i) - if (is.list(khat_hr)) { # retain compatiblity with older posterior that returned a list - khat_hr <- khat_hr$khat - } - if (is.na(khat_hr) && is.na(khat_r)) { - k <- NA - } else { - k <- max(khat_hr, khat_r, na.rm=TRUE) - } - k + return(khat_r_i) + } + # scale so that the largest |h * r| is 1, which avoids underflow for small |h| + log_hr <- log(abs(x_i)) + log_ratios_i + # h * r is 0 for all draws + if (!is.finite(max(log_hr))) { + return(khat_r_i) } + khat_hr <- posterior::pareto_khat( + sign(x_i) * exp(log_hr - max(log_hr)), + tail = "both", + ndraws_tail = tail_len_i + ) + if (is.na(khat_hr)) khat_r_i else max(khat_hr, khat_r_i) } diff --git a/man/E_loo.Rd b/man/E_loo.Rd index eeb1b231..aa7f3521 100644 --- a/man/E_loo.Rd +++ b/man/E_loo.Rd @@ -39,10 +39,12 @@ E_loo(x, psis_object, ...) \item{probs}{For computing quantiles, a vector of probabilities.} \item{log_ratios}{Optionally, a vector or matrix (the same dimensions as \code{x}) -of raw (not smoothed) log ratios. If working with log-likelihood values, -the log ratios are the \strong{negative} of those values. If \code{log_ratios} is -specified we are able to compute more accurate \link[=pareto-k-diagnostic]{Pareto k} -diagnostics specific to \code{E_loo()}.} +of the raw (not smoothed) log ratios from which \code{psis_object} was computed. +If working with log-likelihood values, the log ratios are the \strong{negative} +of those values. If \code{log_ratios} is specified we are able to compute more +accurate \link[=pareto-k-diagnostic]{Pareto k} diagnostics specific to \code{E_loo()}. +\code{NA}, \code{NaN} and \code{Inf} values give an error. \code{-Inf} values (zero ratios) +are allowed.} } \value{ A named list with the following components: @@ -66,9 +68,7 @@ Function-specific diagnostic. For the matrix method it will be a vector of length \code{ncol(x)} containing estimates of the shape parameter \eqn{k} of the generalized Pareto distribution. For the default/vector method, -the estimate is a scalar. If \code{log_ratios} is not specified when -calling \code{E_loo()}, the smoothed log-weights are used to estimate -Pareto-k's, which may produce optimistic estimates. +the estimate is a scalar. For \code{type="mean"}, \code{type="var"}, and \code{type="sd"}, the returned Pareto-k is usually the maximum of the Pareto-k's for the left and right tail of \eqn{hr} @@ -76,6 +76,11 @@ and the right tail of \eqn{r}, where \eqn{r} is the importance ratio and \eqn{h=x} for \code{type="mean"} and \eqn{h=x^2} for \code{type="var"} and \code{type="sd"}. If \eqn{h} is binary, constant, or not finite, or if \code{type="quantile"}, the returned Pareto-k is the Pareto-k for the right tail of \eqn{r}. + +The Pareto-k for the right tail of \eqn{r} is the Pareto-k of +\code{psis_object}. If \code{log_ratios} is not specified when calling \code{E_loo()}, +the smoothed log-weights are used to estimate the Pareto-k's for the tails +of \eqn{hr}, which may produce optimistic estimates. } } } @@ -85,10 +90,10 @@ quantiles) using the importance weights obtained from the \link[=psis]{PSIS} smoothing procedure. The expectations estimated by the \code{E_loo()} function assume that the PSIS approximation is working well. \strong{A small \link[=pareto-k-diagnostic]{Pareto k} estimate is necessary, -but not sufficient, for \code{E_loo()} to give reliable estimates}. If the -\code{log_ratios} argument is provided, \code{E_loo()} also computes a function -specific Pareto k diagnostic, which must also be small for a reliable -estimate. See more details below. +but not sufficient, for \code{E_loo()} to give reliable estimates}. \code{E_loo()} +also computes a function specific Pareto k diagnostic, which must also be +small for a reliable estimate. This diagnostic is more accurate if the +\code{log_ratios} argument is provided. See more details below. } \examples{ \donttest{ diff --git a/tests/testthat/test_E_loo.R b/tests/testthat/test_E_loo.R index cc7f75c1..21e73dc5 100644 --- a/tests/testthat/test_E_loo.R +++ b/tests/testthat/test_E_loo.R @@ -252,8 +252,97 @@ test_that("E_loo pareto_k does not depend on the scale of x", { skip_if(posterior:::is_constant(c(1e-20, 2e-20)), "posterior::is_constant() has an absolute tolerance") k <- E_loo(x, psis_mat, type = "mean", log_ratios = log_rats)$pareto_k - for (s in c(1e-20, 1e-200)) { + # with 1e-307, h * r underflows unless the scaling includes h + for (s in c(1e-20, 1e-200, 1e-307)) { k_s <- E_loo(s * x, psis_mat, type = "mean", log_ratios = log_rats)$pareto_k expect_equal(k_s, k, tolerance = 1e-10) } }) + +test_that("E_loo pareto_k for the ratios is the psis() pareto_k", { + k_psis <- pareto_k_values(psis_mat) + # quantiles and a binary x use only the k for the ratios + expect_identical(E_test_quant$pareto_k, k_psis) + expect_identical(E_test_quant_vec$pareto_k, pareto_k_values(psis_vec)) + k_bin <- E_loo(0 + (x > 0), psis_mat, log_ratios = log_rats)$pareto_k + expect_identical(k_bin, k_psis) + # also without log_ratios + k_quant <- E_loo(x, psis_mat, type = "quantile", probs = 0.5)$pareto_k + expect_identical(k_quant, k_psis) + # the k for h * r can only increase the result + expect_true(all(E_test_mean$pareto_k >= k_psis)) + expect_true(any(E_test_mean$pareto_k > k_psis)) +}) + +test_that("E_loo pareto_k is Inf if the psis() pareto_k is Inf", { + S <- 1000 + set.seed(1) + x_cont <- rnorm(S) + x_bin <- rbinom(S, 1, 0.5) + lrs <- list( + # 30 draws have log ratios near the maximum. For the other draws, + # exp(log_ratios - max(log_ratios)) underflows to 0, so the generalized + # Pareto fit of the tail fails + underflow = c(rnorm(30), rnorm(S - 30) - 1e6), + constant = rep(0, S) + ) + k_of <- function(...) suppressWarnings(E_loo(...))$pareto_k + for (nm in names(lrs)) { + lr <- lrs[[nm]] + ps <- suppressWarnings(psis(lr, r_eff = 1)) + expect_identical(pareto_k_values(ps), Inf, info = nm) + expect_identical(k_of(x_cont, ps, log_ratios = lr), Inf, info = nm) + expect_identical(k_of(x_bin, ps, log_ratios = lr), Inf, info = nm) + expect_identical(k_of(x_cont, ps), Inf, info = nm) + expect_identical( + k_of(x_cont, ps, type = "quantile", probs = 0.5, log_ratios = lr), + Inf, + info = nm + ) + } + + # matrix method: only the first column has an Inf k + lr_mat <- cbind(lrs$underflow, rnorm(S)) + ps_mat <- suppressWarnings(psis(lr_mat, r_eff = c(1, 1))) + k_mat <- k_of(cbind(x_cont, x_cont), ps_mat, log_ratios = lr_mat) + expect_identical(is.finite(k_mat), c(FALSE, TRUE)) + expect_gte(k_mat[2], pareto_k_values(ps_mat)[2]) + + # tail too short for the generalized Pareto fit + lr_short <- rnorm(20) + ps_short <- suppressWarnings(psis(lr_short, r_eff = 1)) + expect_identical(pareto_k_values(ps_short), Inf) + expect_identical(k_of(rnorm(20), ps_short, log_ratios = lr_short), Inf) +}) + +test_that("E_loo pareto_k is the psis() pareto_k if h * r is constant", { + S <- 1000 + set.seed(1) + lr <- c(rep(-Inf, S / 2), rnorm(S / 2)) + ps <- suppressWarnings(psis(lr, r_eff = 1)) + # x is not constant, but x * r is 0 for all draws + x_zero <- c(rnorm(S / 2), rep(0, S / 2)) + expect_no_warning(k <- E_loo(x_zero, ps, log_ratios = lr)$pareto_k) + expect_true(is.finite(k)) + expect_identical(k, pareto_k_values(ps)) +}) + +test_that("E_loo gives an error if log_ratios has NA, NaN or +Inf", { + S <- 1000 + set.seed(3) + lr <- 2 * rexp(S) + x_cont <- rnorm(S) + ps <- suppressWarnings(psis(lr, r_eff = 1)) + ps_mat <- suppressWarnings(psis(cbind(lr, lr), r_eff = c(1, 1))) + x_mat <- cbind(x_cont, x_cont) + # the errors of psis() for such log ratios + msg <- "NAs not allowed|finite or -Inf" + for (v in c(NA, NaN, Inf)) { + lr_v <- replace(lr, 1, v) + expect_error(psis(lr_v, r_eff = 1), msg, info = format(v)) + expect_error(E_loo(x_cont, ps, log_ratios = lr_v), msg, info = format(v)) + # matrix method: only the first column has the value + expect_error(E_loo(x_mat, ps_mat, log_ratios = cbind(lr_v, lr)), msg, + info = format(v)) + } +})