如何在pymc中设置确定性变量的关键字

时间:2014-08-07 18:51:09

标签: bayesian python pymc

我试图绘制两个变量之间的差异。我跟随示例集here(搜索true_p_A,它将在右侧部分)

这是我的代码

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)

在示例中,没有为delta创建变量,因此不会插入任何键值。每当我运行此代码时,它告诉我它无法找到密钥。我的问题是如何访问delta后验数据?

1 个答案:

答案 0 :(得分:1)

您在deterministic函数定义之前缺少delta装饰器。如果你从第21行开始改变它是有效的:

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