python - 生成二项式分布的混合

标签 python statistics distribution random discretization

我想生成二项分布的混合。为什么我需要它是因为 我想要高斯分布的正常离散混合。有没有 scipy 库可用,或者你能指导我的算法。

我知道一般来说,对于预定义的分布,可以使用 ppf。但是对于这个 function 我不认为有任何直接使用ppf的方法。

从每个采样并混合它们似乎也有问题,因为我不知道如何 许多实例我必须从不同的发行版中进行选择。

最后我想要的是这样的: enter image description here

最佳答案

这是生成二项式(和其他)分布的任意混合的简单方法。 它依赖于一个事实,即如果您想从混合物中获取样本 (Nsamp) P(x)=sum(w[i]*P_i(x), i=1..Nmix),那么你可以通过采样来做到这一点 来自每个 P_i(x) 的 Nsamp。然后得到另一个随机变量的另一个 Nsamp 样本,它等于 i 的概率为 w[i]。这个随机变量可用于选择给定样本来自 P_i(x) 中的哪个:

import numpy as np,numpy.random, matplotlib.pyplot as plt

#parameters of the binomial distributions: pairs of (n,p)
binomsP = np.array([.5, .5, .5])
binomsCen = np.array([15, 45, 95]) # centers of binomial distributions
binomsN = (binomsCen/binomsP).astype(int)

fractions = [0.2, 0.3, 0.5]
#mixing fractions of the binomials
assert(sum(fractions)==1)

nbinoms = len(binomsN)
npoints = 10000
cumfractions = np.cumsum(fractions)
def mapper(x):
    # convert the random number between 0 and 1 to
    # the ID of the distribution according to the mixing fractions
    return np.digitize(x, cumfractions)

x0 = np.random.binomial(binomsN[None, :],
        binomsP[None, :], size=(npoints, nbinoms))

x = x0[:, mapper(np.random.uniform(size=npoints))]
plt.hist(x, bin=150, range=(0, 150))

enter image description here

关于python - 生成二项式分布的混合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15413085/

相关文章:

python - 如何对每一组pandas groupby应用不同的功能?

python - Pandas 数据帧 : create new ID variable based on number of modalities of an existing one

r - 循环 R 中的字符串变量

iphone - 团队代理是唯一可以构建 Ad Hoc 的代理吗?

iphone - iOS App 的系统设置是否可以通过 Enterprise Distribution 配置?

python - mplfinance 图表内的阴影区域

python - 根据数据帧 : Python Pandas 中的值进行绘图

matlab - 向量化特征归一化的适当零方差处理?

r - 创建具有固定边距的列联表

r - 从(任意)连续概率分布进行模拟