在Python中计算累积密度函数的导数

时间:2013-07-30 03:49:01

标签: python numpy statistics scipy probability-density

累积密度函数的精确导数是概率密度函数(PDF)吗?我正在使用numpy.diff()来计算导数,这是正确的吗?见下面的代码:

import scipy.stats as s
import matplotlib.pyplot as plt
import numpy as np

wei = s.weibull_min(2, 0, 2) # shape, loc, scale - creates weibull object
sample = wei.rvs(1000)
shape, loc, scale = s.weibull_min.fit(sample, floc=0) 

x = np.linspace(np.min(sample), np.max(sample))

plt.hist(sample, normed=True, fc="none", ec="grey", label="frequency")
plt.plot(x, wei.cdf(x), label="cdf")
plt.plot(x, wei.pdf(x), label="pdf")
plt.plot(x[1:], np.diff(wei.cdf(x)), label="derivative")
plt.legend(loc=1)
plt.show()

Compariosn of CDF, PDF and derivative

如果是这样,我如何将衍生物缩放为等同于PDF?

1 个答案:

答案 0 :(得分:6)

CDF的衍生物是PDF。

以下是CDF衍生物的近似值:

dx = x[1]-x[0]
deriv = np.diff(wei.cdf(x))/dx

import scipy.stats as s
import matplotlib.pyplot as plt
import numpy as np

wei = s.weibull_min(2, 0, 2) # shape, loc, scale - creates weibull object
sample = wei.rvs(1000)
shape, loc, scale = s.weibull_min.fit(sample, floc=0) 

x = np.linspace(np.min(sample), np.max(sample))
dx = x[1]-x[0]
deriv = np.diff(wei.cdf(x))/dx
plt.hist(sample, normed=True, fc="none", ec="grey", label="frequency")
plt.plot(x, wei.cdf(x), label="cdf")
plt.plot(x, wei.pdf(x), label="pdf")
plt.plot(x[1:]-dx/2, deriv, label="derivative")
plt.legend(loc=1)
plt.show()

产量

enter image description here

请注意,与x-locations相关联的deriv已被转移 通过dx/2,所以近似值集中在用于计算它的值之间。