Multi-level model with nonsense state and county coefficients

Hello PyMC3 Community,

I’m new to the Bayesian/PyMC3 community and I’m coming to you with a question about how to make my model make more sense. In my model, I want to have an intercept term that’s informed by the county my data is in which should be informed by the state that my county is in. However, when I finish running my model I end up with lots of coefficients that don’t make sense i.e., a coefficient for a county that doesn’t belong to a given state. Which brings me to my question. Is there a way I can inform my model to not create coefficients for state and county combos that aren’t present in my data?

I’m including my code below with the model with along with a screen shot of the intercept term of my model.

with pm.Model(coords=coords) as hierarchical_model_varying_intercept_county_state:
    
    # Hyper Priors: State
    sigma_a_state = pm.HalfNormal("sigma_a_state", 3.)
    mu_a_state = pm.Normal("mu_a_state",mu=9., sigma = 2.5)
    
    # State coefficients
    a_state_offset = pm.Normal("a_state_offset", mu = 0., sigma = 1., dims="state")
    a_state = pm.Deterministic("a_state", mu_a_state + sigma_a_state*a_state_offset)
    
    # Hyper Priors: County
    sigma_a_county = pm.HalfNormal("sigma_a_county", 3.)
    mu_a_county = pm.Normal("mu_a_county",mu = 0., sigma = 2.5)    

    # County coefficients
    a_county_offset = pm.Normal("a_county_offset", mu = 0., sigma = 1., dims= ("county", "state"))
    a_county = pm.Deterministic("a_county", mu_a_county + a_state + sigma_a_county*a_county_offset)
    
    # Model error
    epsilon = pm.HalfCauchy("eps", 5.0)

    yield_estimate = (
                 a_county[county_idx, state_idx]
                )

    # Data likelihood
    disease_like = pm.TruncatedNormal("disease_likelihood", 
                           mu=yield_estimate, 
                           sigma=epsilon, 
                           observed = data.disease.values, 
                           dims="obs_id", lower = 0.)

I think the issue is with dims= ("county", "state")). Try to reframe the model so that this is dims="county", and yield_estimate becomes

yield_estimate = (
                 a_county[county_idx] +
                )

Hi @DanWeitzenfeld

Sorry I took so long to get back to you. I’m brand new to this community and I triggered the spam bot with my first post.

I tried to work with your suggestion, but I seem to have made the problem worse. I think the issue is that I don’t understand how the dims from coords and the index variables county_idx, state_idx, and obs_id work together. In the following code, I’ve managed to remove “state” from dims in the definition of a_county_offset, but now when I run:

pm.model_to_graphviz(hierarchical_model_varying_intercept_county_state)

I can see that my model has built a coefficient for every observation. To make the discussion easier, I’ve included some sample data, which will hopefully make my code easier to follow.

import arviz as az
import numpy as np
import pandas as pd
import pymc3 as pm

sample_data = pd.DataFrame({"state":["CA", "NV", "CA", "NV", "CA", "CA", "NV", "CA", "NV", "CA", "CA", "NV", "CA", "NV", "CA"],
               "county":["Los Angeles", "Clark", "San Diego", "Washoe", "Orange", "Los Angeles", "Clark", "San Diego", "Washoe", "Orange", "Los Angeles", "Clark", "San Diego", "Washoe", "Orange"],
               "disease_count": [7., 8., 9., 10., 11., 6., 7., 8., 9., 10., 5., 6., 7., 8., 9.]})

county, counties = pd.factorize(sample_data["county"], sort = True)
state, states = pd.factorize(sample_data["state"], sort = True)

coords = {
    "state" : states,
    "county" : counties,
    "obs_id" : np.arange(sample_data.shape[0])
}```

with pm.Model(coords=coords) as hierarchical_model_varying_intercept_county_state:

state_idx = pm.Data("state_idx", state, dims = "obs_id")
county_idx = pm.Data("county_idx", county, dims="obs_id")

# Hyper Priors: State
sigma_a_state = pm.HalfNormal("sigma_a_state", 3.)
mu_a_state = pm.Normal("mu_a_state",mu=9., sigma = 2.5)

# State coefficients
a_state_offset = pm.Normal("a_state_offset", mu = 0., sigma = 1., dims="state")
a_state = pm.Deterministic("a_state", mu_a_state + sigma_a_state*a_state_offset)

# Hyper Priors: County
sigma_a_county = pm.HalfNormal("sigma_a_county", 3.)
mu_a_county = pm.Normal("mu_a_county",mu = 0., sigma = 2.5)    

# County coefficients
a_county_offset = pm.Normal("a_county_offset", mu = 0., sigma = 1., dims= "county")
a_county = pm.Deterministic("a_county", a_state[state_idx] + mu_a_county + sigma_a_county*a_county_offset[county_idx])

# Model error
epsilon = pm.HalfCauchy("eps", 5.0)

disease_estimate = (
              a_county[county_idx]
            )

# Data likelihood
disease_like = pm.TruncatedNormal("disease_likelihood", 
                       mu=disease_estimate, 
                       sigma=epsilon, 
                       observed = sample_data.disease_count.values, 
                       dims="obs_id", lower=0.)

I’m not yet familiar with pm.Data usage, so I got rid of it and just used the idx arrays generated by pandas factorize.
Also, I think mu_a_county is one too many intercepts, so I got rid of that as well.
I don’t have graphviz installed so I can’t check that, but this seems to work:

with pm.Model(coords=coords) as hierarchical_model_varying_intercept_county_state:

    # Hyper Priors: State
    sigma_a_state = pm.HalfNormal("sigma_a_state", 3.)
    mu_a_state = pm.Normal("mu_a_state", mu=9., sigma = 2.5)

    # State coefficients
    a_state_offset = pm.Normal("a_state_offset", mu = 0., sigma = 1., dims="state")
    a_state = pm.Deterministic("a_state", mu_a_state + sigma_a_state*a_state_offset) 

    # Hyper Priors: County
    sigma_a_county = pm.HalfNormal("sigma_a_county", 3.)
    
    # County coefficients
    a_county_offset = pm.Normal("a_county_offset", mu = 0., sigma = 1., dims= "county")
    a_county = pm.Deterministic("a_county", a_state[state] +  sigma_a_county*a_county_offset[county])

    # Model error
    epsilon = pm.HalfCauchy("eps", 5.0)

    # Data likelihood
    disease_like = pm.Normal("disease_likelihood", 
                           mu=a_county, 
                           sigma=epsilon, 
                           observed = sample_data.disease_count.values)

edit: Added code that generated figures.

I’m open to the possibility that I’m interpreting these results wrong or my expected number of coefficients is incorrect, but I would think that should only be a total of 5 intercept terms (one for each county), but my analysis of the model shows that there are as many coefficients as there are observations.

pm.model_to_graphviz(hierarchical_model_varying_intercept_county_state)

The only part I’m confident that looks correct are the state coefficients since there should only be two.

with hierarchical_model_varying_intercept_county_state:
    hierarchical_model_varying_intercept_county_state_idata = pm.sample(draws=500, return_inferencedata=True, tune=500, target_accept=0.95)

az.plot_forest(
hierarchical_model_varying_intercept_county_state_idata, var_names=“a_state”, figsize=(12, 2), r_hat=True, combined=True, textsize=16
);```

but when I pull up the county coefficients, you can see there are 15.

az.plot_forest(
     hierarchical_model_varying_intercept_county_state_idata, var_names="a_county", figsize=(12, 6), r_hat=True, combined=True, textsize=16
);

try:

az.plot_forest(
     trace, var_names="a_county_offset", figsize=(12, 6), r_hat=True, combined=True, textsize=16
);

a_county is expanded to the length of obs; the shape of a_county_offset is the # of counties

Ahhhh ok. So I was looking in the wrong spot. That’s such a relief to finally have this figured out. Thank you!!! Small follow up question. I’m curious what you use to look at the coefficients of your models?

I ask because I would rather see what the distribution of

a_state[state] +  sigma_a_county*a_county_offset[county]

is rather than a_county_offset for a given state/county or for all of the states/counties.