Search code examples
bayesianpythonpymc

how to set key for deterministic variable in pymc


I'm trying to plot the difference between two variables. I'm following the example set here (search for true_p_A and it will be in the right section)

Here is my code

def cool(test):

    n_data_points = len(test)
    alpha = 1.0/np.mean(test)
    lambda_1 = pm.Exponential("lambda_1", alpha)  # prior on first behaviour
    lambda_2 = pm.Exponential("lambda_2", alpha)  # prior on second behaviour
    tau = pm.DiscreteUniform("tau", lower=0, upper=len(test))  # prior on behaviour change

    """
    The below deterministic functions map an assignment, in this case 0 or 1,
    to a set of parameters, located in the (1,2) arrays `taus` and `centers`.
    """

    @pm.deterministic
    def lambda_(tau=tau, lambda_1=lambda_1, lambda_2=lambda_2):
        out = np.zeros(n_data_points)
        out[:tau] = lambda_1  # lambda before tau is lambda1
        out[tau:] = lambda_2  # lambda after tau is lambda2
        return out

    def delta(p_A=lambda_1, p_B=lambda_2):
            return p_A - p_B
    obs = pm.Poisson("obs", lambda_, value=test, observed=True)

    model = pm.Model([obs, lambda_, lambda_1, lambda_2, tau,delta])

    mcmc = pm.MCMC(model)
    mcmc.sample(5000, 1000, 1)

    return mcmc,5000,1

def main_plotter(stats,test):
    mcmc,N,bin = stats

    n_count_data = len(test)

    lambda_1_samples = mcmc.trace('lambda_1')[:]
    lambda_2_samples = mcmc.trace('lambda_2')[:]
    tau_samples = mcmc.trace('tau')[:]
    delta_samples = mcmc.trace('delta')
    print(delta_samples)

data = [1,2,1,2.2,5,5.5,6,5.4]
main_plotter( cool(data),data)

In the example no variable is created for delta so no key value is inserted. Whenever I run this code is tells me it can't find the key. My question is what do I need to do to access the delta posterior data?


Solution

  • You are missing the deterministic decorator before the delta function definition. It works if you change starting at line 21:

    @pm.deterministic
    def delta(p_A=lambda_1, p_B=lambda_2):
            return p_A - p_B