首页 > 解决方案 > 在 Python 中基于 Weibull 到达时间拟合计数模型?

问题描述

我正在尝试使用以下论文中的泊松分布和 Weibull 计数过程模型来拟合足球目标的数据:

http://www.blakemcshane.com/Papers/jbes_weibull.pdf

Python中的代码如下所示:

from math import exp
from scipy.special import gamma, gammaln
from scipy.misc import factorial
import numpy as np
from scipy.optimize import minimize

# definition of the Weibull count model
Acache = dict()

def A(n, j,rate,shape):
    if not (n, j,rate,shape) in Acache:
        if n == 0:
            Acache[(n, j,rate,shape)] = exp(gammaln(shape*j+1) - gammaln(j+1))
        else:
            Acache[(n, j,rate,shape)] = sum( A(n-1, m,rate,shape) * exp(gammaln(shape*(j-m)+1) - gammaln(j-m+1)) for m in range(n-1, j) )
    return Acache[(n, j,rate,shape)]

def Cn(t, n,rate, shape,J=20):
    return sum( ( (-1)**(j+n) * (rate * t**shape)**j * A(n, j,rate,shape) )/gamma(shape*j+1) for j in range(n, n+J) )

def E(t,rate,shape,J=20, N=20):
    return sum( (n * Cn(t, n,rate,shape, J)) for n in range(0, N) )
#finish Weibul count model

#definition of the poisson distribution
def poisson(k, lamb):
    """poisson pdf, parameter lamb is the fit parameter"""
    return (lamb**k/factorial(k)) * np.exp(-lamb)


def negLogLikelihood(params1,data):
    """ the negative log-Likelohood-Function"""
    lnl = - np.sum(np.log(poisson(data,params1[0])))
    return lnl

def negLogLikelihoodweibull(params,data):
    """ the negative log-Likelohood-Function of weibull count model""" #Is it correct
    for i in range(len(data)):
      lnl = - np.sum((np.log(Cn(1,data[i],params[0],params[1]))))
    return lnl


# get poisson deviated random numbers
data = np.random.poisson(1.5, 100)
print(data)


#print for debug
print(negLogLikelihood([1.5],data))
print(Cn(1,3,1.1,1,20))
print(len(data))
print(negLogLikelihoodweibull([1.5,1],data))


# minimize the negative log-Likelihood
result = minimize(negLogLikelihood,  # function to minimize
                  x0=np.ones(1),     # start value
                  args=(data,),      # additional arguments for function
                  method='Powell',   # minimization method, see docs
                  )
print(result)

# result is a scipy optimize result object, the fit parameters 
# are stored in result.x

print("-----------------------------")


result2 = minimize(negLogLikelihoodweibull,  # function to minimize
                  x0=np.ones(2),     # start value
                  args=(data,),      # additional arguments for function
                  method='Powell',   # minimization method, see docs
                  )
print(result2)

该代码非常适合泊松分布,但对于 Weibull,我有以下问题:

OverflowError:数学范围错误

我该如何解决?

标签: pythoncountdata-fittingmodel-fittingweibull

解决方案


推荐阅读