使用 pymc 中的装饰器理解代码,Python

Understanding code with decorators in pymc, Python

我试图获取有关分层模型的一些信息,发现这个很棒post:https://sl8r000.github.io/ab_testing_statistics/use_a_hierarchical_model/

其中,关闭中间的post,作者分享了一些代码。我遇到问题的部分是:

@pymc.stochastic(dtype=np.float64)
def hyperpriors(value=[1.0, 1.0]):
  a, b = value[0], value[1]
  if a <= 0 or b <= 0:
    return -np.inf
  else:
    return np.log(np.power((a + b), -2.5))

a = hyperpriors[0]
b = hyperpriors[1]

如你所见,作者使用pymc。现在,我对这里的语法感到困惑。我得到了装饰器的定义,但没有得到带方括号的 ab 的定义。有人在该领域有经验并且愿意分享幕后发生的事情吗?

pymc 项目使用装饰器不是为了 return 一个新函数,而是为了 return 一个 Stochastic() class instance.

来自文档:

Uniformly-distributed discrete stochastic variable switchpoint in (disaster_model) could alternatively be created from a function that computes its log-probability as follows:

@pymc.stochastic(dtype=int)
def switchpoint(value=1900, t_l=1851, t_h=1962):
    """The switchpoint for the rate of disaster occurrence."""
    if value > t_h or value < t_l:
        # Invalid values
        return -np.inf
    else:
        # Uniform log-likelihood
        return -np.log(t_h - t_l + 1)

Note that this is a simple Python function preceded by a Python expression called a decorator [vanRossum2010], here called @stochastic. Generally, decorators enhance functions with additional properties or functionality. The Stochastic object produced by the @stochastic decorator will evaluate its log-probability using the function switchpoint. The value argument, which is required, provides an initial value for the variable. The remaining arguments will be assigned as parents of switchpoint (i.e. they will populate the parents dictionary).

所以 hyperpriorsStochastic class 的一个实例,它是支持索引的对象。因此,您可以在该对象上使用 hyperpriors[0]hyperpriors[1]hyperpriors 不再是 函数。