diff --git a/NAMESPACE b/NAMESPACE index 3405d737..05ffb3d1 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -154,6 +154,7 @@ export(psislw) export(relative_eff) export(scrps) export(sis) +export(srs_diff_est) export(stacking_weights) export(tis) export(waic) diff --git a/NEWS.md b/NEWS.md index 05834e1f..9535c404 100644 --- a/NEWS.md +++ b/NEWS.md @@ -45,6 +45,7 @@ comparison table with `simplify = FALSE` by @florence-bockting in #383. * Added contribution section. by @VisruthSK in #286 * Update LOO uncertainty paper to use BA doi by @avehtari in #311 * Update documentation for `E_loo()` function by @avehtari in #312 +* Export `srs_diff_est()` function by @vinniott and @avehtari in #340 # loo 2.8.0 diff --git a/R/loo_subsample.R b/R/loo_subsample.R index 4aad6d46..e3916419 100644 --- a/R/loo_subsample.R +++ b/R/loo_subsample.R @@ -24,7 +24,7 @@ #' same length containing the posterior density and the approximation density #' for the individual draws. #' -#' @seealso [loo()], [psis()], [loo_compare()] +#' @seealso [loo()], [psis()], [loo_compare()], [srs_diff_est()] #' @template loo-large-data-references #' #' @export loo_subsample loo_subsample.function @@ -1166,38 +1166,166 @@ loo_subsample_estimation_diff_srs <- function(x) { update_psis_loo_ss_estimates(x) } -#' Difference estimation using SRS-WOR sampling (Magnusson et al., 2020) -#' @noRd -#' @param y_approx Approximated values of all observations. -#' @param y The values observed. -#' @param y_idx The index of `y` in `y_approx`. -#' @return A list with estimates. -srs_diff_est <- function(y_approx, y, y_idx) { +#' Difference estimator with simple random sampling without replacement. +#' +#' The difference estimator `srs_diff_est()` estimates +#' the expectation \eqn{n E[y]} when we have \eqn{n} approximate values \eqn{\tilde{y}_i}, +#' \eqn{i = 1, \ldots, n} and \eqn{m < n} accurate values \eqn{y_j}, \eqn{j \in \mathcal{S}}, +#' where \eqn{m} is the subsample size and \eqn{\mathcal{S}} is +#' a simple random subsample without replacement. The original +#' approach is by Cochran (1977) and we follow the equations 7--9 by +#' Magnusson et al. (2020). +#' +#' @details In Magnusson et al. (2020) Eq (9) first row, the second `+` should +#' be a `-`; Supplementary Material Eq (6) has this correct. +#' As `srs_diff_est()` in the `loo` package is used for \eqn{n E[y]}, there is +#' a proportional difference of \eqn{1/n} compared to the paper. +#' +#' @param y_approx (numeric) `n` approximated values. +#' @param y (numeric) `m unique() |> scale() |> as.data.frame() +#' +#' fitos <- brm(ordered(quality) ~ ., +#' family = cumulative("logit"), +#' prior = prior(R2D2(mean_R2 = 1/3, prec_R2 = 3)), +#' data = wine_scaled, +#' seed = 1, +#' silent = 2, +#' refresh = 0) +#' +#' log_lik_matrix <- log_lik(fitos) +#' +#' N <- nrow(wine_scaled) +#' Nsub <- 100 +#' +#' # posterior log-score +#' lpd <- elpd(log_lik_matrix) +#' sum(lpd$pointwise[,"elpd"]) +#' +#' # Use PSIS-LOO for subsample of 100 randomly selected observations +#' set.seed(1) +#' idx <- sample(1:N, Nsub) +#' elpd_loo_sub <- loo(log_lik_matrix[,idx]) +#' sum(elpd_loo_sub$pointwise[,"elpd_loo"]) / Nsub * N +#' +#' # Use difference estimator to combine fast result and subsampled accurate result +#' srs_diff_est(lpd$pointwise[,"elpd"], elpd_loo_sub$pointwise[,"elpd_loo"], idx) +#' +#' # Comparison to using PSIS-LOO for all observations +#' loo(log_lik_matrix) +#' } +#' @export +srs_diff_est <- function(y_approx, y, y_idx, weights = NULL) { checkmate::assert_numeric(y_approx) checkmate::assert_numeric(y, max.len = length(y_approx)) - checkmate::assert_integerish(y_idx, len = length(y)) + checkmate::assert_integerish( + y_idx, + len = length(y), + lower = 1, + upper = length(y_approx), + unique = TRUE, + any.missing = FALSE + ) + checkmate::assert_numeric( + weights, + lower = 0, + finite = TRUE, + len = length(y_approx), + null.ok = TRUE + ) + if (!is.null(weights) && isTRUE(sum(weights[y_idx]) == 0)) { + stop("The weights of the subsampled observations must not all be 0.", + call. = FALSE) + } N <- length(y_approx) m <- length(y) + # weights with mean 1 over all observations and over the subsample + if (is.null(weights)) { + w <- 1 + w_m <- 1 + } else { + w <- N * weights / sum(weights) + w_m <- m * weights[y_idx] / sum(weights[y_idx]) + } + # Subtract the (weighted) mean of y_approx from all values, so that the + # sums of squares in eq (9) do not cancel when the values have a large + # common offset. In exact arithmetic, v_y_hat and hat_v_y do not depend on + # the shift; N * shift is added to y_hat at the end. A non-finite mean + # (NA or infinite values) gives no shift. + shift <- sum(w * y_approx) / N + if (!is.finite(shift)) { + shift <- 0 + } + y_approx <- y_approx - shift + y <- y - shift y_approx_m <- y_approx[y_idx] e_i <- y - y_approx_m - t_pi_tilde <- sum(y_approx) - t_pi2_tilde <- sum(y_approx^2) - t_e <- N * mean(e_i) - t_hat_epsilon <- N * mean(difference_of_squares(y, y_approx_m)) + t_pi_tilde <- sum(w * y_approx) + t_pi2_tilde <- sum(w * y_approx^2) + t_e <- N * mean(w_m * e_i) + t_hat_epsilon <- N * mean(w_m * difference_of_squares(y, y_approx_m)) - est_list <- list(m = length(y), N = N) + est_list <- list(m = m, N = N) # eq (7) est_list$y_hat <- t_pi_tilde + t_e - # eq (8) - est_list$v_y_hat <- N^2 * (1 - m / N) * var(e_i) / m + # eq (8); with weights, the difference term is a ratio estimator, and its + # linearization variance is the sample variance of w_m * (e_i - e_mean_w) + e_mean_w <- t_e / N + est_list$v_y_hat <- if (m < 2) { + NA_real_ + } else { + N^2 * (1 - m / N) * sum((w_m * (e_i - e_mean_w))^2) / ((m - 1) * m) + } # eq (9) first row second `+` should be `-` # Supplementary material eq (6) has this correct # Here the variance is for sum, while in the paper the variance is for mean # which explains the proportional difference of 1/N est_list$hat_v_y <- (t_pi2_tilde + t_hat_epsilon) - # a (has been checked) (1/N) * (t_e^2 - est_list$v_y_hat + 2 * t_pi_tilde * est_list$y_hat - t_pi_tilde^2) # b + est_list$y_hat <- est_list$y_hat + N * shift est_list } diff --git a/man/loo_subsample.Rd b/man/loo_subsample.Rd index 6f381db6..5889be1e 100644 --- a/man/loo_subsample.Rd +++ b/man/loo_subsample.Rd @@ -196,5 +196,5 @@ In \emph{Proceedings of the 23rd International Conference on Artificial Intelligence and Statistics (AISTATS)}, PMLR 108:341-351. } \seealso{ -\code{\link[=loo]{loo()}}, \code{\link[=psis]{psis()}}, \code{\link[=loo_compare]{loo_compare()}} +\code{\link[=loo]{loo()}}, \code{\link[=psis]{psis()}}, \code{\link[=loo_compare]{loo_compare()}}, \code{\link[=srs_diff_est]{srs_diff_est()}} } diff --git a/man/srs_diff_est.Rd b/man/srs_diff_est.Rd new file mode 100644 index 00000000..a137ed2c --- /dev/null +++ b/man/srs_diff_est.Rd @@ -0,0 +1,106 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/loo_subsample.R +\name{srs_diff_est} +\alias{srs_diff_est} +\title{Difference estimator with simple random sampling without replacement.} +\usage{ +srs_diff_est(y_approx, y, y_idx, weights = NULL) +} +\arguments{ +\item{y_approx}{(numeric) \code{n} approximated values.} + +\item{y}{(numeric) \code{m unique() |> scale() |> as.data.frame() + +fitos <- brm(ordered(quality) ~ ., + family = cumulative("logit"), + prior = prior(R2D2(mean_R2 = 1/3, prec_R2 = 3)), + data = wine_scaled, + seed = 1, + silent = 2, + refresh = 0) + +log_lik_matrix <- log_lik(fitos) + +N <- nrow(wine_scaled) +Nsub <- 100 + +# posterior log-score +lpd <- elpd(log_lik_matrix) +sum(lpd$pointwise[,"elpd"]) + +# Use PSIS-LOO for subsample of 100 randomly selected observations +set.seed(1) +idx <- sample(1:N, Nsub) +elpd_loo_sub <- loo(log_lik_matrix[,idx]) +sum(elpd_loo_sub$pointwise[,"elpd_loo"]) / Nsub * N + +# Use difference estimator to combine fast result and subsampled accurate result +srs_diff_est(lpd$pointwise[,"elpd"], elpd_loo_sub$pointwise[,"elpd_loo"], idx) + +# Comparison to using PSIS-LOO for all observations +loo(log_lik_matrix) +} +} +\references{ +Magnusson, M., Riis Andersen, M., Jonasson, J. and Vehtari, A. (2020). +Leave-One-Out Cross-Validation for Model Comparison in Large Data. +In \emph{Proceedings of the 23rd International Conference on Artificial +Intelligence and Statistics (AISTATS)}, PMLR 108:341-351. + +Cochran, W. G. (1977). \emph{Sampling Techniques, 3rd Edition}. John Wiley. + +Cortez, P., Cerdeira, A.L., Almeida, F., Matos, T., & Reis, J. (2009). +Modeling wine preferences by data mining from physicochemical properties. +\emph{Decis. Support Syst.}, \emph{47}, 547-553. +} +\seealso{ +\code{\link[=loo_subsample]{loo_subsample()}} +} diff --git a/tests/testthat/test_loo_subsampling_approximations.R b/tests/testthat/test_loo_subsampling_approximations.R index 9e20d412..378b19d9 100644 --- a/tests/testthat/test_loo_subsampling_approximations.R +++ b/tests/testthat/test_loo_subsampling_approximations.R @@ -669,6 +669,155 @@ test_that("srs_diff_est works as expected", { expect_equal(sqrt(res$hat_v_y), sigma_hat_true, tolerance = 0.1) }) +test_that("srs_diff_est with equal weights equals srs_diff_est without weights", { + set.seed(1234) + N <- 200 + m <- 30 + y_approx <- rnorm(N) + y_idx <- seq(3, N, by = 6)[1:m] + y <- y_approx[y_idx] + rnorm(m, sd = 0.2) + res <- srs_diff_est(y_approx, y, y_idx) + # reference values from the unweighted formulas with var(e_i) + expect_equal(res$y_hat, 4.7413161538700166, tolerance = 1e-12) + expect_equal(res$v_y_hat, 42.179689783275506, tolerance = 1e-12) + expect_equal(res$hat_v_y, 196.57069172888566, tolerance = 1e-12) + expect_equal(srs_diff_est(y_approx, y, y_idx, weights = rep(1, N)), res) + expect_equal(srs_diff_est(y_approx, y, y_idx, weights = rep(3, N)), res) +}) + +# Monte Carlo summaries of srs_diff_est() with weights +srs_diff_est_weighted_mc <- function(weights, S = 10000, m = 100) { + N <- length(weights) + y_true <- seq_len(N) + y_approx <- rnorm(N, y_true, 0.1) + w <- N * weights / sum(weights) + sum_y_true <- sum(w * y_true) + v_y_true <- sum(w * y_true^2) - sum_y_true^2 / N + hat_v_y <- y_hat <- se_y_hat <- numeric(S) + for (i in seq_len(S)) { + y_idx <- sample.int(N, size = m) + res <- srs_diff_est(y_approx, y_true[y_idx], y_idx, weights = weights) + y_hat[i] <- res$y_hat + se_y_hat[i] <- sqrt(res$v_y_hat) + hat_v_y[i] <- res$hat_v_y + } + q <- qnorm(0.975) + list( + y_hat = mean(y_hat), sum_y_true = sum_y_true, + hat_v_y = mean(hat_v_y), v_y_true = v_y_true, + coverage = mean(y_hat - q * se_y_hat < sum_y_true & + sum_y_true < y_hat + q * se_y_hat) + ) +} + +test_that("srs_diff_est works as expected with weights", { + set.seed(1234) + mc <- srs_diff_est_weighted_mc(sample(2:7, size = 1000, replace = TRUE)) + expect_equal(mc$y_hat, mc$sum_y_true, tolerance = 0.001) + expect_equal(mc$coverage, 0.95, tolerance = 0.01) + expect_equal(mc$hat_v_y, mc$v_y_true, tolerance = 0.01) + + # heavy-tailed weights: the variance of the weighted differences is needed + set.seed(1234) + mc <- srs_diff_est_weighted_mc(rlnorm(1000), S = 2000) + expect_equal(mc$y_hat, mc$sum_y_true, tolerance = 0.001) + expect_gt(mc$coverage, 0.9) +}) + +test_that("srs_diff_est with weights is exact if all observations are sampled", { + set.seed(1234) + N <- 100 + y_true <- rnorm(N) + y_approx <- y_true + rnorm(N, sd = 0.1) + weights <- runif(N, 0.5, 2) + w <- N * weights / sum(weights) + y_idx <- sample.int(N) + res <- srs_diff_est(y_approx, y_true[y_idx], y_idx, weights = weights) + expect_equal(res$y_hat, sum(w * y_true), tolerance = 1e-10) + expect_equal(res$v_y_hat, 0) + expect_equal(res$hat_v_y, sum(w * y_true^2) - sum(w * y_true)^2 / N, + tolerance = 1e-8) +}) + +test_that("srs_diff_est with weights propagates NA values", { + N <- 50L + y_idx <- seq(1, N, by = 5) + m <- length(y_idx) + res_na <- list(m = m, N = N, y_hat = NA_real_, v_y_hat = NA_real_, + hat_v_y = NA_real_) + w <- rep_len(c(2, 3), N) + expect_identical( + srs_diff_est(rep(-0.8, N), c(rep(-0.7, m - 1), NA), y_idx, weights = w), + res_na + ) + expect_identical( + srs_diff_est(rep(-0.8, N), rep(-0.7, m), y_idx, weights = rep(NA, N)), + res_na + ) +}) + +test_that("srs_diff_est is accurate for values with a large common offset", { + set.seed(1234) + N <- 10000 + m <- 500 + y_approx <- rnorm(N, 0, 0.3) + y_idx <- seq(7, N, by = 20)[1:m] + y <- y_approx[y_idx] + rnorm(m, 0, 0.05) + offset <- 1e6 + weights_zero <- rlnorm(N) + weights_zero[y_idx[1:5]] <- 0 + for (weights in list(NULL, rlnorm(N), weights_zero)) { + res <- srs_diff_est(y_approx, y, y_idx, weights = weights) + res_offset <- srs_diff_est(y_approx + offset, y + offset, y_idx, + weights = weights) + expect_equal(res_offset$y_hat, res$y_hat + N * offset, tolerance = 1e-12) + # the errors of v_y_hat and hat_v_y come from the rounding of + # y + offset and y_approx + offset + expect_equal(res_offset$v_y_hat, res$v_y_hat, tolerance = 1e-9) + expect_equal(res_offset$hat_v_y, res$hat_v_y, tolerance = 1e-9) + } + # all observations sampled: the shift is added back once + y_all <- y_approx + rnorm(N, 0, 0.05) + res <- srs_diff_est(y_approx, y_all, seq_len(N)) + res_offset <- srs_diff_est(y_approx + offset, y_all + offset, seq_len(N)) + expect_equal(res_offset$y_hat, res$y_hat + N * offset, tolerance = 1e-12) + expect_equal(res_offset$v_y_hat, 0) + expect_equal(res_offset$hat_v_y, res$hat_v_y, tolerance = 1e-9) +}) + +test_that("srs_diff_est keeps -Inf in y_approx outside the subsample", { + set.seed(1234) + N <- 100 + y_approx <- rnorm(N) + y_idx <- 11:30 + y <- y_approx[y_idx] + rnorm(20, 0, 0.1) + res <- srs_diff_est(y_approx, y, y_idx) + y_approx[1] <- -Inf + res_inf <- srs_diff_est(y_approx, y, y_idx) + expect_identical(res_inf$y_hat, -Inf) + expect_equal(res_inf$v_y_hat, res$v_y_hat) +}) + +test_that("srs_diff_est checks the weights", { + y_approx <- rnorm(10) + expect_error(srs_diff_est(y_approx, y_approx[1:3], 1:3, weights = rep(1, 9)), + "weights") + expect_error(srs_diff_est(y_approx, y_approx[1:3], 1:3, + weights = c(-1, rep(1, 9))), + "weights") + expect_error(srs_diff_est(y_approx, y_approx[1:3], 1:3, + weights = c(Inf, rep(1, 9))), + "weights") + expect_error(srs_diff_est(y_approx, y_approx[1:3], 1:3, weights = rep(0, 10)), + "must not all be 0") + expect_error(srs_diff_est(y_approx, y_approx[1:3], 1:3, + weights = c(0, 0, 0, rep(1, 7))), + "must not all be 0") + # one subsampled observation + res <- srs_diff_est(y_approx, y_approx[2], 2, weights = rep(1, 10)) + expect_identical(res$v_y_hat, NA_real_) +}) + test_that("srs_est works as expected", { set.seed(1234) # Cochran 1976 example Table 2.2