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
99 changes: 55 additions & 44 deletions R/E_loo.R
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -44,16 +46,19 @@
#' 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}
#' and the right tail of \eqn{r}, where \eqn{r} is the importance ratio and
#' \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.
#' }
#' }
#'
Expand Down Expand Up @@ -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))
Expand All @@ -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(
Expand Down Expand Up @@ -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)
Expand All @@ -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(
Expand Down Expand Up @@ -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])
})
)
}

Expand All @@ -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

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
log_hr <- log(abs(x_i)) + log_ratios_i
log_hr <- log(abs(x_i)) + log_ratios_i
if (max(log_hr) == -Inf) {
return(khat_r_i)
}

This avoids potentially passing NaN to posterior::pareto_khat(). Right now it works ok to pass NaN but it's undocumented behavior in posterior so I think better to avoid it in case something changes in the future.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I added the check in f08b1cb, but as if (!is.finite(max(log_hr))) instead of == -Inf. E_loo() accepts log_ratios with NA if the psis() object is valid, and then max(log_hr) == -Inf is NA.

What E_loo() gives for the k (posterior 1.8.0):

input before == -Inf !is.finite()
regular max(k of h * r, psis() k) same same
h * r is 0 for all draws psis() k, warning psis() k psis() k
some log ratios are -Inf max(k of h * r, psis() k) same same
one log ratio is NA or NaN psis() k, warning error psis() k
one log ratio is +Inf psis() k, warning psis() k, warning psis() k

where

  • warning: pareto_khat() gets NaN or NA and warns "Input contains infinite or NA values ...".
  • error: E_loo() stops with "missing value where TRUE/FALSE needed".

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks !is.finite() is better. One question though. psis() errors on NA, NaN and +Inf, so if log_ratios has any of those then it can't be the log ratios used to create psis_object, right? In that situation E_loo() now quietly returns the psis k. Maybe we should call validate_ll(log_ratios) in E_loo() when log_ratios is provided? That would throw an error though. If you prefer not to, or to do something else, that's fine. But I wanted to check before we merge this.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Makes sense. I added validate_ll(log_ratios)

# 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)
}
27 changes: 16 additions & 11 deletions man/E_loo.Rd

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

91 changes: 90 additions & 1 deletion tests/testthat/test_E_loo.R
Original file line number Diff line number Diff line change
Expand Up @@ -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))
}
})
Loading