Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Section 5.3 — Bayesian linear models

Notebook setup
Note: you may need to restart the kernel to use updated packages.
<Figure size 640x480 with 0 Axes>
Found ../datasets/ and copied files to datasets/.

Bayesian model

TODO: formula

TODO: graphical model diagram

Example 1: students score as a function of effort

Students dataset

(15, 5)
Loading...
Loading...
<Figure size 900x500 with 1 Axes>

Bayesian model

TODO: add formulas

Bambi model

Inspecting the Bambi model

Formula: score ~ 1 + effort Family: gaussian Link: mu = identity Observations: 15 Priors: target = mu Common-level effects Intercept ~ Normal(mu: 70.0, sigma: 20.0) effort ~ Normal(mu: 0.0, sigma: 10.0) Auxiliary parameters sigma ~ HalfStudentT(nu: 4.0, sigma: 10.0)
Loading...

Prior predictive checks

Model fitting and analysis

Initializing NUTS using jitter+adapt_diag...
Multiprocess sampling (4 chains in 4 jobs)
NUTS: [sigma, Intercept, effort]
Loading...
Loading...
Sampling 4 chains for 1_000 tune and 1_000 draw iterations (4_000 + 4_000 draws total) took 1 seconds.
Loading...
<Figure size 3105x575 with 3 Axes>

Model predictions

Generate samples form the posterior predictive distribution, then use the ArviZ function plot_lm to generate a complete visualization.

<Figure size 900x500 with 1 Axes>
<Figure size 900x500 with 1 Axes>

Comparing to frequentist results

For your convenience, I’ll reproduce the statsmodels analysis from Section 4.1.

Loading...
4.929598282660258
Loading...

Conclusions

We see effort tends to increase student scores. The results we obtain from the Bayesian analysis are largely consistent with the frequentist results from Section 4.1, however Bayesian models allow for simpler interpretation.

Example 2: doctors sleep scores

Doctors dataset

(156, 9)
Loading...
Loading...

Bayesian model

TODO: add formulas

Bambi model

Formula: score ~ 1 + alc + weed + exrc Family: gaussian Link: mu = identity Observations: 156 Priors: target = mu Common-level effects Intercept ~ Normal(mu: 50.0, sigma: 40.0) alc ~ Normal(mu: 0.0, sigma: 10.0) weed ~ Normal(mu: 0.0, sigma: 10.0) exrc ~ Normal(mu: 0.0, sigma: 10.0) Auxiliary parameters sigma ~ HalfStudentT(nu: 4.0, sigma: 20.0)
Loading...

Prior predictive checks

What kind of parameters (lines) do we get from the data model when the distribution of the parameters comes from random samples from the priors?

Model fitting and analysis

Initializing NUTS using jitter+adapt_diag...
Multiprocess sampling (4 chains in 4 jobs)
NUTS: [sigma, Intercept, alc, weed, exrc]
Loading...
Loading...
Sampling 4 chains for 1_000 tune and 1_000 draw iterations (4_000 + 4_000 draws total) took 2 seconds.
Loading...
<Figure size 3105x575 with 3 Axes>

Comparing to frequentist results

For your convenience, I’ll reproduce the statsmodels analysis from Section 4.2.

Loading...
8.20276811982562

Conclusions

Example 3: Bayesian logistic regression

Interns data

Loading...

Bayesian logistic regression model

Bambi model

Formula: hired ~ 1 + work Family: bernoulli Link: p = logit Observations: 100 Priors: target = p Common-level effects Intercept ~ Normal(mu: 0.0, sigma: 20.0) work ~ Normal(mu: 2.0, sigma: 2.0)
Loading...

Prior predictive checks

Model fitting and analysis

Modeling the probability that hired==1
Initializing NUTS using jitter+adapt_diag...
Multiprocess sampling (4 chains in 4 jobs)
NUTS: [Intercept, work]
Loading...
Loading...
Sampling 4 chains for 1_000 tune and 1_000 draw iterations (4_000 + 4_000 draws total) took 1 seconds.
There were 2 divergences after tuning. Increase `target_accept` or reparameterize.
Loading...
<Figure size 2070x575 with 2 Axes>
Visualize variability of the results
MAP estimates: -80.4 2.03
<Figure size 900x500 with 1 Axes>

Interpretation of the parameters

We can interpret the results on the log-odds scale, the odds scale, or as marginal effects (slopes) at particular values of the predictor ww.

Parameters as changes in the log-odds

The mode of the posterior distribution Bw^MAP\widehat{B_w}_{\text{MAP}} corresponds to the change in log-odds per unit increase in work hours.

2.0291924050685317
Parameters as ratios of odds

We can also \tt{exp}-transform this estimate to obtain the rate of increase in the odds of getting hired per additional hour of work invested.

7.463317347319193

Actually, the more accurate way to summarize the odds ratio would be to exp-transform the whole posterior distribution fBw∣internsf_{B_w|\tt{interns}}, then find the maximum using mode_from_samples(np.exp(post_work)), which produces the estimate 6.81.

Differences in probabilities

What is the marginal effect of the predictor work for an intern who invests 40 hours of effort?

Loading...
0.4711935788438129

Predictions

Let’s use the logistic regression model mod3 to predict the probability of being hired for an intern that invests 42 hours of work per week.

Loading...

The mean model prediction is p(42)=0.987=98.7%p(42) = 0.987 = 98.7\%, with hdip,0.94=[0.959,1.0]\mathbf{hdi}_{p,0.94} = [0.959, 1.0], which means the intern will very likely get hired.

Loading...
Plot predictions

We can visualize the predictions by plotting a histogram.

<Figure size 900x500 with 1 Axes>

Comparing to frequentist results

For your convenience, I’ll reproduce the statsmodels analysis from Section 4.6.

Optimization terminated successfully.
         Current function value: 0.138101
         Iterations 10
Intercept -78.693205 work 1.981458 dtype: float64
Loading...

Conclusions

We end up with similar results...

Explanations

Robust linear regression

We swap out the Normal distribution for Student’s tt-distribution to handle outliers better very useful when data has outliers; see EXX

Links:

Formula: score ~ 1 + effort Family: t Link: mu = identity Observations: 15 Priors: target = mu Common-level effects Intercept ~ Normal(mu: 70.0, sigma: 20.0) effort ~ Normal(mu: 0.0, sigma: 10.0) Auxiliary parameters nu ~ Gamma(alpha: 2.0, beta: 0.1) sigma ~ HalfStudentT(nu: 4.0, sigma: 10.0)
Initializing NUTS using jitter+adapt_diag...
Multiprocess sampling (4 chains in 4 jobs)
NUTS: [nu, sigma, Intercept, effort]
Loading...
Loading...
Sampling 4 chains for 1_000 tune and 1_000 draw iterations (4_000 + 4_000 draws total) took 1 seconds.
Loading...

The mean of the slope 4.303 is slightly less than the mean slope we found in mod1 (4.497), which shows the robust model doesn’t care as much about the one outlier.

We also found a slightly smaller sigma, since we’re using the tt-distribution.

Shrinkage priors

Shrinkage priors = Prior distributions for a parameter that shrink its posterior estimate towards a particular value. Sparsity = A situation where most parameter values are zero and only a few are non-zero.

  • Laplace priors L1 regularization = lasso regression Lasso (statistics)

  • Gaussian priors L2 regularization = ridge regression Ridge regression

  • Reference priors Reference prior ppal pha, beta, sigmaq91{sigma Produces the same results as frequentist linear regression

  • Spike-and-slab priors Specialized for spike-and-slab prior = mix- ture of two distributions: one peaked around zero (spike) and the other a diffuse distribution (slab. The spike component identifies the zero elements whereas the slab component captures the non-zero coefficients.

Standardizing predictors

We make choosing priors easier makes inference more efficient cf. 04_lm/cut_material/standardized_predictors.tex Robust linear regression

Discussion

Comparison to frequentist linear models

  • We can obtain similar results

  • Bayesian models naturally apply regularization (no need to manually add in)

Causal graphs

Causal graphs also used with Bayesian LMs (remember Sec 4.5)

Next steps

  • LMs work with categorical predators too, which is what we’ll discuss in Section 5.4

  • LMs can be extended hierarchical models, which is what we’ll discuss in Section 5.5

Exercises

Exercise 1: redo some of the exercises/problems from Ch4 using Bayesian methods

Exercise 2: redo examples of causal inference

Exercise 3: fit model with different priors

Exercise 4: redo logistic regression exercises from Sec 4.6

Exercise 5: bioassay logistic regression

Gelman et al. (2003) present an example of an acute toxicity test, commonly performed on animals to estimate the toxicity of various compounds.

In this dataset log_dose includes 4 levels of dosage, on the log scale, each administered to 5 rats during the experiment. The response variable is death, the number of positive responses to the dosage.

The number of deaths can be modeled as a binomial response, with the probability of death being a linear function of dose:

yi∼Binom(ni,pi)logit(pi)=a+bxi\begin{aligned} y_i &\sim \text{Binom}(n_i, p_i) \\ \text{logit}(p_i) &= a + b x_i \end{aligned}

The common statistic of interest in such experiments is the LD50, the dosage at which the probability of death is 50%.

via notebooks/Section2-PyMC_Intro.ipynb

Initializing NUTS using jitter+adapt_diag...
Multiprocess sampling (4 chains in 4 jobs)
NUTS: [Intercept, log_dose]
Loading...
Loading...
Sampling 4 chains for 1_000 tune and 1_000 draw iterations (4_000 + 4_000 draws total) took 1 seconds.
Loading...

Exercise 6: redo Poisson regression exercises from Sec 4.6

Exercise 7: fit normal and robust to the dataset ??TODO?? which has outliers

BONUS MATERIAL

Simple linear regression using PyMC

(used in Chapter 4 conclusion)

Initializing NUTS using jitter+adapt_diag...
Multiprocess sampling (4 chains in 4 jobs)
NUTS: [B0, Be, Sigma]
Loading...
Loading...
Sampling 4 chains for 1_000 tune and 1_000 draw iterations (4_000 + 4_000 draws total) took 3 seconds.
There were 4 divergences after tuning. Increase `target_accept` or reparameterize.
Loading...
Loading...

Simple linear regression on synthetic data

Initializing NUTS using jitter+adapt_diag...
       Formula: y ~ 1 + x
        Family: gaussian
          Link: mu = identity
  Observations: 100
        Priors: 
    target = mu
        Common-level effects
            Intercept ~ Normal(mu: 0.0, sigma: 10.0)
            x ~ Normal(mu: 0.0, sigma: 10.0)
        
        Auxiliary parameters
            sigma ~ HalfNormal(sigma: 1.0)
Multiprocess sampling (4 chains in 4 jobs)
NUTS: [sigma, Intercept, x]
Loading...
/Users/ivan/Projects/Minireference/STATSbook/noBSstats/venv/lib/python3.12/site-packages/pymc/step_methods/hmc/quadpotential.py:316: RuntimeWarning: overflow encountered in dot
  return 0.5 * np.dot(x, v_out)
Loading...
Sampling 4 chains for 1_000 tune and 1_000 draw iterations (4_000 + 4_000 draws total) took 1 seconds.
Sampling: [Intercept, sigma, x]
<Figure size 3105x575 with 3 Axes>

Summary using mean

Loading...

Summary using median as focus statistic

ETI = Equal-Tailed Interval

Loading...
<Figure size 3105x575 with 3 Axes>
Loading...
Modeling the probability that vote==clinton
       Formula: vote[clinton] ~ 0 + party_id + party_id:age
        Family: bernoulli
          Link: p = logit
  Observations: 421
        Priors: 
    target = p
        Common-level effects
            party_id ~ Normal(mu: [0. 0. 0.], sigma: [1. 1. 1.])
            party_id:age ~ Normal(mu: [0. 0. 0.], sigma: [0.0586 0.0586 0.0586])
Initializing NUTS using jitter+adapt_diag...
Multiprocess sampling (4 chains in 4 jobs)
NUTS: [party_id, party_id:age]
Loading...
Loading...
Sampling 4 chains for 1_000 tune and 1_000 draw iterations (4_000 + 4_000 draws total) took 13 seconds.

One more example

via http://www.medicine.mcgill.ca/epidemiology/joseph/courses/EPIB-682/bayesreg.pdf

Fit a logistic regression model of bone fractures with independent variables age and sex.

The true model had: β0=−25\beta_0 = -25, βsex=0.5\beta_{\tt{sex}} = 0.5, βage=0.4\beta_{\tt{age}} = 0.4.

With so few data points and three parameters to estimate, do not expect posterior means/medians to equal the correct values exactly, but all would most likely be in the 95% intervals.

Formula: frac ~ 1 + sex + age Family: bernoulli Link: p = logit Observations: 100 Priors: target = p Common-level effects Intercept ~ Normal(mu: 0.0, sigma: 10000.0) sex ~ Normal(mu: 0.0, sigma: 10000.0) age ~ Normal(mu: 0.0, sigma: 10000.0)
Modeling the probability that frac==1
Initializing NUTS using jitter+adapt_diag...
Multiprocess sampling (4 chains in 4 jobs)
NUTS: [Intercept, sex, age]
Loading...
Loading...
Sampling 4 chains for 1_000 tune and 2_000 draw iterations (4_000 + 8_000 draws total) took 1 seconds.
Loading...
Optimization terminated successfully.
         Current function value: 0.297593
         Iterations 8
Intercept -21.850408 sex 1.361099 age 0.344670 dtype: float64