在Python中基于Weibull间隔时间拟合计数模型?

2024-10-01 04:46:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图用泊松分布和威布尔计数过程模型来拟合足球进球的数据:

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: math range error

我该怎么解决呢?在


Tags: theinimportfordatareturnratedef