How access the Model trace from predefined def function in python

Hi fellows, I am trying to create a function and withing that I propose the PYMC3 inference as here:

def get_hyperprior_model(data, N_samples, group_idx):
with pm.Model() as model_h:
μ = pm.Beta(‘μ’, 1., 1.) # hyperprior
κ = pm.HalfNormal(‘κ’, 10) # hyperprior
alpha = pm.Deterministic(‘alpha’, μ*κ)
beta = pm.Deterministic(‘beta’, (1.0-μ)*κ)
θ = pm.Beta(‘θ’, alpha=alpha, beta=beta, shape=len(N_samples)) # prior, len(N_samples) = 3
y = pm.Bernoulli(‘y’, p=θ[group_idx], observed=data)
trace_h = pm.sample(2000)
az.plot_trace(trace_h)
print(az.summary(trace_h))
return(model_h)

model = get_hyperprior_model(data, N_samples, group_idx)

now I want to get the values for “trace_h”, however i donnot know how i should get them from my get_hyperprior_model when I used def function now.

Hi, you can add trace_h in the return of that function, and get its values when calling it.

Somethings like:

def get_hyperprior_model(data, N_samples, group_idx):
    ....
    return (model_h, trace_h)

model, trace = get_hyperprior_model(data, N_samples, group_idx)
1 Like