Numpy如何调用单函数的均值和方差?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (49)

使用Numpy/Python,可以从单个函数调用返回均值和方差吗?

我知道我可以分开做,但是需要用平均值来计算样本标准差。因此,我不希望使用单独的函数来获得均值和方差。

提问于
用户回答回答于

你不能通过已知的手段np.stdnp.var,你得等着statistics模块

In [329]: a = np.random.rand(1000)

In [330]: %%timeit
   .....: a.mean()
   .....: a.var()
   .....: 
10000 loops, best of 3: 80.6 µs per loop

In [331]: %%timeit
   .....: m = a.mean()
   .....: np.mean((a-m)**2)
   .....: 
10000 loops, best of 3: 60.9 µs per loop

In [332]: m = a.mean()

In [333]: a.var()
Out[333]: 0.078365856465916137

In [334]: np.mean((a-m)**2)
Out[334]: 0.078365856465916137

如果你真的想加快速度,那就试试np.dot进行平方和求和:

In [335]: np.dot(a-m,a-m)/a.size
Out[335]: 0.078365856465916137

In [336]: %%timeit
   .....: m = a.mean()
   .....: c = a-m
   .....: np.dot(c,c)/a.size
   .....: 
10000 loops, best of 3: 38.2 µs per loop
用户回答回答于

还可以利用信号的均值、方差和功率之间的关系来避免减法:

In [7]: import numpy as np

In [8]: a = np.random.rand(1000)

In [9]: %%timeit
   ...: a.mean()
   ...: a.var()
   ...: 
10000 loops, best of 3: 24.7 us per loop

In [10]: %%timeit
    ...: m = a.mean()
    ...: np.mean((a-m)**2)
    ...: 
100000 loops, best of 3: 18.5 us per loop

In [11]: %%timeit
    ...: m = a.mean()
    ...: power = np.mean(a ** 2)
    ...: power - m ** 2
    ...: 
100000 loops, best of 3: 17.3 us per loop

In [12]: %%timeit
    ...: m = a.mean()
    ...: power = np.dot(a, a) / a.size
    ...: power - m ** 2
    ...: 
100000 loops, best of 3: 9.16 us per loop

扫码关注云+社区