如何计算和绘制经验CDF的pdf?

时间:2019-07-12 19:34:14

标签: python numpy matplotlib statistics probability

我有两个numpy数组,一个是x值的数组,另一个是y值的数组,它们一起给了我经验CDF。例如:

plt.plot(xvalues, yvalues)
plt.show()

我认为需要以某种方式对数据进行平滑处理以提供平滑的pdf。

enter image description here

我想绘制pdf。我该怎么办?

原始数据位于:http://dpaste.com/1HVK5DR

2 个答案:

答案 0 :(得分:4)

主要有两个问题:您的数据似乎很嘈杂,并且分布不均:低端的采样点比较密集,而高端的采样点则比较稀疏。这可能会导致数值问题。

因此,我首先建议使用线性插值对数据进行重采样以获取等距样本:(请注意,彼此附加的所有代码片段均构成一个 python文件的内容。)

import matplotlib.pyplot as plt
import numpy as np
from data import xvalues, yvalues #load data from file


print("#datapoints: {}".format(len(xvalues)))
#don't use every point if your computer is not very fast
xv = np.array(xvalues)[::5]
yv = np.array(yvalues)[::5]

#interpolate to have evenly space data
xi = np.linspace(xv.min(), xv.max(), 400)
yi = np.interp(xi, xv, yv)

然后,为了平滑数据,我建议执行RBF回归(=使用"RBF Network")。这个想法是拟合形式的曲线

 c(t) = sum a(i) * phi(t - x(i))    #(not part of the program)

其中phi是一些径向基函数。 (理论上,我们可以使用 any 函数。)要获得非常平滑的结果,我选择一个非常平滑的函数,即高斯函数:phi(x) = exp( - x^2/sigma^2),其中sigma尚待确定。 x(i)只是我们可以定义的一些节点。如果我们有一个平滑函数,我们只需要几个节点。节点的数量还决定了需要完成多少计算。 a(i)是我们可以优化以获得最佳拟合的系数。在这种情况下,我只使用最小二乘法。

请注意,如果我们可以按照上面的形式编写一个函数,则很容易计算导数,就是这样

 c(t) = sum a(i) * phi'(t - x(i))

其中phi'phi的派生词。 #(不是程序的一部分)

关于sigma:通常最好将其选择为我们选择的节点之间的步进倍数。我们选择sigma的次数越大,结果函数越平滑。

#set up rbf network
rbf_nodes = xv[::50][None, :]#use a subset of the x-values as rbf nodes
print("#rbfs: {}".format(rbf_nodes.shape[1]))
#estimate width of kernels:
sigma = 20  #greater = smoother, this is the primary parameter to play with
sigma *= np.max(np.abs(rbf_nodes[0,1:]-rbf_nodes[0,:-1]))


# kernel & derivative
rbf = lambda r:1/(1+(r/sigma)**2)
Drbf = lambda r: -2*r*sigma**2/(sigma**2 + r**2)**2

#compute coefficients of rbf network
r = np.abs(xi[:, None]-rbf_nodes)
A = rbf(r)
coeffs = np.linalg.lstsq(A, yi, rcond=None)[0]
print(coeffs)

#evaluate rbf network
N=1000
xe = np.linspace(xi.min(), xi.max(), N)
Ae = rbf(xe[:, None] - rbf_nodes)
ye = Ae @ coeffs


#evaluate derivative
N=1000
xd = np.linspace(xi.min(), xi.max(), N)
Bd = Drbf(xe[:, None] - rbf_nodes)
yd = Bd @ coeffs


fig,ax = plt.subplots()
ax2 = ax.twinx()

ax.plot(xv, yv, '-')
ax.plot(xi, yi, '-')
ax.plot(xe, ye, ':')

ax2.plot(xd, yd, '-')

fig.savefig('graph.png')
print('done')

enter image description here

答案 1 :(得分:-1)

您需要从CDF到PDF的导数

PDF(x) = d CDF(x)/ dx

使用NumPy,您可以使用gradient

pdf = np.gradient(yvalues, xvalues)
plt.plot(xvalues, pdf)
plt.show()

或手动差速器

pdf = np.diff(yvalues)/np.diff(xvalues)
l = np.asarray(xvalues[:-1])
r = np.asarray(xvalues[1:])
plt.plot((l+r)/2.0, pdf) # points in the middle of interval
plt.show()

两者都产生了类似的图像,但由于某种原因而被破坏了

enter image description here