1988 Election: Multilevel Model
Vote choice for 2,015 respondents in a real 1988 poll, modelled by logistic regression with a random intercept for each state.
What explains a vote for Bush?
In the 1988 US presidential election, some people supported Bush and others supported Dukakis. We want to know how far that difference is explained by who a person is, and how far by the state where they live. The steps below turn this question into a model.
Step 1: the vote $y$
We want to explain $y_i$, the choice of person $i$ in a poll taken before the election:
Here $i$ numbers the 2,015 poll respondents across all states, and $j[i]$ is the state of person $i$. The 48 states and DC in the poll are numbered by $j$.
Step 2: from the vote to the probability $p$ of voting for Bush
Each person has a probability $p_i$ of voting for Bush. The vote $y_i$ is one draw with that probability, like one flip of a coin with bias $p_i$:
If $p_i = 0.6$, then $y_i = 1$ with probability 0.6 and $y_i = 0$ with probability 0.4. The model therefore does not say how a person will vote. Two people with the same $p_i$ can vote differently. What we can explain is why $p_i$ differs from person to person.
Step 3: what could shift that probability
| effect | why we add it | in the model |
|---|---|---|
| gender, race, age, education | groups of people vote differently, and these are measured for each person | fixed effects |
| state | people in the same state share things the survey does not measure, so the state where a person lives also shifts the vote | a random intercept for each state |
The effects are added into one number, the linear predictor $\eta_i$:
Step 4: from a person and a state to the probability
The sum $\eta_i$ can be any number, such as $-1$ or $3$, but $p_i$ must stay between 0 and 1. The logit link connects the two. It sets $\eta_i$ equal to the log-odds of $p_i$:
The effects add on the log-odds scale, and the second formula turns the sum back into a probability.
From a person and a state to a vote
The first two arrows are exact formulas. The last one is random.
The data
The data are a national CBS News/New York Times poll taken before the 1988 election, as published with Gelman and Hill (2006). Each row is one real respondent.
- 2,193 respondents, of whom 178 gave no preference for Bush or Dukakis and are dropped
- 2,015 respondents remain, in 48 states and DC. The poll has nobody from Alaska or Hawaii
- $y$ is the column
bush, and 55.8% of respondents have $y = 1$ - state samples are very uneven: 190 respondents in California, 2 in Vermont and 2 in Wyoming
| predictor | baseline | other levels |
|---|---|---|
| gender | male | female |
| race | non-Black | Black |
| age | 18-29 | 30-44, 45-64, 65+ |
| education | no high school diploma | high school graduate, some college, college graduate |
The file also has a column weight, which is not used here. The results therefore describe the people in the poll. They are not a forecast of the vote.
The data file is at polls.subset.dat. The code below reads it directly.
Why a multilevel model
Voters in the same state share things the survey does not measure, such as the local economy, media markets, campaign effort and political culture. Their votes are therefore not independent, and a model that ignores this gives standard errors that are too small.
There are three ways to treat the states:
| approach | what it does | weakness |
|---|---|---|
| complete pooling | one intercept for all states | ignores real differences between states |
| no pooling | a separate intercept for each state, estimated alone | unstable when a state has few respondents |
| partial pooling | state intercepts drawn from a common distribution | assumes the states are exchangeable |
This page uses partial pooling. Each state estimate is pulled toward the overall mean, and the pull is stronger for states with less data. With 2 respondents in Wyoming, this matters.
The model
For respondent $i$ in state $j[i]$,
and the state effects come from a common normal distribution,
Here $p_i = P(y_i = 1)$. The term $u_j$ shifts the baseline log-odds of a Bush vote up or down for state $j$. It collects everything about the state that the demographic terms do not explain.
Load the data
import pandas as pd
import numpy as np
url = ('https://sites.stat.columbia.edu/gelman/arm/examples/'
'election88/polls.subset.dat')
polls = pd.read_csv(url, sep=r'\s+')
df = polls.dropna(subset=['bush']).copy()
print(f"Respondents in the poll: {len(polls)}")
print(f"No Bush or Dukakis preference: {polls['bush'].isna().sum()}")
print(f"Respondents kept: {len(df)}")
print(f"Bush share among them: {df['bush'].mean():.1%}")
print(f"States, with DC: {df['state'].nunique()}")
print("Respondents per state:")
print(df.groupby('state').size().describe().to_string())
Respondents in the poll: 2193
No Bush or Dukakis preference: 178
Respondents kept: 2015
Bush share among them: 55.8%
States, with DC: 49
Respondents per state:
count 49.000000
mean 41.122449
std 41.995849
min 2.000000
25% 12.000000
50% 30.000000
75% 50.000000
max 190.000000
Fit the model
pyINLA makes dummy variables for non-numeric columns and drops the first level as the baseline, so age and edu are converted to strings. The line {'id': 'state', 'model': 'iid'} adds the state intercepts. family='binomial' with one trial per respondent gives logistic regression.
from pyinla import pyinla
# integer columns would be treated as numeric
df['age_cat'] = df['age'].astype(str)
df['edu_cat'] = df['edu'].astype(str)
df['Ntrials'] = 1
model = {
'response': 'bush',
'fixed': ['1', 'female', 'black', 'age_cat', 'edu_cat'],
'random': [
{'id': 'state', 'model': 'iid'}
]
}
control = {
'compute': {
'dic': True,
'waic': True,
'mlik': True
}
}
py_result = pyinla(
model=model,
family='binomial',
data=df,
Ntrials=df['Ntrials'].to_numpy(),
control=control
)
print(py_result.summary_fixed.drop(columns='kld').to_string())
print()
print(py_result.summary_hyperpar.to_string())
print()
print(f"DIC: {py_result.dic['dic']:.2f}")
print(py_result.mlik.to_string())
mean sd 0.025quant 0.5quant 0.975quant mode
(Intercept) 0.312884 0.192367 -0.064445 0.312884 0.690211 0.312884
female -0.096649 0.095263 -0.283468 -0.096644 0.090138 -0.096644
black -1.750821 0.209739 -2.162490 -1.750685 -1.339928 -1.750684
age_cat2 -0.293120 0.122685 -0.533706 -0.293117 -0.052555 -0.293116
age_cat3 -0.065959 0.136474 -0.333618 -0.065944 0.201609 -0.065943
age_cat4 -0.224180 0.160334 -0.538621 -0.224166 0.090182 -0.224166
edu_cat2 0.230818 0.164474 -0.091612 0.230786 0.553428 0.230786
edu_cat3 0.514568 0.177916 0.165812 0.514525 0.863568 0.514525
edu_cat4 0.313234 0.173278 -0.026420 0.313188 0.653146 0.313188
mean sd 0.025quant 0.5quant 0.975quant mode
Precision for state 7.806398 4.396984 3.010736 6.737357 18.776698 5.393871
DIC: 2645.63
log marginal-likelihood (integration) -1374.323974
log marginal-likelihood (Gaussian) -1374.732124
Fixed effects
The figures on this page share one plotting function. It draws each posterior mean with its 95% credible interval, in teal when the interval excludes the no-effect value and in grey when it does not.
import matplotlib.pyplot as plt
TEAL, GREY, INK, MUTED, RULE = '#0b7f82', '#b4b9c0', '#1a1a1a', '#6b7280', '#e5e7eb'
plt.rcParams.update({
'font.size': 11, 'text.color': INK,
'axes.edgecolor': RULE, 'axes.labelcolor': '#3d434c',
'axes.spines.top': False, 'axes.spines.right': False,
'xtick.color': MUTED, 'ytick.color': MUTED, 'axes.axisbelow': True,
'savefig.dpi': 200, 'savefig.facecolor': 'white',
})
def interval_plot(ax, mean, low, high, no_effect=0, size=60, width=2):
y = np.arange(len(mean))
excludes = (low > no_effect) | (high < no_effect)
colors = np.where(excludes, TEAL, GREY).tolist()
ax.axvline(no_effect, color=MUTED, linewidth=1, linestyle=(0, (4, 3)))
ax.hlines(y, low, high, colors=colors, linewidth=width)
ax.scatter(mean, y, c=colors, s=size, linewidths=0, zorder=3)
ax.grid(axis='x', color=RULE, linewidth=0.8)
ax.tick_params(length=0)
labels = {
'female': 'Female', 'black': 'Black',
'age_cat2': 'Age 30-44', 'age_cat3': 'Age 45-64', 'age_cat4': 'Age 65+',
'edu_cat2': 'High school graduate', 'edu_cat3': 'Some college',
'edu_cat4': 'College graduate'
}
coef = py_result.summary_fixed.drop('(Intercept)').sort_values('mean')
low, high = coef['0.025quant'], coef['0.975quant']
fig, ax = plt.subplots(figsize=(9, 4.4), constrained_layout=True)
interval_plot(ax, coef['mean'], low, high)
ax.set_yticks(range(len(coef)))
ax.set_yticklabels([labels[name] for name in coef.index], color=INK)
ax.set_xlabel('coefficient, log-odds')
fig.savefig('election_coefficients.png')

Three of the eight intervals exclude zero: Black, age 30-44 and some college. Race has by far the largest effect. The interval for gender includes zero, so this poll alone does not settle the size or the sign of that effect.
Odds ratios
The coefficients are on the log-odds scale. Exponentiating a coefficient gives an odds ratio, which is easier to read.
Odds
If 60 of 100 people vote for Bush, the probability is 0.60 and the odds are 60 / 40 = 1.5, or 1.5 Bush voters for each voter who did not choose Bush. In general,
Reading an odds ratio
| odds ratio | meaning | example |
|---|---|---|
| 1 | same odds as the baseline group | |
| above 1 | higher odds, by (OR − 1) × 100% | some college, 1.67: 67% higher |
| below 1 | lower odds, by (1 − OR) × 100% | Black, 0.17: 83% lower |
Each ratio compares a group with its baseline, and always refers to the outcome coded 1, here a vote for Bush. Ratios multiply: 0.25 means the odds are divided by 4. For this reason the figure below uses a log scale, on which 0.5 and 2 lie the same distance from 1.
odds = np.exp(coef[['mean', '0.025quant', '0.975quant']])
odds.columns = ['OR', 'low', 'high']
for name, row in odds.iterrows():
print(f"{labels[name]:21s} {row['OR']:.2f} ({row['low']:.2f} to {row['high']:.2f})")
fig, ax = plt.subplots(figsize=(9, 4.4), constrained_layout=True)
interval_plot(ax, odds['OR'], odds['low'], odds['high'], no_effect=1)
ax.set_xscale('log')
ticks = [0.125, 0.25, 0.5, 1, 2]
ax.set_xticks(ticks)
ax.set_xticklabels([str(t) for t in ticks])
ax.minorticks_off()
ax.set_yticks(range(len(odds)))
ax.set_yticklabels([labels[name] for name in odds.index], color=INK)
ax.set_xlabel('odds ratio against the baseline group, log scale')
fig.savefig('election_odds_ratios.png')
Black 0.17 (0.12 to 0.26)
Age 30-44 0.75 (0.59 to 0.95)
Age 65+ 0.80 (0.58 to 1.09)
Female 0.91 (0.75 to 1.09)
Age 45-64 0.94 (0.72 to 1.22)
High school graduate 1.26 (0.91 to 1.74)
College graduate 1.37 (0.97 to 1.92)
Some college 1.67 (1.18 to 2.37)

| effect | coefficient | odds ratio | 95% interval | compared with the baseline |
|---|---|---|---|---|
| Black | −1.751 | 0.17 | 0.12 to 0.26 | 83% lower odds |
| Age 30-44 | −0.293 | 0.75 | 0.59 to 0.95 | 25% lower odds |
| Age 65+ | −0.224 | 0.80 | 0.58 to 1.09 | interval includes 1 |
| Female | −0.097 | 0.91 | 0.75 to 1.09 | interval includes 1 |
| Age 45-64 | −0.066 | 0.94 | 0.72 to 1.22 | interval includes 1 |
| High school graduate | 0.231 | 1.26 | 0.91 to 1.74 | interval includes 1 |
| College graduate | 0.313 | 1.37 | 0.97 to 1.92 | interval includes 1 |
| Some college | 0.515 | 1.67 | 1.18 to 2.37 | 67% higher odds |
State effects
A caterpillar plot shows the random intercept of each state, ordered from lowest to highest. A state above zero is more pro-Bush than its demographics predict, and a state below zero is less so. The poll codes the states by number, in alphabetical order with DC in 9th place.
# states in alphabetical order, with DC in 9th place
state_abbr = ('AL AK AZ AR CA CO CT DE DC FL GA HI ID IL IN IA KS '
'KY LA ME MD MA MI MN MS MO MT NE NV NH NJ NM NY NC '
'ND OH OK OR PA RI SC SD TN TX UT VT VA WA WV WI WY').split()
state = py_result.summary_random['state'].sort_values('mean')
state['code'] = state['ID'].astype(int)
state['name'] = [state_abbr[code - 1] for code in state['code']]
fig, ax = plt.subplots(figsize=(8, 9.6), constrained_layout=True)
interval_plot(ax, state['mean'], state['0.025quant'], state['0.975quant'],
size=18, width=1.3)
ax.set_yticks(range(len(state)))
ax.set_yticklabels(state['name'], color=INK, fontsize=8.5)
ax.set_ylim(-1, len(state))
ax.spines['left'].set_visible(False)
ax.set_xlabel('state effect, log-odds')
fig.savefig('election_state_effects.png')
print(state[['name', 'mean', '0.025quant', '0.975quant']].iloc[[0, 1, 2, -3, -2, -1]]
.round(2).to_string(index=False))
name mean 0.025quant 0.975quant
MD -0.54 -1.17 0.03
MA -0.46 -0.96 0.01
MN -0.46 -0.99 0.04
UT 0.48 -0.19 1.29
AL 0.53 -0.03 1.16
TN 0.62 0.09 1.20

Only New York and Tennessee have intervals that exclude zero. The other intervals are wide because most states have few respondents. The order is still sensible in part: Massachusetts and Minnesota, which Dukakis won, are near the bottom, and Tennessee, Alabama and Utah, which Bush won, are at the top. It is not exact. Maryland is lowest, although Bush won it, and its sample has only 31 respondents.
Shrinkage
All 11 respondents in Utah chose Bush, and so did both respondents in Wyoming. Taken alone, these states would look unanimous. The figure compares each state's own votes with its effect from the model.
votes = df.groupby('state')['bush'].agg(['size', 'sum'])
votes = votes.join(state.set_index('code')[['name', 'mean']])
# log-odds of each state's own votes, against the whole poll
share = df['bush'].mean()
own = np.log((votes['sum'] + 0.5) / (votes['size'] - votes['sum'] + 0.5))
votes['own'] = own - np.log(share / (1 - share))
fig, ax = plt.subplots(figsize=(9, 3.6), constrained_layout=True)
ax.axline((0, 0), slope=1, color=MUTED, linewidth=1, linestyle=(0, (4, 3)))
ax.axhline(0, color=RULE, linewidth=0.8)
ax.scatter(votes['own'], votes['mean'], s=2.5 * votes['size'], color=TEAL,
alpha=0.55, linewidths=0)
for _, row in votes[votes['name'].isin(['UT', 'WY', 'DC', 'NY'])].iterrows():
ax.annotate(row['name'], (row['own'], row['mean']), xytext=(0, 7),
textcoords='offset points', ha='center', fontsize=9)
ax.set_aspect('equal')
ax.set_xlim(-2.5, 3.2)
ax.set_ylim(-1, 1)
ax.tick_params(length=0)
ax.set_xlabel("state's own votes, log-odds against the whole poll")
ax.set_ylabel('state effect from the model')
fig.savefig('election_shrinkage.png')
print(votes[['name', 'size', 'sum', 'own', 'mean']].sort_values('own')
.iloc[[0, 1, -2, -1]].round(2).to_string(index=False))
name size sum own mean
DC 3 0.0 -2.18 -0.09
MD 31 8.0 -1.25 -0.54
WY 2 2.0 1.38 0.11
UT 11 11.0 2.90 0.48

Small states are pulled hard toward zero. Wyoming moves from 1.38 to 0.11, on 2 respondents, and Utah from 2.90 to 0.48, on 11. Large states keep most of their own value: New York moves from −0.54 to −0.45, on 163 respondents.
Variation between states
pyINLA reports the precision of the state effects. The variance is its inverse, and the standard deviation is the square root of the variance.
from scipy import stats
prec_mean = py_result.summary_hyperpar['mean'].values[0]
state_var = 1 / prec_mean
state_sd = np.sqrt(state_var)
print(f"State effect precision: {prec_mean:.3f}")
print(f"State effect variance: {state_var:.3f}")
print(f"State effect SD: {state_sd:.3f}")
means = state['mean'].values
x = np.linspace(means.min() - 0.3, means.max() + 0.3, 200)
fig, ax = plt.subplots(figsize=(7, 3.8), constrained_layout=True)
ax.hist(means, bins=12, density=True, color='#9fd8d9', edgecolor='white')
ax.plot(x, stats.norm.pdf(x, 0, state_sd), color=TEAL, linewidth=2.2)
ax.grid(axis='y', color=RULE, linewidth=0.8)
ax.tick_params(length=0)
ax.set_xlabel('posterior mean of the state effect, log-odds')
ax.set_ylabel('density')
fig.savefig('election_state_variance.png')
State effect precision: 7.806
State effect variance: 0.128
State effect SD: 0.358

The standard deviation is about 0.36 on the log-odds scale. A state one SD above average has odds about exp(0.36) = 1.4 times those of an average state, for voters with the same demographics. The estimate is uncertain: the 95% interval for the precision, 3.01 to 18.78, corresponds to an SD between 0.23 and 0.58.
The state effects use model='iid', which treats states as exchangeable: knowing the effect of one state says nothing about another. With spatial correlation between neighbouring states, model='besag' or model='bym' would be used instead.
Fixed and random effects
| fixed effects | random effects | |
|---|---|---|
| models | specific categories of interest, such as male and female | groups seen as a sample from a population, such as states |
| estimates | the effect of each category | the variance across groups, and each group's effect with shrinkage |
| reads as | Black respondents have 83% lower odds of choosing Bush | states vary with SD 0.36 in their baseline support |
A check on simulated data
With real data the true values are unknown, so the poll cannot show that the method recovers them. As a separate check, election_1988.csv holds 6,003 simulated respondents in 50 numbered states, generated from known values. It is not poll data. The same model fitted to it gives:
| term | true value | estimate | 95% interval |
|---|---|---|---|
| Intercept | 0.3 | 0.374 | 0.177 to 0.572 |
| Female | −0.1 | −0.177 | −0.283 to −0.071 |
| Black | −1.5 | −1.372 | −1.575 to −1.169 |
| Age 30-44 | −0.3 | −0.268 | −0.412 to −0.124 |
| Age 45-64 | −0.1 | −0.114 | −0.259 to 0.031 |
| Age 65+ | −0.2 | −0.234 | −0.408 to −0.061 |
| High school graduate | 0.2 | 0.035 | −0.106 to 0.177 |
| Some college | 0.5 | 0.406 | 0.248 to 0.564 |
| College graduate | 0.3 | 0.143 | −0.038 to 0.324 |
| State precision | 5 | 5.99 | 3.56 to 9.36 |
Nine of the ten true values lie inside their intervals. The miss, high school graduate, is about what chance gives with 95% intervals.
References
- Gelman, A., and Hill, J. (2006). Data Analysis Using Regression and Multilevel/Hierarchical Models. Cambridge University Press. Chapters 11-14.
- Rue, H., Martino, S. and Chopin, N. (2009). Approximate Bayesian inference for latent Gaussian models using integrated nested Laplace approximations. Journal of the Royal Statistical Society: Series B, 71(2), 319-392.