如何使用scipy.stats查找np.array的期望值?

ykejflvf  于 7个月前  发布在  其他
关注(0)|答案(1)|浏览(77)

我试图获取NumPy数组的预期值,但当我将数组传递到函数中时遇到了问题,这里是一个例子:

a = np.ones(10)
stats.rv_continuous.expect(args=a)

字符串
我得到这个错误:

Traceback (most recent call last):
  File "<pyshell#3>", line 1, in <module>
    stats.rv_continuous.expect(args=a)
TypeError: expect() missing 1 required positional argument: 'self'


如果我尝试stats.rv_continuous.expect(a),我会得到这个错误:

'numpy.ndarray' object has no attribute '_argcheck'


有人能告诉我如何让scipy.stats与数组一起工作吗?
更新:根据bob的评论,我将代码改为:

st=stats.rv_continuous()
ev = st.expect(args=signal_array)
print(ev)


其中signal_array是一个numpy数组。然而我现在得到这个错误:

Traceback (most recent call last):
  File "C:\Users\...\OneDrive\Área de Trabalho\TickingClock\Main.py", line 35, in <module>
ev = st.expect(args=signal_array)
  File "C:\Users\...\AppData\Local\Programs\Python\Python39\lib\site-packages\scipy\stats\_distn_infrastructure.py", line 2738, in expect
vals = integrate.quad(fun, lb, ub, **kwds)[0] / invfac
  File "C:\Users\...\AppData\Local\Programs\Python\Python39\lib\site-packages\scipy\integrate\quadpack.py", line 351, in quad
retval = _quad(func, a, b, args, full_output, epsabs, epsrel, limit,
  File "C:\Users\...\AppData\Local\Programs\Python\Python39\lib\site-packages\scipy\integrate\quadpack.py", line 465, in _quad
return _quadpack._qagie(func,bound,infbounds,args,full_output,epsabs,epsrel,limit)
  File "C:\Users\...\AppData\Local\Programs\Python\Python39\lib\site-packages\scipy\stats\_distn_infrastructure.py", line 2722, in fun
return x * self.pdf(x, *args, **lockwds)
  File "C:\Users\...\AppData\Local\Programs\Python\Python39\lib\site-packages\scipy\stats\_distn_infrastructure.py", line 1866, in pdf
args, loc, scale = self._parse_args(*args, **kwds)
TypeError: _parse_args() got multiple values for argument 'loc'

daupos2t

daupos2t1#

scipy.stats.rv_continuous是一个类,在调用它的expect方法之前,它必须被子类化和示例化。子类至少需要一个_pdf_cdf方法。它不能“只工作”于数组,因为数组没有定义概率分布。
你的问题包括“我试图获得NumPy数组的期望值”,但你评论说“不,我不想要的只是平均值”,但如果“期望值”甚至为数组定义,这些似乎是矛盾的。(我不知道 * 数组 * 的期望值有什么标准定义,所以我做了一个关于 * 随机变量 * 的期望值的定义如何适应于包含随机变量的独立观察的数组的假设。)来自维基百科“期望值”,例如:
在概率论中,期望值(也称为期望、期望、期望算子、数学期望、均值、平均值或一阶矩)是加权平均的推广。非正式地,期望值是随机变量的大量独立选择结果的算术平均值。
如果你想要一个随机变量的函数的期望值(再次假设我们已经将定义推广到数组的情况),也许你想要scipy.stats.rv_histogram,它使用数据的归一化直方图作为分布的pdf

import numpy as np
from scipy import stats
x = np.ones(10)
hist = np.histogram(x, bins=np.arange(3))
dist = stats.rv_histogram(hist)
dist.pdf([0, 1, 2])  # array([0., 1., 0.])

字符串
它的expect方法没有产生我期望的x = np.ones(10)边缘情况示例的结果,但是它应该为实际数据集做一些合理的事情,尽管它可能会发出警告。
比如说,

import numpy as np
from scipy import stats
x = np.random.rand(10000)
hist = np.histogram(x, bins=50)
dist = stats.rv_histogram(hist)
dist.expect(lambda x: x**2)  # 0.33645365355131046
stats.moment(x, 2, center=0)  # 0.3365266431887173


但是你仍然可能更好地只取应用于数组的函数的样本均值。

np.mean(x**2)  # 0.3365266431887173

相关问题