【问题标题】:Custom distribution in scipy with pdf given给定pdf的scipy中的自定义分发
【发布时间】:2017-07-03 20:24:14
【问题描述】:

我尝试使用通过 scipy.stats 给出的 pdf 定义自定义分布

import numpy as np
from scipy.stats import rv_continuous

class CustomDistribution(rv_continuous):
    def __init__(self, pdf=None):
        super(CustomDistribution, self).__init__()
        self.custom_pdf = pdf
        print "Initialized!"

    def _pdf(self, x, *args):
        if self.custom_pdf is None:
            # print 'PDF is not overridden'
            return super(CustomDistribution, self)._pdf(x, *args)
        else:
            # print 'PDF is overridden'
            return self.custom_pdf(x)

def g(x, mu):
    if x < 0:
        return 0
    else:
        return mu * np.exp(- mu * x)

my_exp_dist = CustomDistribution(pdf=lambda x: g(x, .5))
print my_exp_dist.mean()

如你所见,我尝试定义指数分布 wuth 参数 mu=0.5,但输出如下。

已初始化!

D:\Anaconda2\lib\site-packages\scipy\integrate\quadpack.py:357:

IntegrationWarning:算法不收敛。舍入误差 在外推表中检测到。假设 无法达到要求的容差,并且返回的结果 (如果 full_output = 1) 是可以得到的最好的。
warnings.warn(msg, IntegrationWarning)

D:\Anaconda2\lib\site-packages\scipy\integrate\quadpack.py:357:

IntegrationWarning:已达到最大细分数 (50) 达到了。

2.0576933609

如果增加限制没有改善,建议 分析被积函数以确定困难。如果 可以确定局部难度的位置(奇点, 不连续性)一个人可能会从分裂中获益 间隔并在子范围上调用积分器。也许一个 应使用专用积分器。警告.警告(味精, 集成警告)

我应该怎么做才能改善这一点?

注意:计算精度问题在this GitHub issue中讨论。

【问题讨论】:

    标签: python scipy statistics


    【解决方案1】:

    这似乎可以满足您的需求。每次创建实例时,必须为类的实例指定 lambda 参数的值。 rv_continuous 足够聪明,可以推断出您不提供的项目,但您当然可以提供我在此处提供的更多定义。

    from scipy.stats import rv_continuous
    import numpy
    
    class Neg_exp(rv_continuous): 
        "negative exponential"
        def _pdf(self, x, lambda):
            self.lambda=lambda
            return lambda*numpy.exp(-lambda*x)
        def _cdf(self, x, lambda):
            return 1-numpy.exp(-lambda*x)
        def _stats(self,lambda):
            return [1/self.lambda,0,0,0]
    
    neg_exp=Neg_exp(name="negative exponential",a=0)
    
    print (neg_exp.pdf(0,.5))
    print (neg_exp.pdf(5,.5))
    
    print (neg_exp.stats(0.5))
    
    print (neg_exp.rvs(0.5))
    

    【讨论】:

    • 但是如何在实例构造函数中使用 custom pdf?
    • 您不应该这样做,因为当您定义 _pdf 或 _cdf 时,软件使用您提供的函数签名来获取定义方法(如 rvs)所需的其他信息,如果您不这样做定义_rvs。对于您想要的每个 pdf/cdf,您需要一个 rv_continuous 子类(最多参数)。
    • 这正是我所需要的——我希望软件能够使用我的自定义 pdf 自动计算其他方法。顺便说一句,为什么我的代码会错误地计算指数分布的期望值?
    • 我不知道,因为我对 rv_continuous 的内部工作一无所知。我猜想当你把它放在它不希望找到的地方时,它无法找到它需要的信息。顺便说一句,当我从上面的代码中删除 _stats 方法并重新运行它时,rv_continuous 正确计算了该参数的负二项式的均值和方差。希望我能提供更多信息。
    猜你喜欢
    • 2021-05-13
    • 1970-01-01
    • 2023-03-30
    • 2017-05-30
    • 1970-01-01
    • 1970-01-01
    • 2018-12-12
    • 2015-02-14
    • 1970-01-01
    相关资源
    最近更新 更多