## ----setup, include = FALSE--------------------------------------------------- knitr::opts_chunk$set( collapse = TRUE, comment = "#>", # Evaluated wherever INLA and the packages used here are installed. eval = all(vapply( c("INLA", "parsnip", "broom", "rsample", "yardstick", "dplyr", "vetiver", "pins"), requireNamespace, logical(1), quietly = TRUE )) ) ## ----message = FALSE---------------------------------------------------------- library(inlabru) library(inlaops) library(parsnip) library(broom) library(rsample) library(yardstick) library(dplyr) ## ----------------------------------------------------------------------------- set.seed(123) n <- 300 dat <- data.frame( area = rnorm(n), effort = runif(n, 0.5, 2.0) ) log_mu <- 0.5 + 0.8 * dat$area + log(dat$effort) dat$counts <- rpois(n, exp(log_mu)) ## ----------------------------------------------------------------------------- spec <- bru_reg(mode = "regression", family = "poisson") fit <- spec |> set_engine("inlabru") |> fit(counts ~ Intercept(1) + area + effort, data = dat) fit ## ----------------------------------------------------------------------------- tidy(fit$fit) glance(fit$fit) ## ----------------------------------------------------------------------------- new_dat <- data.frame(area = c(-1, 0, 1), effort = c(1, 1, 1)) predict(fit, new_data = new_dat) ## ----------------------------------------------------------------------------- augment(fit$fit, data = new_dat, pred_formula = ~ exp(Intercept + area + effort)) ## ----------------------------------------------------------------------------- # Frequentist baseline fit_glm <- glm(counts ~ area + effort, data = dat, family = poisson()) # Bayesian with inlabru, via parsnip bru_spec <- bru_reg(family = "poisson") |> set_engine("inlabru") fit_bru <- bru_spec |> fit(counts ~ Intercept(1) + area + effort, data = dat) # Coefficient comparison (response-scale interval for the Bayesian fit) broom::tidy(fit_glm) broom::tidy(fit_bru$fit) ## ----------------------------------------------------------------------------- cv_preds <- bru_cv_predict( formula = counts ~ Intercept(1) + area + effort, family = "poisson", data = dat, v = 5L, pred_formula = ~ exp(Intercept + area + effort), n_samples = 500L ) cv_preds # Compute RMSE across folds yardstick::rmse(cv_preds, truth = .truth, estimate = .pred) ## ----------------------------------------------------------------------------- library(vetiver) library(pins) v <- vetiver_model(fit$fit, "poisson_glm") v$metadata$user <- list( pred_formula = "~ exp(Intercept + area + effort)", n_samples = 1000L ) board <- board_temp() vetiver_pin_write(board, v)