Pymc3 python函数确定性

时间:2018-02-19 15:59:19

标签: python bayesian pymc pymc3 deterministic

在贝叶斯方法黑客的this notebook中,他们从python函数中创建了一个确定性变量:

# 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

我试图几乎完全重新创建这个实验,但显然@pm.deterministic不是pymc3中的东西。知道如何在pymc3中做到这一点吗?

1 个答案:

答案 0 :(得分:3)

此模型在" Probabilistic Programming and Bayesian Methods for Hackers"的PyMC3端口中翻译。如

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()

请注意,我们只是使用pm.math.switch(使用theano.tensor.switch的别名)来计算lambda_。还有pm.Deterministic,但这里不需要它。