使用“最大似然估计器”实现无法实现曲线拟合

时间:2019-03-27 20:44:21

标签: python-3.x scipy curve-fitting statsmodels log-likelihood

我正在为离散计数数据实现最大似然估计器,以进行曲线拟合,实现了一个curve_fit函数,用作scipy中最小函数的初始猜测参数。我为多个发行版定义并尝试了这些方法,但是为了简单起见,将仅包括一种方法,即logseries发行版。

这时,我还尝试了statsmodels方法中的以下方法: 1. statsmodels.discrete.discrete_model.fit 2. statsmodels.discrete.count_model.fit 3. statsmodels.base.model.GenericLikelihoodModel

大多数曲线拟合往往会遇到溢出错误或内部的难点和零点。我将在另一篇文章中详细介绍这些错误

#Import a few packages
import numpy as np
from scipy.optimize import curve_fit
from scipy.optimize import minimize
from scipy import stats
from numpy import log
import numpy as np
import matplotlib.pyplot as plt

#Given data
x=np.arange(1, 28, 1)
y=np.array([18899, 10427, 6280, 4281, 2736, 1835, 1158, 746, 467, 328, 201, 129, 65, 69, 39, 21, 15, 10, 3, 3, 1, 1, 1, 1, 1, 1, 1])

#Define a custom distribution
def Logser(x, p): 
    return (-p**x)/(x*log(1-p))

#Doing a least squares curve fit
def lsqfit(x, y):
 cf_result = curve_fit(Logser, x, y, p0=0.7, bounds=(0.5,1), method='trf') 
 return cf_result

param_guess=lsqfit(x,y)[0][0]   
print(param_guess)

#Doing a custom MLE definition, minimized using the scipy minimize function

def MLERegression(param_guess):  
 yhat = Logser(x, param_guess) # predictions based on a parameter value
 sd=1 #initially guessed for fitting a normal distribution error around the regressed curve
# next, we flip the Bayesian question
# compute PDF of observed values normally distributed around mean (yhat)
# with a standard deviation of sd
 negLL = -np.sum( stats.norm.logpdf(y, loc=yhat, scale=sd) ) #log of the probability density function
 return negLL

results = minimize(MLERegression, param_guess, method='L-BFGS-B', bounds=(0.5,1.0), options={'disp': True})
final_param=results['x']
print(final_param)

我已经约束了优化器,使其获得与我期望的结果相似的结果(参数值在0.8或0.9左右)。算法以其他方式输出零

1 个答案:

答案 0 :(得分:0)

我认为这是由于缩放。当我通过添加比例因子将方程式更改为“比例*(-p ** X)/(X * log(1-p))”时,得到以下值而没有任何界限:p = 9.0360470735534726E-01和比例= 5.1189277041342692E + 04,得出以下结果: plot

我对p的拟合值确实是0.9。