python - PyMC 中的装饰器

标签 python decorator python-decorators pymc mcmc

我有三个关于装饰器的问题,我无法找到答案:

Q1)PyMC 中装饰器的参数(@Deterministic、@Stochastic)表示什么?

第二季度)

@pymc.stochastic(dtype=int)
def switchpoint(value=10, t_l=0, t_h=110):
    def logp(value, t_l, t_h):
        if value > t_h or value < t_l:
            return -np.inf
        else:
            return -np.log(t_h - t_l + 1)
    def random(t_l, t_h):
        from numpy.random import random
        return np.round( (t_l - t_h) * random() ) + t_l

1)print switchpoint.logp #按照预期打印对数概率

2)print switchpoint.random #不生成随机数

3)print switchpoint.random() #生成随机数

4)print switchpoint.logp() #error

如果 2 不起作用,而 3 起作用,那么 1 就不应该起作用,而 4 应该起作用(这与我观察到的相反)。有人可以解释一下发生了什么事吗?

第三季度)

@pymc.stochastic(dtype=int)
def switchpoint(value=1900, t_l=1851, t_h=1962):
    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)

这里没有指定是logp还是如果我输入switchpoint.logp,这段代码就被执行了?

最佳答案

Q1) 随机的所有参数的含义都记录在 here 中。确定性的参数是相同的,加上记录的附加参数 here .

Q2)行为上的差异在于 PyMC 内部有一些魔法,它实际上执行 switchpoint.logp 函数并将其转换为 Python property ,而 switchpoint.random 则没有得到这种处理,而是作为函数保留。

如果您对实际发生的情况感到好奇,这里有一些相关的 source :

def get_logp(self):
    if self.verbose > 1:
        print '\t' + self.__name__ + ': log-probability accessed.'
    logp = self._logp.get()
    if self.verbose > 1:
        print '\t' + self.__name__ + ': Returning log-probability ', logp

    try:
        logp = float(logp)
    except:
        raise TypeError, self.__name__ + ': computed log-probability ' + str(logp) + ' cannot be cast to float'

    if logp != logp:
        raise ValueError, self.__name__ + ': computed log-probability is NaN'

    # Check if the value is smaller than a double precision infinity:
    if logp <= d_neg_inf:
        if self.verbose > 0:
            raise ZeroProbability, self.errmsg + ": %s" %self._parents.value
        else:
            raise ZeroProbability, self.errmsg

    return logp

def set_logp(self,value):
    raise AttributeError, 'Potential '+self.__name__+'\'s log-probability cannot be set.'

logp = property(fget = get_logp, fset=set_logp, doc="Self's log-probability value conditional on parents.")

那里还发生了一些其他事情,例如在 logp 函数中执行名为 LazyFunction 的操作。 ,但这就是基本思想。

Q3) stochastic 装饰器有一些(更多)魔力,它使用代码自省(introspection)来确定 randomlogp 子函数是否是在switchpoint内定义。如果是,则使用 logp 子函数来计算 logp,如果不是,则仅使用 switchpoint 本身。其源代码是 here :

# This gets used by stochastic to check for long-format logp and random:
if probe:
    # Define global tracing function (I assume this is for debugging??)
    # No, it's to get out the logp and random functions, if they're in there.
    def probeFunc(frame, event, arg):
        if event == 'return':
            locals = frame.f_locals
            kwds.update(dict((k,locals.get(k)) for k in keys))
            sys.settrace(None)
        return probeFunc

    sys.settrace(probeFunc)

    # Get the functions logp and random (complete interface).
    # Disable special methods to prevent the formation of a hurricane of Deterministics
    cur_status = check_special_methods()
    disable_special_methods()
    try:
        __func__()
    except:
        if 'logp' in keys:
            kwds['logp']=__func__
        else:
            kwds['eval'] =__func__
    # Reenable special methods.
    if cur_status:
        enable_special_methods()

for key in keys:
    if not kwds.has_key(key):
        kwds[key] = None

for key in ['logp', 'eval']:
    if key in keys:
        if kwds[key] is None:
            kwds[key] = __func__

同样,还有更多的事情发生,而且相当复杂,但这就是基本的想法。

关于python - PyMC 中的装饰器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24005601/

相关文章:

python - 从 python 生成器接收 'return' 值的最佳方法

python - IPython Notebook NB 转换格式化页脚?

python - 如何从 Pandas 数据框中删除特定列中包含任何字符串的行

python - 在 Mechanize 中获取 '407 Proxy Authentication requires' 错误

python:用默认的kwargs装饰函数

design-patterns - GoF 设计模式 Bridge/Adapter/Decorator

python - 自定义装饰器不允许在主 Python 中调用函数

python装饰器不从传递的常量中获取值

c# - Autofac Singleton Decorator 构造多次

python - 当一个Python函数被修饰时,该修饰在哪些范围内可见?