numpy生成离散概率分布

时间:2014-03-28 05:22:07

标签: python numpy scipy

我正在关注我在http://docs.scipy.org/doc/scipy/reference/tutorial/stats.html#subclassing-rv-discrete找到的代码示例,用于为正态分布的离散值实现随机数生成器。确切的例子(毫不奇怪)工作得很好,但是如果我修改它只允许左或右尾的结果,那么0左右的分布应该太低(bin 0应该包含更多的值)。我必须遇到边界条件,但我无法解决问题。我错过了什么吗?

这是计算每个bin的随机数的结果:

np.bincount(rvs) [1082 2069 1833 1533 1199  837  644  376  218  111   55   20   12    7    2 2]

这是直方图:

enter image description here

from scipy import stats

np.random.seed(42)

def draw_discrete_gaussian(rng, tail='both'):
    # number of integer support points of the distribution minus 1
    npoints = rng if tail == 'both' else rng * 2
    npointsh = npoints / 2
    npointsf = float(npoints)
    # bounds for the truncated normal
    nbound = 4
    # actual bounds of truncated normal
    normbound = (1+1/npointsf) * nbound
    # integer grid
    grid = np.arange(-npointsh, npointsh+2, 1)
    # bin limits for the truncnorm
    gridlimitsnorm = (grid-0.5) / npointsh * nbound
    # used later in the analysis
    gridlimits = grid - 0.5
    grid = grid[:-1]
    probs = np.diff(stats.truncnorm.cdf(gridlimitsnorm, -normbound, normbound))
    gridint = grid

    normdiscrete = stats.rv_discrete(values=(gridint, np.round(probs, decimals=7)), name='normdiscrete')
    # print 'mean = %6.4f, variance = %6.4f, skew = %6.4f, kurtosis = %6.4f'% normdiscrete.stats(moments =  'mvsk')
    rnd_val = normdiscrete.rvs()
    if tail == 'both':
        return rnd_val
    if tail == 'left':
        return -abs(rnd_val)
    elif tail == 'right':
        return abs(rnd_val)


rng = 15
tail = 'right'
rvs = [draw_discrete_gaussian(rng, tail=tail) for i in xrange(10000)]

if tail == 'both':
    rng_min = rng / -2.0
    rng_max = rng / 2.0
elif tail == 'left':
    rng_min = -rng
    rng_max = 0
elif tail == 'right':
    rng_min = 0
    rng_max = rng

gridlimits = np.arange(rng_min-.5, rng_max+1.5, 1)
print gridlimits
f, l = np.histogram(rvs, bins=gridlimits)

# cheap way of creating histogram
import matplotlib.pyplot as plt
%matplotlib inline

bins, edges = f, l
left,right = edges[:-1],edges[1:]
X = np.array([left, right]).T.flatten()
Y = np.array([bins, bins]).T.flatten()

# print 'rvs', rvs
print 'np.bincount(rvs)', np.bincount(rvs)

plt.plot(X,Y)
plt.show()

1 个答案:

答案 0 :(得分:0)

我尝试根据@ user333700和@ user235711的评论回答我自己的问题:

我在normdiscrete = ...

之前插入方法
if tail == 'right':
    gridint = gridint[npointsh:]
    probs = probs[npointsh:]
    s = probs.sum()
    probs = probs / s
elif tail == 'left':
    gridint = gridint[0: npointsh]
    probs = probs[0: npointsh]
    s = probs.sum()
    probs = probs / s

生成的直方图enter image description hereenter image description here看起来更好: