from pathlib import Path
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import lapylace as lp
root = Path("../../ROS-Examples")
def coef_medians(fit):
return pd.Series(
[np.median(fit.alpha_draws()), *np.median(fit.beta_draws(), axis=0)],
index=["Intercept", *fit.columns],
)
def fit_glm(formula, data, family=None, seed=1, prior_scale=2.5, intercept_scale=5, aux_scale=10, **kwargs):
return lp.stan_glm(
formula,
data=data,
family=family or lp.gaussian(),
prior=lp.normal(0, prior_scale),
prior_intercept=lp.normal(0, intercept_scale),
prior_aux=lp.exponential(aux_scale),
chains=2,
parallel_chains=2,
iter_warmup=300,
iter_sampling=500,
seed=seed,
refresh=100,
**kwargs,
)Elections and the economy: hills of uncertainty
Source: ElectionsEconomy/hills.Rmd
This page visualizes posterior draws for the intercept and slope in the Hibbs regression, fitted through lapylace.
Setup
hibbs = pd.read_csv(root / "ElectionsEconomy/data/hibbs.dat", sep=r"\s+")
fit = fit_glm("vote ~ growth", hibbs, seed=17901, prior_scale=10, intercept_scale=100, aux_scale=10)
coef_medians(fit).round(2)
Intercept 46.33
growth 3.02
dtype: float64
draws = pd.DataFrame({"intercept": fit.alpha_draws(), "growth": fit.beta_draws()[:,0]})
fig, axes = plt.subplots(1, 2, figsize=(8, 3))
axes[0].hist(draws.intercept, bins=30, color="0.6")
axes[0].set_title("Intercept")
axes[1].hist(draws.growth, bins=30, color="0.6")
axes[1].set_title("Growth slope")
fig.tight_layout()