Search code examples
pythonbayesianpymcpymc3deterministic

Pymc3 python function to deterministic


In this notebook from Bayesian Methods for Hackers, they create a Deterministic variable from a python function as such:

# from code line 9 in the notebook
@pm.deterministic
def lambda_(tau=tau, lambda_1=lambda_1, lambda_2=lambda_2):
    out = np.zeros(n_count_data)
    out[:tau] = lambda_1  # lambda before tau is lambda1
    out[tau:] = lambda_2  # lambda after (and including) tau is lambda2
    return out

I'm trying to recreate this experiment almost exactly, but apparently @pm.deterministic is not a thing in pymc3. Any idea how I would do this in pymc3?


Solution

  • This model is translated in the PyMC3 port of "Probabilistic Programming and Bayesian Methods for Hackers" as

    with pm.Model() as model:
        alpha = 1.0/count_data.mean()  # Recall count_data is the
                                       # variable that holds our txt counts
        lambda_1 = pm.Exponential("lambda_1", alpha)
        lambda_2 = pm.Exponential("lambda_2", alpha)
    
        tau = pm.DiscreteUniform("tau", lower=0, upper=n_count_data - 1)
    
        # These two lines do what the deterministic function did above
        idx = np.arange(n_count_data) # Index
        lambda_ = pm.math.switch(tau > idx, lambda_1, lambda_2)
    
        observation = pm.Poisson("obs", lambda_, observed=count_data)
        trace = pm.sample()
    

    Note that we are just using pm.math.switch (with is an alias for theano.tensor.switch) to compute lambda_. There is also pm.Deterministic, but it is not needed here.