如何使用NumPy获得累积分布函数?

时间:2012-05-17 17:44:34

标签: python numpy histogram

我想用NumPy创建一个CDF,我的代码是下一个:

histo = np.zeros(4096, dtype = np.int32)
for x in range(0, width):
   for y in range(0, height):
      histo[data[x][y]] += 1
      q = 0 
   cdf = list()
   for i in histo:
      q = q + i
      cdf.append(q)

我正在走数组,但需要很长时间才能执行程序。有这个功能的内置功能,不是吗?

4 个答案:

答案 0 :(得分:72)

使用直方图是一种解决方案,但它涉及对数据进行分级。这对于绘制经验数据的CDF不是必需的。让F(x)计算小于x的条目数,然后它会增加1,正好在我们看到测量的位置。因此,如果我们对我们的样本进行排序,那么在每个点我们将计数增加一个(或者将分数增加1 / N)并将一个相对于另一个绘制,我们将看到“精确”(即未分箱的)经验CDF。

以下代码示例演示了方法

import numpy as np
import matplotlib.pyplot as plt

N = 100
Z = np.random.normal(size = N)
# method 1
H,X1 = np.histogram( Z, bins = 10, normed = True )
dx = X1[1] - X1[0]
F1 = np.cumsum(H)*dx
#method 2
X2 = np.sort(Z)
F2 = np.array(range(N))/float(N)

plt.plot(X1[1:], F1)
plt.plot(X2, F2)
plt.show()

输出以下内容

enter image description here

答案 1 :(得分:17)

我不确定您的代码在做什么,但如果您hist返回了bin_edgesnumpy.histogram个数组,则可以使用numpy.cumsum生成累积直方图内容的总和。

>>> import numpy as np
>>> hist, bin_edges = np.histogram(np.random.randint(0,10,100), normed=True)
>>> bin_edges
array([ 0. ,  0.9,  1.8,  2.7,  3.6,  4.5,  5.4,  6.3,  7.2,  8.1,  9. ])
>>> hist
array([ 0.14444444,  0.11111111,  0.11111111,  0.1       ,  0.1       ,
        0.14444444,  0.14444444,  0.08888889,  0.03333333,  0.13333333])
>>> np.cumsum(hist)
array([ 0.14444444,  0.25555556,  0.36666667,  0.46666667,  0.56666667,
        0.71111111,  0.85555556,  0.94444444,  0.97777778,  1.11111111])

答案 2 :(得分:3)

更新numpy版本1.9.0。 user545424的答案在1.9.0中不起作用。这有效:

>>> import numpy as np
>>> arr = np.random.randint(0,10,100)
>>> hist, bin_edges = np.histogram(arr, density=True)
>>> hist = array([ 0.16666667,  0.15555556,  0.15555556,  0.05555556,  0.08888889,
    0.08888889,  0.07777778,  0.04444444,  0.18888889,  0.08888889])
>>> hist
array([ 0.1       ,  0.11111111,  0.11111111,  0.08888889,  0.08888889,
    0.15555556,  0.11111111,  0.13333333,  0.1       ,  0.11111111])
>>> bin_edges
array([ 0. ,  0.9,  1.8,  2.7,  3.6,  4.5,  5.4,  6.3,  7.2,  8.1,  9. ])
>>> np.diff(bin_edges)
array([ 0.9,  0.9,  0.9,  0.9,  0.9,  0.9,  0.9,  0.9,  0.9,  0.9])
>>> np.diff(bin_edges)*hist
array([ 0.09,  0.1 ,  0.1 ,  0.08,  0.08,  0.14,  0.1 ,  0.12,  0.09,  0.1 ])
>>> cdf = np.cumsum(hist*np.diff(bin_edges))
>>> cdf
array([ 0.15,  0.29,  0.43,  0.48,  0.56,  0.64,  0.71,  0.75,  0.92,  1.  ])
>>>

答案 3 :(得分:-1)

我不确定是否有现成的答案,确切的方法是定义一个函数:

def _cdf(x,data):
    return(sum(x>data))

这将非常快。