Pymc3 python 确定性函数

Pymc3 python function to 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 中执行此操作吗?

此模型在“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(with 是 theano.tensor.switch 的别名)来计算 lambda_。还有pm.Deterministic,不过这里不需要。