在测量数据上拟合高斯函数

Fitting Gaus-function on measurement data

我们正在尝试对某些数据拟合高斯函数,但我们总是收到警告,无法估计误差,而且拟合非常糟糕。参数全部估计为1,误差为无穷大。

import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
from uncertainties import unumpy as unp
from uncertainties import ufloat
from uncertainties import umath as um
from scipy.constants import pi,c,e,h,sigma,k,N_A,zero_Celsius

x_H=np.loadtxt('a4_spek.csv',delimiter=',',usecols=0,skiprows=3)
P_H=np.loadtxt('a4_spek.csv',delimiter=',',usecols=1,skiprows=3)

x_H=unp.uarray(x_H,1)+ufloat(38,1) #in mm
x_L=unp.uarray(x_L,1)+ufloat(38,1) #in mm

P_H=unp.uarray(P_H,0.001)-ufloat(0.001,0.001) #in µW
P_L=unp.uarray(P_L,0.001)-ufloat(0.001,0.001) #in µW

def gaus(x,y0,x0,sig):
    return y0*np.exp(-(x-x0)**2/(2*sig**2))/np.sqrt(2*pi*sig**2)


sig=unp.std_devs(P_H)
y=unp.nominal_values(P_H)
x=unp.nominal_values(x_H)

kg, kger = curve_fit(gaus,x,y,sigma=sig,method='lm')    
print(kg)
print(kger)

这是相关数据: a4_spek.csv

感谢您的帮助。

curve_fit 对初始条件敏感。您的情况下的默认设置是 p0 = [1.0, 1.0, 1.0] ,这就是给您带来问题的原因。尝试以下操作,

import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
from uncertainties import unumpy as unp
from uncertainties import ufloat
from uncertainties import umath as um
from scipy.constants import pi,c,e,h,sigma,k,N_A,zero_Celsius

x_H=np.loadtxt('a4_spek.csv',delimiter=',',usecols=0,skiprows=3)
P_H=np.loadtxt('a4_spek.csv',delimiter=',',usecols=1,skiprows=3)

x_H=unp.uarray(x_H,1)+ufloat(38,1) #in mm
#x_L=unp.uarray(x_L,1)+ufloat(38,1) #in mm

P_H=unp.uarray(P_H,0.001)-ufloat(0.001,0.001) #in µW
#P_L=unp.uarray(P_L,0.001)-ufloat(0.001,0.001) #in µW

def gaus(x,y0,x0,sig):
    return y0*np.exp(-(x-x0)**2/(2*sig**2))/np.sqrt(2*pi*sig**2)


sig=unp.std_devs(P_H)
y=unp.nominal_values(P_H)
x=unp.nominal_values(x_H)

kg, kger = curve_fit(gaus, x, y, p0= [100, 100, 100], sigma=sig, method='lm')    
print(kg)
print(kger)

拟合的初始值现在是 [100, 100, 100],这似乎是您数据的更好起点。

输出,

[ 1.48883451 84.19781151  3.66861888]
[[ 0.00923875 -0.00232398  0.01531638]
 [-0.00232398  0.07796845 -0.01488248]
 [ 0.01531638 -0.01488248  0.07563641]]