python - `scipy.stat.distributions` 的内置概率密度函数是否比用户提供的慢?

标签 python performance numpy scipy weibull

假设我有一个数组:adata=array([0.5, 1.,2.,3.,6.,10.]) 我想计算 Weibull 分布的对数似然这个数组,给定参数 [5.,1.5][5.1,1.6]。我从没想过我需要为此任务编写自己的 Weibull 概率密度函数,因为它已经在 scipy.stat.distributions 中提供。所以,应该这样做:

from scipy import stats
from numpy import *
adata=array([0.5, 1.,2.,3.,6.,10.])
def wb2LL(p, x): #log-likelihood of 2 parameter Weibull distribution
    return sum(log(stats.weibull_min.pdf(x, p[1], 0., p[0])), axis=1)

并且:

>>> wb2LL(array([[5.,1.5],[5.1,1.6]]).T[...,newaxis], adata)
array([-14.43743911, -14.68835298])

或者我重新发明轮子,写一个新的Weibull pdf函数,比如:

wbp=lambda p, x: p[1]/p[0]*((x/p[0])**(p[1]-1))*exp(-((x/p[0])**p[1]))
def wb2LL1(p, x): #log-likelihood of 2 paramter Weibull
    return sum(log(wbp(p,x)), axis=1)

并且:

>>> wb2LL1(array([[5.,1.5],[5.1,1.6]]).T[...,newaxis], adata)
array([-14.43743911, -14.68835298])

诚然,我总是理所当然地认为,如果某些东西已经在 scipy 中,那么它应该得到很好的优化,重新发明轮子很少会使它变得更快。但惊喜来了:如果我 timeit,调用 100000 次 wb2LL1(array([[5.,1.5],[5.1,1.6]])[...,newaxis], adata) 需要 2.156s 而 wb2LL(array([[5.,1.5],[5.1,1.6]])[...,newaxis], adata) 调用 100000 次需要5.219 秒,内置的 stats.weibull_min.pdf() 慢了两倍多。

检查源代码 python_path/sitepackage/scipy/stat/distributions.py 并没有提供一个简单的答案,至少对我而言。如果有的话,我希望 stats.weibull_min.pdf() 几乎和 wbp() 一样快。

相关源码:第2999-3033行:

class frechet_r_gen(rv_continuous):
    """A Frechet right (or Weibull minimum) continuous random variable.

    %(before_notes)s

    See Also
    --------
    weibull_min : The same distribution as `frechet_r`.
    frechet_l, weibull_max

    Notes
    -----
    The probability density function for `frechet_r` is::

        frechet_r.pdf(x, c) = c * x**(c-1) * exp(-x**c)

    for ``x > 0``, ``c > 0``.

    %(example)s

    """
    def _pdf(self, x, c):
        return c*pow(x,c-1)*exp(-pow(x,c))
    def _logpdf(self, x, c):
        return log(c) + (c-1)*log(x) - pow(x,c)
    def _cdf(self, x, c):
        return -expm1(-pow(x,c))
    def _ppf(self, q, c):
        return pow(-log1p(-q),1.0/c)
    def _munp(self, n, c):
        return special.gamma(1.0+n*1.0/c)
    def _entropy(self, c):
        return -_EULER / c - log(c) + _EULER + 1
frechet_r = frechet_r_gen(a=0.0, name='frechet_r', shapes='c')
weibull_min = frechet_r_gen(a=0.0, name='weibull_min', shapes='c')

那么,问题是:stats.weibull_min.pdf() 真的更慢吗?如果是,怎么会?

最佳答案

pdf()方法定义在rv_continuous类中,调用frechet_r_gen._pdf()pdf() 的代码是:

def pdf(self,x,*args,**kwds):
    loc,scale=map(kwds.get,['loc','scale'])
    args, loc, scale = self._fix_loc_scale(args, loc, scale)
    x,loc,scale = map(asarray,(x,loc,scale))
    args = tuple(map(asarray,args))
    x = asarray((x-loc)*1.0/scale)
    cond0 = self._argcheck(*args) & (scale > 0)
    cond1 = (scale > 0) & (x >= self.a) & (x <= self.b)
    cond = cond0 & cond1
    output = zeros(shape(cond),'d')
    putmask(output,(1-cond0)+np.isnan(x),self.badvalue)
    if any(cond):
        goodargs = argsreduce(cond, *((x,)+args+(scale,)))
        scale, goodargs = goodargs[-1], goodargs[:-1]
        place(output,cond,self._pdf(*goodargs) / scale)
    if output.ndim == 0:
        return output[()]
    return output

因此,它有很多参数处理代码,这使它变慢了。

关于python - `scipy.stat.distributions` 的内置概率密度函数是否比用户提供的慢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18431629/

相关文章:

python - 如何一次为多个实现运行 python unittests

python - 我怎样才能吞掉Python异常消息?

java - 快速写入持久队列

AngularJS 性能 - 太多观察者?

python - Numpy:具有不同值的索引样本组

Python dataframe 将点击路径行转为列

python - 简单的 Python 挑战 : Fastest Bitwise XOR on Data Buffers

python - 有没有比 np.where 更好的方法使用条件语句来索引大型数组?

python - 3d 数组的乘法和切片

python - 具有两个类的 Seaborn pairplot 非对角线 KDE