python 標準差計算的實現(xiàn)(std)
numpy.std() 求標準差的時候默認是除以 n 的,即是有偏的,np.std無偏樣本標準差方式為加入?yún)?shù) ddof = 1;
pandas.std() 默認是除以n-1 的,即是無偏的,如果想和numpy.std() 一樣有偏,需要加上參數(shù)ddof=0 ,即pandas.std(ddof=0) ;DataFrame的describe()中就包含有std();
demo:
>>> a array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) >>> np.std(a, ddof = 1) 3.0276503540974917 >>> np.sqrt(((a - np.mean(a)) ** 2).sum() / (a.size - 1)) 3.0276503540974917 >>> np.sqrt(( a.var() * a.size) / (a.size - 1)) 3.0276503540974917
PS:numpy中標準差std的神坑
我們用Matlab作為對比。計算標準差,得到:
>> std([1,2,3]) ans = 1
然而在numpy中:
>>> np.std([1,2,3]) 0.81649658092772603
什么鬼!這么簡單的都能出錯?原因在于,np.std有這么一個參數(shù):
ddof : int, optional
Means Delta Degrees of Freedom. The divisor used in calculations is N - ddof, where N represents the number of elements. By default ddof is zero.
因此,想要正確調(diào)用,必須使ddof=1:
>>> np.std([1,2,3], ddof=1) 1.0
而且,這一特性還影響到了許多基于numpy的包。比如scikit-learn里的StandardScaler。想要正確調(diào)用,只能自己手動設置參數(shù):
ss = StandardScaler() ss.mean_ = np.mean(X, axis=0) ss.scale_ = np.std(X, axis=0, ddof=1) X_norm = ss.transform(X)
當X數(shù)據(jù)量較大時無所謂,當X數(shù)據(jù)量較小時則要尤為注意。
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
解決python-docx打包之后找不到default.docx的問題
今天小編就為大家分享一篇解決python-docx打包之后找不到default.docx的問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-02-02Python在Matplotlib圖中顯示中文字體的操作方法
這篇文章主要介紹了Python在Matplotlib圖中顯示中文字體的方法,本篇主要針對在Ubuntu系統(tǒng)中,matplotlib顯示不了中文的問題,尤其是在無法安裝系統(tǒng)字體的情況下,解決Python繪圖時中文顯示的問題。需要的朋友可以參考下2019-07-07