Congress

Predictive uncertainty for congressional elections. See Chapters 10 and 15 in Regression and Other Stories.

Source: Congress/congress.Rmd.

The Python version keeps data handling explicit and uses lapylace for Stan-backed generalized linear models, so the statistical model can be read from a formula rather than from handwritten Stan.

from pathlib import Path
import sys
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import lapylace as lp

sys.path.append(str(Path.cwd().parent / 'python'))
from data import ros_path

Data

congress = pd.read_csv(ros_path('Congress/data', 'congress.csv'))
congress.head()
inc86 inc88 inc90 v86 v88 v90 v86_adj v88_adj v90_adj
0 1 1 1 0.745036 0.772443 0.714029 0.745036 0.772443 0.714029
1 1 1 1 0.673845 0.636182 0.597050 0.673845 0.636182 0.597050
2 1 1 0 0.696457 0.664928 0.521043 0.696457 0.664928 0.521043
3 -1 -1 -1 0.464590 0.273834 0.234377 0.464590 0.273834 0.234377
4 -1 -1 0 0.391095 0.263613 0.477439 0.391095 0.263613 0.477439

Models

The formulas below are the Python counterparts of the model formulas in the source example. Use lapylace for the Stan-backed Bayesian fit with the same formula interface.

# fit = lp.stan_glm('vote ~ past_vote + inc', data=congress, family=lp.gaussian(), chains=4, iter_sampling=1000)

Notes

  • Source computation blocks represented: 15.
  • Data paths are expressed through the shared ros_path() helper.
  • Formula-based Bayesian regressions are routed through lapylace.stan_glm().
  • Plotting and simulation work uses NumPy, pandas, matplotlib idioms.