【问题标题】:How do I calculate expected values of a Poisson distributed random variable in Python using Scipy?如何使用 Scipy 在 Python 中计算泊松分布随机变量的期望值?
【发布时间】:2014-07-30 18:20:30
【问题描述】:

我想使用 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)

TypeError: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。

祝你好运,约翰内斯

【问题讨论】:

    标签: python numpy scipy


    【解决方案1】:

    有些函数需要位置参数而不是关键字参数。 stats.poissondist.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 是一个空字典,所以不管你想不想在最后传递它。

    【讨论】:

    • 谢谢!为什么在我上面的示例中,相同的代码适用于正态分布,而不适用于泊松?
    • 首先,API 不保证所有发行版都可以带关键字参数。其次,stats.normstats.poisson 实例是自动生成的,它们接受的参数是通过对其方法的自省推导出来的。 locscale 参数存在于每个发行版中,因此它们被方便地制成关键字参数。但一般来说,用于自动生成参数的代码不会使其他参数成为关键字参数。 The autogeneration code
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-12-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-14
    • 2020-12-09
    • 1970-01-01
    • 2020-03-14
    相关资源
    最近更新 更多