第 65 章 贝叶斯假设检验
library(tidyverse)
library(tidybayes)
library(rstan)
rstan_options(auto_write = TRUE)
options(mc.cores = parallel::detectCores())
theme_set(bayesplot::theme_default())
65.1 人们会给爱情片打高分?
这是一个关于电影评分的数据。我们想看下爱情片与动作片的平均得分是否存在显著不同?
## # A tibble: 100 × 5
## title year rating genre genre_numeric
## <chr> <int> <dbl> <fct> <dbl>
## 1 One of Our Spies Is… 1966 5.6 Acti… 1
## 2 Black Pirate, The 1926 7.5 Acti… 1
## 3 Caged Heat 3000 1995 2.9 Acti… 1
## 4 G.P.U. 1942 8.8 Acti… 1
## 5 Goal Club 2001 9.2 Acti… 1
## 6 Dead or Alive: Hanz… 1999 6.9 Acti… 1
## # … with 94 more rows
65.1.1 可视化探索
看下两种题材电影评分的分布
movies %>%
ggplot(aes(x = genre, y = rating, color = genre)) +
geom_boxplot() +
geom_jitter() +
scale_x_discrete(
expand = expansion(mult = c(0.5, 0.5))
) +
theme(legend.position = "none")

65.1.2 计算均值差
统计两种题材电影评分的均值
group_diffs <- movies %>%
group_by(genre) %>%
summarize(avg_rating = mean(rating, na.rm = TRUE)) %>%
mutate(diff_means = avg_rating - lag(avg_rating))
group_diffs
## # A tibble: 2 × 3
## genre avg_rating diff_means
## <fct> <dbl> <dbl>
## 1 Action 5.55 NA
## 2 Romance 6.22 0.67
65.1.3 t检验
传统的t检验
t.test(
rating ~ genre,
data = movies,
var.equal = FALSE
)
##
## Welch Two Sample t-test
##
## data: rating by genre
## t = -2.3, df = 84, p-value = 0.03
## alternative hypothesis: true difference in means between group Action and group Romance is not equal to 0
## 95 percent confidence interval:
## -1.2571 -0.0829
## sample estimates:
## mean in group Action mean in group Romance
## 5.55 6.22
65.2 stan 代码
65.2.1 normal分布
先假定rating评分,服从正态分布,同时不同的电影题材分组考虑
\[ \begin{aligned} \textrm{rating} & \sim \textrm{normal}(\mu_{\textrm{genre}}, \, \sigma _{\textrm{genre}}) \\ \mu &\sim \textrm{normal}(\textrm{mean_rating}, \, 2) \\ \sigma &\sim \textrm{cauchy}(0, \, 1) \end{aligned} \]
stan_program <- '
data {
int<lower=1> N;
int<lower=2> n_groups;
vector[N] y;
int<lower=1, upper=n_groups> group_id[N];
}
transformed data {
real mean_y;
mean_y = mean(y);
}
parameters {
vector[2] mu;
vector<lower=0>[2] sigma;
}
model {
mu ~ normal(mean_y, 2);
sigma ~ cauchy(0, 1);
for (n in 1:N){
y[n] ~ normal(mu[group_id[n]], sigma[group_id[n]]);
}
}
generated quantities {
real mu_diff;
mu_diff = mu[2] - mu[1];
}
'
stan_data <- movies %>%
select(genre, rating, genre_numeric) %>%
tidybayes::compose_data(
N = nrow(.),
n_groups = n_distinct(genre),
group_id = genre_numeric,
y = rating
)
stan_best_normal <- stan(model_code = stan_program, data = stan_data)
stan_best_normal
## 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%
## mu[1] 5.55 0.00 0.25 5.06 5.39 5.55
## mu[2] 6.22 0.00 0.16 5.90 6.11 6.22
## sigma[1] 1.77 0.00 0.19 1.45 1.64 1.76
## sigma[2] 1.15 0.00 0.12 0.95 1.06 1.14
## mu_diff 0.67 0.00 0.30 0.09 0.46 0.66
## lp__ -86.87 0.03 1.47 -90.58 -87.59 -86.55
## 75% 97.5% n_eff Rhat
## mu[1] 5.72 6.05 3946 1
## mu[2] 6.32 6.55 3707 1
## sigma[1] 1.88 2.19 3885 1
## sigma[2] 1.22 1.40 4169 1
## mu_diff 0.86 1.25 3771 1
## lp__ -85.79 -85.09 1840 1
##
## Samples were drawn using NUTS(diag_e) at Sun May 8 09:52:31 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).
stan_best_normal %>%
tidybayes::spread_draws(mu_diff) %>%
ggplot(aes(x = mu_diff)) +
tidybayes::stat_halfeye() +
geom_vline(xintercept = 0)

stan_best_normal %>%
tidybayes::spread_draws(mu_diff) %>%
ggplot(aes(x = mu_diff)) +
stat_eye(side = "right",
fill = "skyblue",
point_interval = mode_hdi,
.width = c(0.5, 0.89),
interval_colour = "red",
point_colour = "red",
width = 15.5,
height = 0.1
) +
geom_vline(xintercept = c(-0.1, 0.1), linetype = "dashed", size = 1) +
coord_cartesian(xlim = c(-1, 2)) +
labs(x = "mu_diff", y = NULL)

65.2.2 等效检验
我们一般会采用实用等效区间 region of practical equivalence ROPE。实用等效区间,就是我们感兴趣值附近的一个区间,比如这里的均值差。频率学中的零假设是看均值差是否为0,贝叶斯则是看均值差有多少落入0附近的区间。具体方法就是,先算出后验分布的高密度区间,然后看这个高密度区间落在[-0.1, 0.1]的比例.
lower <- -0.1*sd(movies$rating)
upper <- 0.1*sd(movies$rating)
stan_best_normal %>%
tidybayes::spread_draws(mu_diff) %>%
filter(
mu_diff > ggdist::mean_hdi(mu_diff, .width = c(0.89))$ymin,
mu_diff < ggdist::mean_hdi(mu_diff, .width = c(0.89))$ymax
) %>%
summarise(
percentage_in_rope = mean(between(mu_diff, lower, upper))
)
## # A tibble: 1 × 1
## percentage_in_rope
## <dbl>
## 1 0
在做假设检验的时候,我们内心是期望,后验概率的高密度区间落在实际等效区间的比例越小越小,如果小于2.5%,我们就可以拒绝零假设了;如果大于97.5%,我们就接受零假设。
stan_best_normal %>%
tidybayes::spread_draws(mu_diff) %>%
pull(mu_diff) %>%
bayestestR::rope(x,
range = c(-0.1, 0.1)*sd(movies$rating),
ci = 0.89,
ci_method = "HDI"
)
## # Proportion of samples inside the ROPE [-0.15, 0.15]:
##
## inside ROPE
## -----------
## 0.00 %
65.2.3 Student-t 分布
标准正态分布是t分布的极限分布
for (nu in c(1, seq(5, 50, by = 10))) {
p <- tibble(x = seq(-5, 5, by=0.1)) %>%
ggplot(aes(x)) +
stat_function(fun = dnorm, color = 'gray') +
stat_function(fun = dt, args = list(df = nu), color = 'blue') +
theme_classic() +
ylab("Density") +
xlab('Value') +
ggtitle(paste("df =", nu))
print(p)
}
假定rating评分服从student-t分布,
\[ \begin{aligned} \textrm{rating} & \sim \textrm{student_t}(\nu, \,\mu_{\textrm{genre}}, \, \sigma _{\textrm{genre}}) \\ \mu &\sim \textrm{normal}(\textrm{mean_rating}, \, 2) \\ \sigma &\sim \textrm{cauchy}(0, \, 1) \\ \nu &\sim \textrm{exponential}(1.0/29) \end{aligned} \]
stan_program <- '
data {
int<lower=1> N;
int<lower=2> n_groups;
vector[N] y;
int<lower=1, upper=n_groups> group_id[N];
}
transformed data {
real mean_y;
mean_y = mean(y);
}
parameters {
vector[2] mu;
vector<lower=0>[2] sigma;
real<lower=0, upper=100> nu;
}
model {
mu ~ normal(mean_y, 2);
sigma ~ cauchy(0, 1);
nu ~ exponential(1.0/29);
for (n in 1:N){
y[n] ~ student_t(nu, mu[group_id[n]], sigma[group_id[n]]);
}
}
generated quantities {
real mu_diff;
mu_diff = mu[2] - mu[1];
}
'
stan_data <- movies %>%
select(genre, rating, genre_numeric) %>%
tidybayes::compose_data(
N = nrow(.),
n_groups = n_distinct(genre),
group_id = genre_numeric,
y = rating
)
stan_best_student <- stan(model_code = stan_program, data = stan_data)
stan_best_student
## 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%
## mu[1] 5.54 0.00 0.25 5.06 5.36 5.54
## mu[2] 6.24 0.00 0.16 5.92 6.12 6.23
## sigma[1] 1.71 0.00 0.19 1.37 1.58 1.69
## sigma[2] 1.05 0.00 0.13 0.81 0.96 1.04
## nu 27.13 0.41 19.82 5.27 12.11 20.88
## mu_diff 0.70 0.00 0.30 0.11 0.49 0.70
## lp__ -119.52 0.04 1.60 -123.55 -120.37 -119.21
## 75% 97.5% n_eff Rhat
## mu[1] 5.71 6.03 4778 1
## mu[2] 6.35 6.55 4020 1
## sigma[1] 1.82 2.12 4126 1
## sigma[2] 1.13 1.31 3223 1
## nu 36.49 78.45 2313 1
## mu_diff 0.90 1.27 4327 1
## lp__ -118.34 -117.38 1797 1
##
## Samples were drawn using NUTS(diag_e) at Sun May 8 09:54:10 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).
stan_best_student %>%
tidybayes::spread_draws(mu_diff) %>%
ggplot(aes(x = mu_diff)) +
tidybayes::stat_halfeye() +
geom_vline(xintercept = 0)

stan_best_student %>%
as.data.frame() %>%
head()
## mu[1] mu[2] sigma[1] sigma[2] nu mu_diff lp__
## 1 5.586 6.099 1.922 1.0341 10.863 0.5128 -118.7
## 2 5.262 6.450 2.232 1.2170 13.952 1.1879 -122.9
## 3 5.166 6.334 1.665 0.8879 13.429 1.1676 -118.9
## 4 5.306 5.983 1.757 1.1454 7.552 0.6778 -120.7
## 5 5.525 6.312 1.716 0.9283 63.953 0.7872 -119.9
## 6 5.410 6.351 1.712 0.8915 70.707 0.9407 -121.5
stan_best_student %>%
as.data.frame() %>%
ggplot(aes(x = `mu[1]`)) +
geom_density()

stan_best_student %>%
tidybayes::gather_draws(mu[i], sigma[i]) %>%
tidybayes::mean_hdi(.width = 0.89)
## # A tibble: 4 × 8
## i .variable .value .lower .upper .width .point
## <int> <chr> <dbl> <dbl> <dbl> <dbl> <chr>
## 1 1 mu 5.54 5.14 5.94 0.89 mean
## 2 1 sigma 1.71 1.41 2.01 0.89 mean
## 3 2 mu 6.24 5.98 6.49 0.89 mean
## 4 2 sigma 1.05 0.833 1.24 0.89 mean
## # … with 1 more variable: .interval <chr>
65.4 作业
- 将上一章线性模型的stan代码应用到电影评分数据中
\[ \begin{aligned} \textrm{rating} & \sim \textrm{Normal}(\mu, \, \sigma) \\ \mu & = \alpha + \beta \, \textrm{genre} \\ \alpha &\sim \textrm{Normal}(0, \, 5) \\ \beta &\sim \textrm{Normal}(0, \, 1) \\ \sigma &\sim \textrm{Exponential}(1) \\ \end{aligned} \]
stan_program <- '
data {
int<lower=1> N;
vector[N] y;
vector[N] x;
}
parameters {
real<lower=0> sigma;
real alpha;
real beta;
}
model {
y ~ normal(alpha + beta * x, sigma);
alpha ~ normal(0, 5);
beta ~ normal(0, 1);
sigma ~ exponential(1);
}
'
stan_data <- list(
N = nrow(movies),
x = as.numeric(movies$genre),
y = movies$rating
)
stan_linear <- stan(model_code = stan_program, data = stan_data)
stan_linear
## 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% 75%
## sigma 1.49 0.00 0.10 1.30 1.41 1.48 1.55
## alpha 4.92 0.01 0.46 4.07 4.60 4.91 5.23
## beta 0.64 0.01 0.29 0.06 0.45 0.64 0.84
## lp__ -91.23 0.03 1.24 -94.31 -91.80 -90.92 -90.33
## 97.5% n_eff Rhat
## sigma 1.70 1954 1
## alpha 5.83 1530 1
## beta 1.19 1543 1
## lp__ -89.80 1275 1
##
## Samples were drawn using NUTS(diag_e) at Sun May 8 09:55:40 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).
stan_linear %>%
tidybayes::spread_draws(beta) %>%
ggplot(aes(x = beta)) +
tidybayes::stat_halfeye() +
geom_vline(xintercept = 0)

stan_linear %>%
tidybayes::gather_draws(beta) %>%
tidybayes::mean_hdi(.width = 0.89)
## # A tibble: 1 × 7
## .variable .value .lower .upper .width .point
## <chr> <dbl> <dbl> <dbl> <dbl> <chr>
## 1 beta 0.641 0.149 1.06 0.89 mean
## # … with 1 more variable: .interval <chr>