【问题标题】:How to get log likelihood for exponential and gamma distributions如何获得指数和伽马分布的对数似然
【发布时间】:2014-10-24 11:41:57
【问题描述】:

我有一些数据,我可以使用来自Fitting a gamma distribution with (python) Scipy 的代码来拟合伽马分布。

import scipy.stats as ss
import scipy as sp

生成一些伽马数据:

alpha=5
loc=100.5
beta=22
data=ss.gamma.rvs(alpha,loc=loc,scale=beta,size=10000)    
print(data)
# [ 202.36035683  297.23906376  249.53831795 ...,  271.85204096  180.75026301
#   364.60240242]

这里我们将数据拟合到伽马分布:

fit_alpha,fit_loc,fit_beta=ss.gamma.fit(data)
print(fit_alpha,fit_loc,fit_beta)
# (5.0833692504230008, 100.08697963283467, 21.739518937816108)

print(alpha,loc,beta)
# (5, 100.5, 22)

我还可以将指数分布拟合到相同的数据。然而,我想做一个likelihood ratio test。为此,我不仅需要拟合分布,还需要返回可能性。你怎么能在python中做到这一点?

【问题讨论】:

    标签: python statistics scipy statsmodels


    【解决方案1】:

    您可以通过调用stats.gamma 的logpdf 方法然后对数组求和来计算data 的对数似然。

    第一段代码来自您的示例:

    In [63]: import scipy.stats as ss
    
    In [64]: np.random.seed(123)
    
    In [65]: alpha = 5
    
    In [66]: loc = 100.5
    
    In [67]: beta = 22
    
    In [68]: data = ss.gamma.rvs(alpha, loc=loc, scale=beta, size=10000)
    
    In [70]: data
    Out[70]: 
    array([ 159.73200869,  258.23458137,  178.0504184 , ...,  281.91672824,
            164.77152977,  145.83445141])
    
    In [71]: fit_alpha, fit_loc, fit_beta = ss.gamma.fit(data)
    
    In [72]: fit_alpha, fit_loc, fit_beta
    Out[72]: (4.9953385276512883, 101.24295938462399, 21.992307537192605)
    

    以下是计算对数似然的方法:

    In [73]: loglh = ss.gamma.logpdf(data, fit_alpha, fit_loc, fit_beta).sum()
    
    In [74]: loglh
    Out[74]: -52437.410641032831
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-05-27
      • 2020-09-20
      • 2017-04-20
      • 2018-12-20
      • 2013-03-27
      • 1970-01-01
      • 2019-01-31
      • 1970-01-01
      相关资源
      最近更新 更多