4  Stan Models

Code
# Load libraries
library(tidyverse)
library(gt)
library(cmdstanr)
library(tidybayes)
#library(posterior)
library(ggpmisc)
library(ggridges)
library(loo)

# Set ggplot theme
theme_set(theme_classic())

# Create a function to convert decimals to percentages
to_percent <- function(x, digits = 0){
  return(round(x * 100, digits = digits))
}

Now that we’ve established theoretical models and simulated realistic data from them, we can use Stan to fit these models to data. For now, we’ll stick to our simulated data and see if our posterior estimates can recover the true value of the parameters.

Code
grades <- read_csv(file = "data/sim_grades.csv") |>
  transmute(
    student = row_number(),
    y8 = round(y8, 2),
    y9 = round(y9, 2),
    y10 = round(y10, 2)) |>
  # Remove zeros or ones for the Beta distribution and Stan
  mutate(
    across(
      starts_with("y"), ~ case_when(
        .x == 0 ~ 0.001,
        .x == 1 ~ 0.999,
        TRUE ~ .x
      )))

4.3 Model Comparisons

Code
fit_lin_mod$loo()

Computed from 4000 by 250 log-likelihood matrix.

         Estimate   SE
elpd_loo    198.9 10.8
p_loo         3.8  0.6
looic      -397.7 21.5
------
MCSE of elpd_loo is 0.0.
MCSE and ESS estimates assume MCMC draws (r_eff in [0.6, 1.3]).

All Pareto k estimates are good (k < 0.7).
See help('pareto-k-diagnostic') for details.
Code
fit_logit_mod$loo()

Computed from 4000 by 250 log-likelihood matrix.

         Estimate   SE
elpd_loo    203.2 11.0
p_loo         3.8  0.5
looic      -406.3 22.0
------
MCSE of elpd_loo is 0.0.
MCSE and ESS estimates assume MCMC draws (r_eff in [0.5, 1.4]).

All Pareto k estimates are good (k < 0.7).
See help('pareto-k-diagnostic') for details.
Code
loo_compare(x = list(
  linear_model = fit_lin_mod$loo(),
  logit_model = fit_logit_mod$loo()
))
             elpd_diff se_diff
logit_model   0.0       0.0   
linear_model -4.3       3.0   

Based on LOO cross-validation, the logit model has slightly better predictive performance than the linear model, with an elpd difference of 4.4 (SE = 3.0).