如何在 Python 中从给定 CDF 的分布中采样

Rap*_*ael 4 python math statistics scipy

我想从CDF 的 1 - e^(-x^2)概率分布中抽取样本。

python/scipy/等中有没有方法?使您能够从仅给定 CDF 的概率分布中进行采样?

Hei*_*ike 6

要创建给定 CDF 的自定义随机变量类,您可以子类化scipy.rv_continuous并覆盖rv_continuous._cdf. 然后,这将自动生成相应的 PDF 和有关您的发行版的其他统计信息,例如

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

class MyRandomVariableClass(stats.rv_continuous):
    def __init__(self, xtol=1e-14, seed=None):
        super().__init__(a=0, xtol=xtol, seed=seed)

    def _cdf(self, x):
        return 1-np.exp(-x**2)


if __name__ == "__main__":
    my_rv = MyRandomVariableClass()

    # sample distribution
    samples = my_rv.rvs(size = 1000)

    # plot histogram of samples
    fig, ax1 = plt.subplots()
    ax1.hist(list(samples), bins=50)

    # plot PDF and CDF of distribution
    pts = np.linspace(0, 5)
    ax2 = ax1.twinx()
    ax2.set_ylim(0,1.1)
    ax2.plot(pts, my_rv.pdf(pts), color='red')
    ax2.plot(pts, my_rv.cdf(pts), color='orange')

    fig.tight_layout()
    plt.show()
Run Code Online (Sandbox Code Playgroud)

  • 哇,这真是太神奇了。您知道它在幕后是如何做到这一点的(即创建 PDF 并提供从中采样的方法)吗?假设它实际上没有做任何微分,那么它一定是某种数值近似。 (3认同)