python - 使用 NumPy 获取反向累积密度函数?

标签 python numpy random probability-density

我对特定密度感兴趣,我需要以代表其形状(而非随机)的方式“定期”对其进行采样。

形式上,f是我的密度函数,F是对应的累积密度函数(F' = f),其反函数rF = F^-1 确实存在。我有兴趣通过 F^-1[0, 1] 中的常规样本转换到我的可变域中。像这样的东西:

import numpy as np
uniform_sample = np.linspace(0., 1., 256 + 2)[1:-1] # source sample
shaped_sample = rF(uniform_sample) # this is what I want to get

numpy 是否有专门的方法来完成此操作,还是我应该手动执行此操作?这是指数定律的“手工”方式:

l = 5. # exponential parameter
# f = lambda x: l * np.exp(-l * x) # density function, not used
# F = lambda x: 1 - np.exp(-l * x) # cumulative density function, not used either
rF = lambda y: np.log(1. / (1. - y)) / l # reverse `F^-1` function
# What I need is:
shaped_sample = rF(uniform_sample)

我知道,理论上,rF 在调用 np.random.exponential 时在内部用于绘制随机样本,例如(来自[0, 1]rF 转换得到实际结果)。所以我的猜测是 numpy.random 确实知道它提供的每个分布的 rF 函数。

我如何访问它? numpy 是否提供如下功能:

np.random.<any_numpy_distribution>.rF

np.random.get_reverse_F(<any_custom_density_function>)

.. 还是我应该自己推导出/近似它们?

最佳答案

scipy 具有 numpy.random 中所有(我认为)概率分布的概率分布对象。

http://docs.scipy.org/doc/scipy/reference/stats.html

它们都有一个 ppf() 方法来做你想做的事。

http://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.rv_continuous.ppf.html

在你的例子中:

import scipy.stats as st

l = 5. # exponential parameter
dist = st.expon(0., l) # distribution object provided by scipy
f  = dist.pdf # probability density function
F  = dist.cdf # cumulative density function
rF = dist.ppf # percent point function : reverse `F^-1` function
shaped_sample = rF(uniform_sample)
# and much more!

关于python - 使用 NumPy 获取反向累积密度函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34313940/

相关文章:

python - 使用python urllib和beautiful soup从html站点中提取信息

python - 实现以下逻辑的 pythonic 方法应该是什么?

python - 即使 CLI session 关闭,也要继续在 AWS EC2 上运行 python 脚本

python - sympy 中表达式的数值

python - 使用 python 中的特定规则集生成电话号码

python - 计数器 : ordering elements with equal counts

python - 在c++中,是否可以像Numpy中的ndarray风格一样,用语法[i, j, ...]实现访问数组元素的功能?

python - Numpy修改数组到位?

c++ - 如何在类中编写高效的正态分布

javascript - Node.js Javascript 随机彩色打印