python - 为什么 stats.rv_continuous 始终返回相同的值?

标签 python python-3.x statistics scipy distribution

我有以下代码片段:

from scipy import stats

class my_distribution(stats.rv_continuous):
    def __init__(self):
        super().__init__(a=0, b=1)

    def _cdf(self, x):
        return 0.2 * log(x)


def main():
    distribution = my_distribution()

    val = [distribution.rvs() for i in range(10000)]

    sum(val) == 10000 # why !?

有趣的是,对于其他函数(例如均匀分布),我得到不同的随机值。

最佳答案

In [24]: class distr_gen(stats.rv_continuous):
   ....:     def _pdf(self, x):
   ....:         return 1./(1.2*x)**0.8
   ....:     

In [25]: d = distr_gen(a=0., b=1., name='xxx')
In [26]: d.rvs(size=10)
Out[26]: 
array([  2.41056898e-05,   6.05777448e-04,   7.62206590e-06,
         1.46271162e-07,   1.49455630e-05,   6.84527767e-05,
         1.62679847e-04,   1.28736701e-05,   4.59315246e-05,
         4.15976052e-05])

您的OP中的代码存在几个问题:

  1. cdf 与 pdf 不对应
  2. cdf(下限)应为 0,cdf(上限)应为 1。您的公式并非如此。

对于如此简单的 pdf,您可能最好纠正 cdf 积分中的错误并反转一张纸上的 cdf。然后将其作为 ppf 方法添加到您的类中。或者,如果您需要的只是随机采样,则只需生成一堆统一的随机数并根据您计算的 ppf 对其进行转换即可。

关于python - 为什么 stats.rv_continuous 始终返回相同的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29123373/

相关文章:

python - XGBoost 回归器中的 "reg_alpha"参数。使用高值是不是不好?

python - 除非包装在函数中,否则为什么打印 for 循环(整数)输出会产生语法错误?

python - 将 QLineEdit() 放入 QTreeWidgetItem()

linux - Linux 中 GetProcessIoCounters 的等价物是什么?

python - 有没有一种简单的方法可以对 pandas 数据框中的分布进行所有成对统计比较?

python - 将日期时间对象转换为整数 python

java - 从 Java 调用 python 脚本时获取输出的问题

python-3.x - 如何在多线程应用程序中使用 aiopg 池?

python - 如何更好地拟合seaborn fiddle 情节?

python - 从距离和日期时间数据创建新的速度列