高斯拟合误差:优化警告:无法估计参数的协方差

时间:2018-03-24 22:36:34

标签: python covariance

我试图用高斯函数拟合我的数据。我已经设置了正确的参数,据我所知,我的代码也是正确的。但我没有得到正确的拟合,并且关于参数的协方差存在一些错误。任何人都可以投入时间来审查这段代码并告诉我我错过了什么?

import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
old_settings = np.seterr(all='ignore')
from scipy import interp
from scipy import genfromtxt
import scipy
from math import pi, sqrt
old_settings = np.seterr(all='ignore')


data= genfromtxt('steel.txt')
x= data[:,0]
y= data[:,3]


def gaus(x, amp, mu, s):
    return amp *np.exp(-(x-mu)**2/(2*s**2))

amp,mu,s= 400, 0, -0.1
popt, pcov = curve_fit(gaus,x,y,p0=(400, 0, -0.1))
print(popt) 

p1 = popt[0] 
p2 = popt[1] 
p3 = popt[2] 



residuals = y - gaus(x, amp, mu, s)
fres = sum( (residuals**2)/gaus(x, amp, mu, s) ) 
print(fres)


curvey = gaus(x, p1,p2,p3)
plt.plot(x,y, 'b.', label='experimental data')
plt.plot(x, curvey, 'r.', label='gaussian fit')
plt.legend(loc='best')
plt.ylim(2700,4000)
plt.xlabel('velocity')
plt.ylabel('counts per seconds')
plt.legend()
plt.show()

我的数据在这里: https://www.dropbox.com/s/7wn34goicl8wu0l/steel.txt?dl=0

1 个答案:

答案 0 :(得分:0)

您的拟合函数的范围从0amp。这不是您的数据集的范围。解决方案:为函数添加偏移量:

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

data= genfromtxt('steel.txt')
x= data[:,0]
y= data[:,3]
#added offset parameter
def gaus(x, amp, mu, s, offset):
    return amp *np.exp(-(x-mu)**2/(2*s**2)) + offset

popt, pcov = curve_fit(gaus,x,y,p0=(-4, 0, -0.1, 100))
print(popt) 
#better resolution for fit curve representation
curvex = np.linspace(np.min(x), np.max(x), 1000)
curvey = gaus(curvex, *popt)
plt.plot(x,y, 'b.', label='experimental data')
plt.plot(curvex, curvey, 'r', label='gaussian fit')
plt.legend(loc='best')
plt.ylim(2700,4000)
plt.xlabel('velocity')
plt.ylabel('counts per seconds')
plt.legend()
plt.show()

输出 enter image description here