從np.random.normal()到正態(tài)分布的擬合操作
先看偉大的高斯分布(Gaussian Distribution)的概率密度函數(probability density function):
對應于numpy中:
numpy.random.normal(loc=0.0, scale=1.0, size=None)
參數的意義為:
loc
:float
此概率分布的均值(對應著整個分布的中心centre)
scale
:float
此概率分布的標準差(對應于分布的寬度,scale越大越矮胖,scale越小,越瘦高)
size
:int or tuple of ints
輸出的shape,默認為None,只輸出一個值
我們更經常會用到的np.random.randn(size)所謂標準正態(tài)分布
對應于np.random.normal(loc=0, scale=1, size)。
采樣(sampling)
# 從某一分布(由均值和標準差標識)中獲得樣本 mu, sigma = 0, .1 s = np.random.normal(loc=mu, scale=sigma, size=1000)
也可使用scipy庫中的相關api(這里的類與函數更符合數理統(tǒng)計中的直覺):
import scipy.stats as st mu, sigma = 0, .1 s = st.norm(mu, sigma).rvs(1000)
校驗均值和方差:
>>> abs(mu < np.mean(s)) < .01 True >>> abs(sigma-np.std(s, ddof=1)) < .01 True # ddof,delta degrees of freedom,表示自由度 # 一般取1,表示無偏估計,
擬合
我們看使用matplotlib.pyplot便捷而強大的語法如何進行高斯分布的擬合:
import matplotlib.pyplot as plt count, bins, _ = plt.hist(s, 30, normed=True) # normed是進行擬合的關鍵 # count統(tǒng)計某一bin出現的次數,在Normed為True時,可能其值會略有不同 plt.plot(bins, 1./(np.sqrt(2*np.pi)*sigma)*np.exp(-(bins-mu)**2/(2*sigma**2), lw=2, c='r') plt.show()
或者:
s_fit = np.linspace(s.min(), s.max()) plt.plot(s_fit, st.norm(mu, sigma).pdf(s_fit), lw=2, c='r')
np.random.normal()的含義及實例
這是個隨機產生正態(tài)分布的函數。(normal 表正態(tài))
先看一下官方解釋:
有三個參數
loc
:正態(tài)分布的均值,對應著這個分布的中心.代表下圖的μ
scale
:正態(tài)分布的標準差,對應分布的寬度,scale越大,正態(tài)分布的曲線 越矮胖,scale越小,曲線越高瘦。 代表下圖的σ
size
:你輸入數據的shape,例子:
下面展示一些 內聯代碼片。
// An highlighted block a=np.random.normal(0, 1, (2, 4)) print(a) 輸出: [[-0.29217334 0.41371571 1.26816017 0.46474676] [ 1.33271487 0.80162296 0.47974157 -1.49748788]]
看這個圖直觀些:
以下為官方文檔:
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
python3 通過 pybind11 使用Eigen加速代碼的步驟詳解
這篇文章主要介紹了python3 通過 pybind11 使用Eigen加速代碼的步驟詳解,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-12-12