在pymc、Python中理解带装饰器的代码

2024-06-16 14:42:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图获得一些关于层次模型的信息,发现了这个很棒的帖子:https://sl8r000.github.io/ab_testing_statistics/use_a_hierarchical_model/

在这篇文章的中间,作者分享了一些代码。有一部分我遇到了麻烦:

@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。现在,我被这里的语法搞糊涂了。我得到了decorator的定义,但没有得到带方括号的ab的定义。有没有人有这方面的经验,愿意分享下引擎盖下发生的事情?你知道吗


Tags: httpsiogithub信息returnab定义value
1条回答
网友
1楼 · 发布于 2024-06-16 14:42:57

pymc项目使用decorator不返回新函数,而是返回^{} 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类的一个实例,正是这个对象支持索引。因此,您可以在该对象上使用hyperpriors[0]hyperpriors[1]hyperpriors不再是函数了。你知道吗

相关问题 更多 >