如何使用对数普通CDF拟合数据

时间:2019-05-16 21:09:36

标签: python data-fitting cdf

我是Python的新用户,我正在尝试使用CDF拟合一些实验数据。数据如下,它们应该以x轴对数刻度绘制:

%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt

x=np.array([0.995, 3.003, 5.908, 10.525, 13.617, 24.321, 33.917, 47.843, 64.172, 91.353, 126.745, 174.118, 225.059, 292.998, 369.133, 640.295, 828.169, 1255.39, 1496.613, 1942.785])

y=np.array([0.142, 0.2, 0.25, 0.36, 0.498, 0.616, 0.599, 0.7, 0.835, 1.102, 1.083, 1.225, 1.133, 1.165, 1.298, 1.365, 1.298, 1.373, 1.409, 1.538])

pyplot.xscale('log')

plt.plot(x,y,'r.')

我从一个使用以下方法拟合数据的用户中发现了证词:

from scipy.special import erf
from lmfit import Model

def gaussian_cdf(x,amp,mu,sigma):
    return (amp/2.0)*(1+erf((mu-x)/(sigma*np.sqrt(2.0))))


model = Model(gaussian_cdf,prefix='g1_') + Model(gaussian_cdf,prefix='g2_')

params = model.make_params(g1_amp=0.50,g1_mu=94,g1_sigma=1.,
                          g2_amp=0.50,g2_mu=98,g2_sigma=1.)

params['g1_sigma'].min=0
params['g2_sigma'].min=0

result = model.fit(y,params,x = x)

print(result.fit_report())

comps=result.eval_components(result.params,x=x)


plt.plot(x,y,'r.',label='data')
plt.plot(x,result.best_fit,'k-',label='fit')
plt.plot(x,comps['g1_'],'b--',label='g1_')
plt.plot(x,comps['g2_'],'g--',label='g2_')
plt.legend()
plt.show()

enter image description here

但是,当我尝试使此代码适应我自己的问题(上面显示的数据)时,该问题处理LogNormal分布pdf和cdf,结果并不理想。

enter image description here

如果有人可以帮助我,我将非常感谢!

预先感谢

1 个答案:

答案 0 :(得分:0)

您可以使用scipy.optimize.curve_fit并定义您的行,以使其符合y = a * log10(b * x + h)+ k的形式(似乎比对数正态分布更适合您的数据)日志功能。

import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import lognorm
from scipy.optimize import curve_fit

x=np.array([0.995, 3.003, 5.908, 10.525, 13.617, 24.321, 33.917, 47.843, 64.172, 91.353, 126.745, 174.118, 225.059, 292.998, 369.133, 640.295, 828.169, 1255.39, 1496.613, 1942.785])

y=np.array([0.142, 0.2, 0.25, 0.36, 0.498, 0.616, 0.599, 0.7, 0.835, 1.102, 1.083, 1.225, 1.133, 1.165, 1.298, 1.365, 1.298, 1.373, 1.409, 1.538])

def log(x, a, b, h, k):
    return a*np.log10(b*x + h) + k

# Provide guesses to the parameters
params = [6, 1, 0, 0]#, .2]
popt, pcov = curve_fit(log, x, y, p0=params)

plt.plot(x,y,'r.')
plt.plot(x, log(x, *popt), 'k--', label = 'fit: a = %.2f b = %.2f h = %.2f k = %.2f ' 
% tuple(popt)) #locl = %.2f scale = %.2f
plt.legend(loc = 'lower right')
#plt.xscale('log')
plt.show()

没有对数刻度,您将得到如下所示的拟合

enter image description here

使用对数刻度,您的身材看起来像

enter image description here