如何在Python中使用Scipy计算泊松分布随机变量的期望值?

0 投票
1 回答
3212 浏览
提问于 2025-04-18 15:18

我想用Scipy来计算一个服从泊松分布的随机变量的期望值。

import scipy.stats as stats
from scipy.stats import poisson, norm

G = poisson(mu=30)
G.dist.expect(func=lambda x:(x+1), lb=0, ub=np.inf, *G.args, **G.kwds)    

但是这导致了一个错误:

文件 "ipython-input-3-da8a2a80eba8",第2行,模块中 G.dist.expect(func=lambda x:(x+1), lb=0, ub=np.inf, *G.args, **G.kwds)

类型错误:expect() 收到了一个意外的关键字参数 'mu'

如果我用一个正态随机变量尝试同样的代码

F = norm(loc=100,scale=30) 
F.dist.expect(func=lambda x:(x+1), lb=0, ub=np.inf, *F.args, **F.kwds)  

代码就能正常运行,并返回 101.0029332762359。

我应该如何正确地定义随机变量 G,以便我可以使用任何函数来计算期望值?我使用的是 Python 2.7.8(默认,2014年7月26日,15:25:14),IPython 2.1.0。

祝好,Johannes

1 个回答

4

有些函数需要你按照位置来传递参数,而不是用关键词来传递。比如说,stats.poisson里的dist.expect就是一个例子。这个错误信息

TypeError: expect() got an unexpected keyword argument 'mu'

是在说expect不接受关键词参数mu。但是如果你把mu的值直接作为位置参数传进去,你会发现G = stats.poisson(30)是可以正常工作的:

import numpy as np
import scipy.stats as stats

G = stats.poisson(30)
print(G.dist.expect(lambda x: (x+1), G.args, lb=0, ub=np.inf))
# 31.0

另外,G.args必须作为第二个参数传给expect。你可以通过查看G.dist.expect的帮助文档来确认这一点:

In [14]: help(G.dist.expect)
Help on method expect in module scipy.stats._distn_infrastructure:

expect(self, func=None, args=(), loc=0, lb=None, ub=None, conditional=False) method of scipy.stats._discrete_distns.poisson_gen instance

所以你应该使用

G.dist.expect(lambda x: (x+1), G.args, lb=0, ub=np.inf)

而不是

G.dist.expect(func=lambda x:(x+1), lb=0, ub=np.inf, *G.args, **G.kwds)

G.kwds是一个空的字典,所以你在最后传不传它都没关系。

撰写回答