Files
bayesian_inference_2025/borrowing_strenght_hierarchical_model.ipynb

11 KiB
Raw Blame History

Borrowing of strength in Bayesian hierarchical model

We consider the problem of estimating the average number of patients admitted to ER per day from various hospitals across a city. A Bayesian hierarchical model (BHM) allows us to partially pool information across hospitals, reducing variance in small-sample groups and leveraging strength across hospitals to estimate the population-level parameters. Here, we investigate a Poisson- lognormal model.

(a) Generate a dataset where the logarithm of the expected number of admissions per day for hospital $j$, $ln \lambda_j$, comes from a Normal distribution:

$$ ln \lambda_j \sim \mathcal{N}(\mu_0,\,\sigma_0^{2}), \text{ for } j = 1, ..., J $$

The admission counts data for each hospital for day $i$ follow a Poisson distribution:

$$ y_{ij} \mid \lambda_j \sim \text{Poisson}(\lambda_j), \text{ for } i = 1, ..., n_j $$

where each hospital $j$ has a different reporting frequency, which leads to different $n_j$ for each. To model this, you may draw $n_j$ randomly with equal probability from the set $\{52, 24, 12\}$, representing respectively weekly, twice a month and monthly reporting. Do this once, and keep $n_j$ fixed, treating it as known, throughout the exercise.

The DAG for this model is shown in Fig. 1. Since $\mu_0$ is the typical log-rate across hospitals, we may choose for its prior $$Pr(\mu_0) = \mathcal{N}(\log m, s^2)$$

where $m$ is a plausible choice for the median number of admissions/day, and s controls its spread. Since $\sigma_0$ controls the variability across hospitals, a prior choice that tends to reinforce shrinkage is $Pr(\sigma_0) = \exp(\tau)$.

Fix $m$, $s^2$, $\tau$ to sensible values, and use an MCMC algorithm of your choice to sample from the model and produce posterior distribution on $\{\lambda_j\}^J_{j=1}, \mu _0, \sigma _0$ (a sensible choice might be $J = 10$ hospitals).


(b) Determine the marginal posterior distribution for the admission rate for each hospital, and compare it with the posterior estimate in a model with no pooling (i.e., where each hospitals rate is inferred exclusively from its observed counts, i.e. $ \ln \lambda_j \sim \mathcal{N} (\mu_0, \sigma^2_0) $ and the same priors as above, and the posterior for hospital j comes exclusively from its own data). Check that the posterior means for hospitals with a smaller number of records (i.e., $n_j = 12$) exhibit stronger shrinkage towards the global mean, thus demonstrating borrowing of strength, and typically have 68% HPD credible intervals that are shorter than in the pooling model. You may use a violin plot to make this comparison.


(c) Consider the prior predictive distribution for possible data within the BHM:

$$ Pr( y_{ij} \mid priors) = \int Pr ( y_{ij} \mid \lambda_j) Pr(\lambda_j \mid \mu_0, \sigma_0) Pr (\mu_0,\sigma_0) d \mu_0 d \sigma_0$$

and simulate from it predictions for the possible counts $y_{ij}$ from the model (before you see any data). Evaluate the degree of shrinkage by using as metric the average shrinkage in the standard deviation of the posterior with respect to the no-pooling scenario, i.e.

$$ S = \frac {1} {J} \sum_{j=1}^{J}{1 - \frac{\text{std}_\text{BHM}(\ln \lambda_j \mid \bold y)}{\text{std}_\text{no pool}(\ln \lambda_j \mid \bold y)}}$$

where a smaller S corresponds to higher degree of shrinkage.

Determine which hyperparameter among $(m, s, \tau)$ has the most effect on the degree of shrinkage, and tune each to avoid predictions that are too diffuse (i.e., the predictive spread is unreasonably wide) or too narrow (i.e., the predictive spread is over-constraining).

In [ ]:
import emcee
import numpy as np
import pandas as pd

np.random.seed(42)
In [ ]:
J = 10
reporting_frequency = np.random.choice(
    [54, 24, 12],
    number_of_hospitals
)

print(f"We have {J} hospitals reporting admission data.")
for j in range(J):
    print(
        f"- Hospital number {j + 1:2} reports admission data "
        f"{reporting_frequency[j]} times a year."
    )
In [ ]:
def get_expected_admissions(mu, sigma):
    """Get expected number of admissions to a hospital at a time point.
    
    The log of the admission rate comes from a normal distribution with mean
        'mu' and standard deviation 'sigma'.
    The expected number of admissions comes from a Poisson distribution with
        frequency admission rate.
    """
    log_admission_rate = np.random.normal(
        mu, sigma
    )
    admission_rate = np.pow(np.e, log_admission_rate)
    #print(admission_rate)
    admission_counts = np.random.poisson(admission_rate)
    return admission_counts
In [ ]:
def get_admission_counts(mu: float, sigma: float) -> pd.DataFrame:
    data = {}
    max_T = max(reporting_frequency)
    for j in range(J):  # For each hospital
        admission_records = []
        for i in range(reporting_frequency[j]):  # For each report
            admission_records.append(get_expected_admissions(
                mu, sigma
            ))
        admission_records.extend([pd.NA] * (max_T - len(admission_records)))
        data[f"Hospital {j+1}"] = admission_records
    data = pd.DataFrame(data).transpose()
    data.index.name = "Time point"
    return data
  • Prior for $\mu_0$: we choose $m$ (typical log-rate across hospitals) and $s$ (a measure of the spread of $m$); $ Pr(\mu_0) = \mathcal{N}(\log m, s^2) $.
  • Prior for $\sigma_0$: $Pr(\sigma_0) = \text{Exponential}(\tau)$
In [ ]:
m = 85
s = 0.4
tau = 0.1
In [ ]:
mu_zero = np.random.normal(np.log(m), s)
sigma_zero = np.random.exponential(tau)

df = get_admission_counts(mu=mu_zero, sigma=sigma_zero)

print(df)

We can use AIES (ensemble samplers with affine invariance), introduced by Goodman and Weare in 2010 and implemented by the emcee python package, to sample from the joint posterior without analytically deriving it.

We have to write a function that takes in all hyper-parameters (both fixed and unknown) and returns the posterior value for those parameters; we will then construct an emcee.EnsembleSampler (giving the number of unknown parameters and the known ones) and we will finally run MCMC for a certain number of steps. The sampler will return tuples of sampled parameters.

For analytical convenience, we will use $\ln(Posterior)$, $\ln(\text{Prior})$ and $\ln(\mathcal{L})$.

In [ ]:
def log_posterior(parameters, m, s, tau):
    mu_0, sigma_0 = parameters
    if sigma_0 <= 0:  # Standard deviation must be strictly positive
        return -np.inf
    log_prior = 0.0
    # Prior for 'mu_0' (normally distributed, parameters 'm' and 's')
    log_prior += (
        -0.5 * np.log(2 * np.pi * s**2)
        -0.5 * ((mu_0 - np.log(m))**2) / s**2
    )
    # Prior for 'sigma_0' (exponentially distributed, parameter 'tau')
    log_prior += (
         np.log(tau) - tau * sigma_0
    )
    log_likelihood = 0.0
    # Likelihood for ''
    # TODO
    return log_prior + log_likelihood
In [ ]:
# Data: x_obs and y_obs (from previous synthetic data generation)
# Assuming x_obs and y_obs are numpy arrays of length N


# Number of dimensions and walkers
ndim = 4  # [theta_0, theta_1, x0, log_Rx2]
nwalkers = 32

# Initial guess for parameters
initial_guess = [2.0, 0.5, 5.0, Rx**2]

# Initialize walkers in a small ball around the initial guess
pos = initial_guess + 1e-4 * np.random.randn(nwalkers, ndim)

# Create the sampler
sampler = emcee.EnsembleSampler(nwalkers, ndim, log_posterior,
                                args=(x_obs, y_obs, sigma_x, sigma_y,
                                      mu_x0, sigma_x0_squared, alpha_R, beta_R))

# Run MCMC
nsteps = 5000
sampler.run_mcmc(pos, nsteps, progress=True)

# Get the samples
samples = sampler.get_chain(discard=1000, thin=10, flat=True)