第 67 章 贝叶斯logistic-binomial模型

library(tidyverse)
library(tidybayes)
library(rstan)

rstan_options(auto_write = TRUE)
options(mc.cores = parallel::detectCores())
theme_set(bayesplot::theme_default())

67.1 企鹅案例

筛选出物种为”Gentoo”的企鹅,并构建gender变量,male 对应1,female对应0

library(palmerpenguins)
gentoo <- penguins %>%
  filter(species == "Gentoo", !is.na(sex)) %>% 
  mutate(gender = if_else(sex == "male", 1, 0))
gentoo
## # A tibble: 119 × 9
##   species island bill_length_mm bill_depth_mm
##   <fct>   <fct>           <dbl>         <dbl>
## 1 Gentoo  Biscoe           46.1          13.2
## 2 Gentoo  Biscoe           50            16.3
## 3 Gentoo  Biscoe           48.7          14.1
## 4 Gentoo  Biscoe           50            15.2
## 5 Gentoo  Biscoe           47.6          14.5
## 6 Gentoo  Biscoe           46.5          13.5
## # … with 113 more rows, and 5 more variables:
## #   flipper_length_mm <int>, body_mass_g <int>,
## #   sex <fct>, year <int>, gender <dbl>

67.1.1 dotplots

借鉴ggdist的Logit dotplots 的画法,画出dotplot

gentoo %>%
  ggplot(aes(x = body_mass_g, y = sex, side = ifelse(sex == "male", "bottom", "top"))) +
  geom_dots(scale = 0.5) +
  ggtitle(
    "geom_dots(scale = 0.5)",
    'aes(side = ifelse(sex == "male", "bottom", "top"))'
  )

\[ \begin{align*} y_i & = \text{bernoulli}( p_i) \\ p_i & =\text{logit}^{-1}(X_i \beta) \end{align*} \]

67.1.2 bayesian logit模型

stan_program <- "
data {
  int<lower=0> N;
  vector[N] x;
  int<lower=0,upper=1> y[N];
  int<lower=0> M;
  vector[M] new_x;  
}
parameters {
  real alpha;
  real beta;
}
model {
  // more efficient and arithmetically stable
  y ~ bernoulli_logit(alpha + beta * x);
}
generated quantities {
  vector[M] y_epred; 
  vector[M] mu = alpha + beta * new_x;

  for(i in 1:M) {
    y_epred[i] = inv_logit(mu[i]);
  }
   
}
"

newdata <- data.frame(
    body_mass_g = seq(min(gentoo$body_mass_g), max(gentoo$body_mass_g), length.out = 100)
   ) 


stan_data <- list(
  N = nrow(gentoo),
  y = gentoo$gender, 
  x = gentoo$body_mass_g,
  M = nrow(newdata),
  new_x = newdata$body_mass_g
)

m <- stan(model_code = stan_program, data = stan_data)
fit <- m %>%
  tidybayes::gather_draws(y_epred[i]) %>%
  ggdist::mean_qi(.value)
fit
## # A tibble: 100 × 8
##       i .variable  .value  .lower  .upper .width .point
##   <int> <chr>       <dbl>   <dbl>   <dbl>  <dbl> <chr> 
## 1     1 y_epred   1.92e-5 4.35e-9 1.49e-4   0.95 mean  
## 2     2 y_epred   2.36e-5 6.61e-9 1.81e-4   0.95 mean  
## 3     3 y_epred   2.89e-5 9.96e-9 2.18e-4   0.95 mean  
## 4     4 y_epred   3.55e-5 1.50e-8 2.64e-4   0.95 mean  
## 5     5 y_epred   4.37e-5 2.29e-8 3.20e-4   0.95 mean  
## 6     6 y_epred   5.37e-5 3.43e-8 3.86e-4   0.95 mean  
## # … with 94 more rows, and 1 more variable:
## #   .interval <chr>

两个图画在一起

fit %>% 
  bind_cols(newdata) %>% 
  ggplot(aes(x = body_mass_g)) +
  geom_dots(
    data = gentoo,
    aes(y = gender, side = ifelse(sex == "male", "bottom", "top")),
    scale = 0.4
  ) +
  geom_lineribbon(
    aes(y = .value, ymin = .lower, ymax = .upper), 
    alpha = 1/4, 
    fill = "#08306b"
  ) +
  labs(
    title = "logit dotplot: stat_dots() with stat_lineribbon()",
    subtitle = 'aes(side = ifelse(sex == "male", "bottom", "top"))',
    x = "Body mass (g) of Gentoo penguins",
    y = "Pr(sex = male)"
  )

67.2 篮球案例

我们模拟100个选手每人投篮20次,假定命中概率是身高的线性函数,案例来源chap15.3 of [Regression and Other Stories] (page270).

n <- 100

data <-
  tibble(size   = 20,
         height = rnorm(n, mean = 72, sd = 3)) %>% 
  mutate(y = rbinom(n, size = size, p = 0.4 + 0.1 * (height - 72) / 3))

head(data)
## # A tibble: 6 × 3
##    size height     y
##   <dbl>  <dbl> <int>
## 1    20   65.4     4
## 2    20   72.1     8
## 3    20   74.0    10
## 4    20   73.9     9
## 5    20   71.1     5
## 6    20   69.0     4

67.2.1 常规做法

fit_glm <- glm(
  cbind(y, 20-y) ~ height, family = binomial(link = "logit"),
  data = data
)
fit_glm
## 
## Call:  glm(formula = cbind(y, 20 - y) ~ height, family = binomial(link = "logit"), 
##     data = data)
## 
## Coefficients:
## (Intercept)       height  
##     -10.775        0.143  
## 
## Degrees of Freedom: 99 Total (i.e. Null);  98 Residual
## Null Deviance:       182 
## Residual Deviance: 86    AIC: 421

67.2.2 stan 代码

\[ \begin{align*} y_i & = \text{Binomial}(n_i, p_i) \\ p_i & =\text{logit}^{-1}(X_i \beta) \end{align*} \]

stan_program <- "
data {
  int<lower=0> N;
  int<lower=0> K;
  matrix[N, K] X;
  int<lower=0> y[N];
  int trials[N];
}
parameters {
  vector[K] beta;
}
model {
  
  for(i in 1:N) {
    target += binomial_logit_lpmf(y[i] | trials[i], X[i] * beta);
  }
  
}
"


stan_data <- data %>%
  tidybayes::compose_data(
    N      = n,
    K      = 2,
    y      = y,
    trials = size,
    X      = model.matrix(~ 1 + height)
  )

fit <- stan(model_code = stan_program, data = stan_data)
fit
## Inference for Stan model: anon_model.
## 4 chains, each with iter=2000; warmup=1000; thin=1; 
## post-warmup draws per chain=1000, total post-warmup draws=4000.
## 
##            mean se_mean   sd    2.5%     25%     50%
## beta[1]  -10.79    0.05 1.10  -12.97  -11.56  -10.79
## beta[2]    0.14    0.00 0.02    0.11    0.13    0.14
## lp__    -209.28    0.03 1.02 -212.04 -209.68 -208.96
##             75%   97.5% n_eff Rhat
## beta[1]  -10.03   -8.59   536 1.01
## beta[2]    0.15    0.17   537 1.01
## lp__    -208.55 -208.28   935 1.00
## 
## Samples were drawn using NUTS(diag_e) at Sun May  8 10:01:04 2022.
## For each parameter, n_eff is a crude measure of effective sample size,
## and Rhat is the potential scale reduction factor on split chains (at 
## convergence, Rhat=1).