1. 程式人生 > >numpy中標準差std的神坑

numpy中標準差std的神坑

我們用Matlab作為對比。計算標準差,得到:

>> std([1,2,3])
ans =
     1

然而在numpy中:

>>> np.std([1,2,3])
0.81649658092772603

什麼鬼!這麼簡單的都能出錯?原因在於,np.std有這麼一個引數:

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.

因此,想要正確呼叫,必須使ddof=1:

>>> np.std([1,2,3], ddof=1)
1.0

而且,這一特性還影響到了許多基於numpy的包。比如scikit-learn裡的StandardScaler。想要正確呼叫,只能自己手動設定引數:

ss = StandardScaler()
ss.mean_ = np.mean(X, axis=0)
ss.scale_ = np.std(X, axis=0, ddof=1)
X_norm = ss.transform(X)

當X資料量較大時無所謂,當X資料量較小時則要尤為注意。