【问题标题】:Using python scipy to fit gamma distribution to data使用 python scipy 将伽马分布拟合到数据
【发布时间】:2013-09-09 16:58:19
【问题描述】:

我想为我的数据拟合一个伽马分布,我使用这个

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)

我想将 gamma 分布的参数之一保留为变量(比如形状),并修复其中一个参数(比如 scale=1)。但是,如果我将 loc 变量保持为零,则无法将比例固定为 1。有一些解决方法吗?我不能只使用形状和比例来参数化伽玛分布吗?

【问题讨论】:

标签: python statistics scipy gamma-distribution


【解决方案1】:

在评论中我说您在gamma 发行版中遇到了一个错误——它不允许您修复位置和比例。 scipy 0.13 中修复了该错误,但如果无法升级,可以使用rv_continuous 类的fit 方法解决该错误,该类是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)

【讨论】:

【解决方案2】:

看看 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,它会调用父类(即rv_continuous)的fit函数,你可以固定比例。

【讨论】:

    猜你喜欢
    • 2011-02-23
    • 1970-01-01
    • 1970-01-01
    • 2017-04-20
    • 2021-02-15
    • 2018-01-14
    • 1970-01-01
    • 1970-01-01
    • 2016-01-14
    相关资源
    最近更新 更多