使用 scipy.rv_continuous 从自定义连续分布中绘制随机数时出错

数据挖掘 Python 统计数据 麻木的 scipy
2022-02-24 19:16:42

我正在尝试从自定义分布中生成随机数样本

p(x)=xnextn.

在阅读了 scipy 网站上的教程后,我编写了一个名为 kbayes 的子类:

class kbayes(rv_continuous):
    def _pdf(self, x, t, n):
        p = x**n * np.exp(-t*n*x)
        s = np.sum(p)
        return p/s

这条线s=np.sum(p)用于规范分布。

当我检查一些数字时,pdf似乎没问题:运行以下代码

ks = np.logspace(-5, -2.3, 1000)
p = kb._pdf(ks, 500, 12)
hist, _ = np.histogram(p, ks)
plt.plot(ks, p)

结果是

测试代码结果

这是我所期望的。

但是当我尝试通过例如生成样本时

p_test = kb.rvs(size=1000, t=500, n=12)

我收到以下错误:

/home/[redacted]/anaconda3/lib/python3.6/site-packages/ipykernel_launcher.py:5: RuntimeWarning: invalid value encountered in double_scalars
  """
/home/[redacted]/anaconda3/lib/python3.6/site-packages/scipy/integrate/quadpack.py:385: IntegrationWarning: The occurrence of roundoff error is detected, which prevents 
  the requested tolerance from being achieved.  The error may be 
  underestimated.
  warnings.warn(msg, IntegrationWarning)

我知道这个分布的实际范围很小(概率高于),但我希望班级能够应对这一点。1010rv_continuous

我将不胜感激有关如何使这项工作的任何输入,或任何其他使用 python 从该发行版中抽取样本的方式。

1个回答

这是一个可以忽略的警告。下面是一个清理示例,它生成样本并忽略该警告。

from   warnings import filterwarnings

import matplotlib.pyplot as plt
import numpy as np
from   scipy.stats import rv_continuous

filterwarnings('ignore')

class kbayes_gen(rv_continuous):
    def _pdf(self, x, t, n):
        p = x**n * np.exp(-t*n*x)
        s = np.sum(p)
        return p/s

kb = kbayes_gen()    
ks = np.logspace(-5, -2.3, 1000)
p = kb._pdf(x=ks, t=500, n=12)
plt.plot(ks, p);

samples = kb.rvs(size=1000, t=500, n=12)