一、导入库
安装 numpy 库:
pip install -i https://mirrors.aliyun.com/pypi/simple numpy
导入 numpy 库:
import numpy as np
二、代码
计算样本无偏方差:
np.var(sequence, ddof = 1)
计算样本无偏标准差:
np.std(sequence, ddof = 1)
注:这里加上参数 ddof = 1 代表计算无偏估计量,不加就是方差/标准差,均值的无偏估计量就是均值。
三、验证
创建一个长度为 28 的随机样本:
import numpy as np
from random import random
s = np.array([random() for i in range(28)])
输出如下:
>>> s
array([0.93259626, 0.46911754, 0.54737121, 0.53544777, 0.26714662,
0.37934229, 0.54700632, 0.67346936, 0.39982201, 0.21360426,
0.79517928, 0.17532289, 0.73401393, 0.78699864, 0.15338764,
0.31620712, 0.01594868, 0.61922761, 0.590406 , 0.70125128,
0.58197372, 0.87002376, 0.7005907 , 0.82183506, 0.87593159,
0.15591517, 0.41502928, 0.46949077])
计算样本方差和标准差:
>>> np.var(s)
0.06075341764933035
>>> np.std(s)
0.24648208383030673
若记
S
~
\widetilde{S}
S
为总体方差
σ
2
\sigma^2
σ2 的无偏估计量,则有
S
~
?
1
n
?
1
∑
i
=
1
n
(
ε
i
?
ε
 ̄
)
=
n
n
?
1
S
2
\widetilde{S} \triangleq \dfrac{1}{n - 1}\sum_{i = 1}^{n}(\varepsilon_i - \overline{\varepsilon}) = \dfrac{n}{n - 1}S^2
S
?n?11?i=1∑n?(εi??ε)=n?1n?S2
我们的样本大小 n = 28 ,可使用如下命令验证:
n = 28
np.var(s, ddof = 1) == np.var(s) * n / (n - 1)
np.std(s, ddof = 1) == np.std(s) * np.sqrt(n / (n - 1))
输出如下:
>>> np.var(s, ddof = 1) == np.var(s) * n / (n - 1)
True
>>> np.std(s, ddof = 1) == np.std(s) * np.sqrt(n / (n - 1))
True
|