簡體   English   中英

使用python scipy將伽馬分布擬合到數據中

[英]Using python scipy to fit gamma distribution to data

我想在我的數據中使用伽瑪分布,我使用它

import scipy.stats as ss
import scipy as sp
import numpy as np
import os
import matplotlib.pyplot as plt

alpha = []
beta = []
loc = []

data = np.loadtxt(data)
fit_alpha, fit_loc, fit_beta = ss.gamma.fit(data, floc=0, fscale=1)

我想將其中一個參數保留為伽馬分布作為變量(比如形狀),並修復其中一個參數(比如scale=1 )。 但是,如果我將loc變量保持為零,我無法將比例固定為一。 這有什么解決方法嗎? 我是否可以僅使用形狀和比例來參數化伽瑪分布?

在評論中,我說你遇到了gamma分布中的一個錯誤 - 它不會讓你修復位置和比例。 該錯誤已在scipy 0.13中修復,但如果您無法升級,則可以使用rv_continuous類的fit方法來解決該rv_continuous ,該方法是gamma的父類:

In [22]: from scipy.stats import rv_continuous, gamma

In [23]: x = gamma.rvs(2.5, loc=0, scale=4, size=1000)  # A test sample.

In [24]: rv_continuous.fit(gamma, x, floc=0, fscale=4)
Out[24]: (2.5335837650122608, 0, 4)

看看gamma.fit的實現:

def fit(self, data, *args, **kwds):
    floc = kwds.get('floc', None)
    if floc == 0:
        xbar = ravel(data).mean()
        logx_bar = ravel(log(data)).mean()
        s = log(xbar) - logx_bar
        def func(a):
            return log(a) - special.digamma(a) - s
        aest = (3-s + math.sqrt((s-3)**2 + 24*s)) / (12*s)
        xa = aest*(1-0.4)
        xb = aest*(1+0.4)
        a = optimize.brentq(func, xa, xb, disp=0)
        scale = xbar / a
        return a, floc, scale
    else:
        return super(gamma_gen, self).fit(data, *args, **kwds)

如果你把floc = None,它會調用父類的fit函數(這是rv_continuous),你可以修復比例。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM