python标准差计算的实现(std)
numpy.std() 求标准差的时候默认是除以 n 的,即是有偏的,np.std⽆偏样本标准差⽅式为加⼊参数 ddof = 1;
pandas.std() 默认是除以n-1 的,即是⽆偏的,如果想和numpy.std() ⼀样有偏,需要加上参数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有这么⼀个参数:
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库是标准库吗⽽且,这⼀特性还影响到了许多基于numpy的包。⽐如scikit-learn⾥的StandardScaler。想要正确调⽤,只能⾃⼰⼿动设置参数:
ss = StandardScaler()
ss.scale_ = np.std(X, axis=0, ddof=1)
X_norm = ss.transform(X)
当X数据量较⼤时⽆所谓,当X数据量较⼩时则要尤为注意。
以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。