# Comparison of two means (T-test)

import arviz as az
import bambi as bmb
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
az.style.use("arviz-darkgrid")
np.random.seed(1234)

In this notebook we demo two equivalent ways of performing a two-sample Bayesian t-test to compare the mean value of two Gaussian populations using Bambi.

## Generate data

We generate 160 values from a Gaussian with $$\mu=6$$ and $$\sigma=2.5$$ and another 120 values from a Gaussian’ with $$\mu=8$$ and $$\sigma=2$$

a = np.random.normal(6, 2.5, 160)
b = np.random.normal(8, 2, 120)
df = pd.DataFrame({"Group": ["a"] * 160 + ["b"] * 120, "Val": np.hstack([a, b])})
df.head()
Group Val
0 a 7.178588
1 a 3.022561
2 a 9.581767
3 a 5.218370
4 a 4.198528
az.plot_violin({"a": a, "b": b});
/home/tomas/anaconda3/envs/bambi/lib/python3.10/site-packages/arviz/plots/backends/matplotlib/violinplot.py:64: UserWarning: This figure was using a layout engine that is incompatible with subplots_adjust and/or tight_layout; not calling subplots_adjust.
fig.subplots_adjust(wspace=0)

When we carry out a two sample t-test we are implicitly using a linear model that can be specified in different ways. One of these approaches is the following:

### Model 1

$\mu_i = \beta_0 + \beta_1 (i) + \epsilon_i$

where $$i = 0$$ represents the population 1, $$i = 1$$ the population 2 and $$\epsilon_i$$ is a random error with mean 0. If we replace the indicator variables for the two groups we have

$\mu_0 = \beta_0 + \epsilon_i$

and

$\mu_1 = \beta_0 + \beta_1 + \epsilon_i$

if $$\mu_0 = \mu_1$$ then

$\beta_0 + \epsilon_i = \beta_0 + \beta_1 + \epsilon_i\\ 0 = \beta_1$

Thus, we can see that testing whether the mean of the two populations are equal is equivalent to testing whether $$\beta_1$$ is 0.

### Analysis

We start by instantiating our model and specifying the model previously described.

model_1 = bmb.Model("Val ~ Group", df)
results_1 = model_1.fit()
Auto-assigning NUTS sampler...
Initializing NUTS using jitter+adapt_diag...
Multiprocess sampling (2 chains in 2 jobs)
NUTS: [Val_sigma, Intercept, Group]
100.00% [4000/4000 00:03<00:00 Sampling 2 chains, 0 divergences]
Sampling 2 chains for 1_000 tune and 1_000 draw iterations (2_000 + 2_000 draws total) took 4 seconds.

We’ve only specified the formula for the model and Bambi automatically selected priors distributions and values for their parameters. We can inspect both the setup and the priors as following:

model_1
       Formula: Val ~ Group
Family: gaussian
Link: mu = identity
Observations: 280
Priors:
target = mu
Common-level effects
Intercept ~ Normal(mu: 6.9762, sigma: 8.1247)
Group ~ Normal(mu: 0, sigma: 12.4107)

Auxiliary parameters
Val_sigma ~ HalfStudentT(nu: 4, sigma: 2.4567)
------
* To see a plot of the priors call the .plot_priors() method.
* To see a summary or plot of the posterior pass the object returned by .fit() to az.summary() or az.plot_trace()
model_1.plot_priors();
Sampling: [Group, Intercept, Val_sigma]

To inspect our posterior and the sampling process we can call az.plot_trace(). The option kind='rank_vlines' gives us a variant of the rank plot that uses lines and dots and helps us to inspect the stationarity of the chains. Since there is no clear pattern or serious deviations from the horizontal lines, we can conclude the chains are stationary.

az.plot_trace(results_1, kind="rank_vlines");

az.summary(results_1)
mean sd hdi_3% hdi_97% mcse_mean mcse_sd ess_bulk ess_tail r_hat
Intercept 6.116 0.179 5.778 6.449 0.003 0.002 3290.0 1795.0 1.00
Group[b] 2.005 0.270 1.498 2.507 0.005 0.003 3537.0 1634.0 1.00
Val_sigma 2.261 0.092 2.077 2.423 0.002 0.001 3217.0 1551.0 1.01

In the summary table we can see the 94% highest density interval for $$\beta_1$$ ranges from 1.511 to 2.499. Thus, according to the data and the model used, we conclude the difference between the two population means is somewhere between 1.2 and 2.2 and hence we support the hypotehsis that $$\beta_1 \ne 0$$.

Similar conclusions can be made with the density estimate for the posterior distribution of $$\beta_1$$. As seen in the table, most of the probability for the difference in the mean roughly ranges from 1.2 to 2.2.

az.plot_posterior(results_1, var_names="Group", ref_val=0);

Another way to arrive to a similar conclusion is by calculating the probability that the parameter $$\beta_1 > 0$$. This probability is equal to 1, telling us that the mean of the two populations are different.

# Probabiliy that posterior is > 0
(results_1.posterior["Group"] > 0).mean().item()
1.0

The linear model implicit in the t-test can also be specified without an intercept term, such is the case of Model 2.

### Model 2

When we carry out a two sample t-test we’re implicitly using the following model:

$\mu_i = \beta_i + \epsilon_i$

where $$i = 0$$ represents the population 1, $$i = 1$$ the population 2 and $$\epsilon$$ is a random error with mean 0. If we replace the indicator variables for the two groups we have

$\mu_0 = \beta_0 + \epsilon$

and

$\mu_1 = \beta_1 + \epsilon$

if $$\mu_0 = \mu_1$$ then

$\beta_0 + \epsilon = \beta_1 + \epsilon\\$

Thus, we can see that testing whether the mean of the two populations are equal is equivalent to testing whether $$\beta_0 = \beta_1$$.

### Analysis

We start by instantiating our model and specifying the model previously described. In this model we will bypass the intercept that Bambi adds by default by setting it to zero, even though setting to -1 has the same effect.

model_2 = bmb.Model("Val ~ 0 + Group", df)
results_2 = model_2.fit() 
Auto-assigning NUTS sampler...
Initializing NUTS using jitter+adapt_diag...
Multiprocess sampling (2 chains in 2 jobs)
NUTS: [Val_sigma, Group]
100.00% [4000/4000 00:02<00:00 Sampling 2 chains, 0 divergences]
Sampling 2 chains for 1_000 tune and 1_000 draw iterations (2_000 + 2_000 draws total) took 3 seconds.

We’ve only specified the formula for the model and Bambi automatically selected priors distributions and values for their parameters. We can inspect both the setup and the priors as following:

model_2
       Formula: Val ~ 0 + Group
Family: gaussian
Link: mu = identity
Observations: 280
Priors:
target = mu
Common-level effects
Group ~ Normal(mu: [0. 0.], sigma: [12.4107 12.4107])

Auxiliary parameters
Val_sigma ~ HalfStudentT(nu: 4, sigma: 2.4567)
------
* To see a plot of the priors call the .plot_priors() method.
* To see a summary or plot of the posterior pass the object returned by .fit() to az.summary() or az.plot_trace()
model_2.plot_priors();
Sampling: [Group, Val_sigma]

To inspect our posterior and the sampling process we can call az.plot_trace(). The option kind='rank_vlines' gives us a variant of the rank plot that uses lines and dots and helps us to inspect the stationarity of the chains. Since there is no clear pattern or serious deviations from the horizontal lines, we can conclude the chains are stationary.

az.plot_trace(results_2, kind="rank_vlines");

az.summary(results_2)
mean sd hdi_3% hdi_97% mcse_mean mcse_sd ess_bulk ess_tail r_hat
Group[a] 6.113 0.177 5.806 6.465 0.003 0.002 2973.0 1385.0 1.0
Group[b] 8.117 0.209 7.724 8.506 0.004 0.003 3341.0 1662.0 1.0
Val_sigma 2.263 0.099 2.082 2.446 0.002 0.001 2727.0 1454.0 1.0

In this summary we can observe the estimated distribution of means for each population. A simple way to compare them is subtracting one to the other. In the next plot we can se that the entirety of the distribution of differences is higher than zero and that the mean of population 2 is higher than the mean of population 1 by a mean of 2.

post_group = results_2.posterior["Group"]
diff = post_group.sel(Group_dim="b") - post_group.sel(Group_dim="a")
az.plot_posterior(diff, ref_val=0);

Another way to arrive to a similar conclusion is by calculating the probability that the parameter $$\beta_1 - \beta_0 > 0$$. This probability equals to 1, telling us that the mean of the two populations are different.

# Probabiliy that posterior is > 0
(post_group > 0).mean().item()
1.0
%load_ext watermark
%watermark -n -u -v -iv -w
Last updated: Thu Jan 05 2023

Python implementation: CPython
Python version       : 3.10.4
IPython version      : 8.5.0

matplotlib: 3.6.2
pandas    : 1.5.2
bambi     : 0.9.3
arviz     : 0.14.0
numpy     : 1.23.5
sys       : 3.10.4 (main, Mar 31 2022, 08:41:55) [GCC 7.5.0]

Watermark: 2.3.1