Python處理PDF與CDF


在拿到數據后,最需要做的工作之一就是查看一下自己的數據分布情況。而針對數據的分布,又包括pdf和cdf兩類。

下面介紹使用python生成pdf的方法:

  1. 使用matplotlib的畫圖接口hist(),直接畫出pdf分布;
  2. 使用numpy的數據處理函數histogram(),可以生成pdf分布數據,方便進行后續的數據處理,比如進一步生成cdf;
  3. 使用seaborn的distplot(),好處是可以進行pdf分布的擬合,查看自己數據的分布類型;

上圖所示為采用3種算法生成的pdf圖。下面是源代碼。

from scipy import stats
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns

arr = np.random.normal(size=100)

# plot histogram
plt.subplot(221)
plt.hist(arr)

# obtain histogram data
plt.subplot(222)
hist, bin_edges = np.histogram(arr)
plt.plot(hist)

# fit histogram curve
plt.subplot(223)
sns.distplot(arr, kde=False, fit=stats.gamma, rug=True)
plt.show()

 

下面介紹使用python生成cdf的方法:

  1. 使用numpy的數據處理函數histogram(),生成pdf分布數據,進一步生成cdf;
  2. 使用seaborn的cumfreq(),直接畫出cdf;

上圖所示為采用2種算法生成的cdf圖。下面是源代碼。

from scipy import stats
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns

arr = np.random.normal(size=100)

plt.subplot(121)
hist, bin_edges = np.histogram(arr)
cdf = np.cumsum(hist)
plt.plot(cdf)

plt.subplot(122)
cdf = stats.cumfreq(arr)
plt.plot(cdf[0])

plt.show()

 

在更多時候,需要把pdf和cdf放在一起,可以更好的顯示數據分布。這個實現需要把pdf和cdf分別進行歸一化。

上圖所示為歸一化的pdf和cdf。下面是源代碼。

from scipy import stats
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns

arr = np.random.normal(size=100)

hist, bin_edges = np.histogram(arr)
width = (bin_edges[1] - bin_edges[0]) * 0.8
plt.bar(bin_edges[1:], hist/max(hist), width=width, color='#5B9BD5')

cdf = np.cumsum(hist/sum(hist))
plt.plot(bin_edges[1:], cdf, '-*', color='#ED7D31')

plt.xlim([-2, 2])
plt.ylim([0, 1])
plt.grid()

plt.show()

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM