python - 使用 numpy.average 的加权平均值

标签 python python-2.7 numpy average weighted-average

我有一个数组:

In [37]: bias_2e13 # our array
Out[37]: 
[1.7277990734072355,
 1.9718263893212737,
 2.469657573252167,
 2.869022991373125,
 3.314720313010104,
 4.232269039271717]

数组中每个值的错误是:

In [38]: bias_error_2e13 # the error on each value
Out[38]: 
array([ 0.13271387,  0.06842465,  0.06937965,  0.23886647,  0.30458249,
        0.57906816])

现在我将每个值的误差除以 2:

In [39]: error_half # error divided by 2
Out[39]: 
array([ 0.06635694,  0.03421232,  0.03468982,  0.11943323,  0.15229124,
        0.28953408])

现在我使用 numpy.average 计算数组的平均值,但使用 errors 作为 weights

首先我在值上使用了完整的错误,然后我使用了一半 错误,即错误除以 2。

In [40]: test = np.average(bias_2e13,weights=bias_error_2e13)

In [41]: test_2 = np.average(bias_2e13,weights=error_half)

当一个数组的误差是另一个数组的一半时,两个平均值如何给出相同的结果

In [42]: test
Out[42]: 3.3604746813456936

In [43]: test_2
Out[43]: 3.3604746813456936

最佳答案

因为所有错误都具有相同的相对权重。提供一个weight参数不会改变你平均的实际值,它只是表示每个值对平均值的贡献。换句话说,在将传递的每个值乘以其对应的权重后,np.average 除以提供的权重之和。

>>> import numpy as np
>>> np.average([1, 2, 3], weights=[0.2, 0.2, 0.2])
2.0
>>> np.average([1, 2, 3])
2.0

实际上,n 维类数组容器的平均公式是

enter image description here

如果未提供给 numpy.average,则假定每个权重等于 1 .

关于python - 使用 numpy.average 的加权平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38241174/

相关文章:

python-2.7 - 在类的一个函数中获取用户输入并在 Python 中的另一个函数中使用它

python - 在 Python 中查找 numpy 数组是否是较大数组的子集

python - python中的numpy迭代没有FOR循环

python - 测试需要 Flask 应用程序或请求上下文的代码

python - PyQt MainWindow 不显示小部件

python - WebDriverException : Message: 'Can not connect to the ChromeDriver' . utils.is_connectable(self.port) 错误:

python - python 2.x中不可避免的 'encoding is an invalid keyword'错误吗?

python - 如何在python中自动递增

python - 如何将单元格填充设置为透明/无填充

python - 从 Scipy 调用统计函数