我正在编写一个脚本,用于使用自定义模型拟合某些光致发光光谱,并在使用SciPy创建脚本后,我了解到如果lmfit(cars9.uchicago)更容易设置拟合参数的界限使用.edu / software / python / lmfit / intro.html)所以我决定使用它。下面是我编写的一个脚本,用一个高斯函数拟合一个光谱(使用2个高斯函数更好,但我想从一个更简单的情况开始)。
from numpy import loadtxt, vstack, average, exp
import matplotlib.pyplot as plt
import lmfit
def sub_BG(data_array):
naujas_X = data_array[:,1]-average(data_array[1:10,1])
return vstack((data_array[:,0], naujas_X)).T
def gauss(x, a1, b1, c1):
return a1 * exp(-(x- b1)**2/ (2*c1**2))
#amp * exp(-(x-cen)**2 /wid)
data="single_spectra.txt"
spectra = loadtxt(open(data, 'r'), skiprows=2)
spectra_beBG = sub_BG(spectra)
plt.plot(spectra_beBG[:,0],spectra_beBG[:,1],'g')
mod1 = lmfit.Model(gauss)
pars = lmfit.Parameters()
# (Name, Value, Vary, Min, Max, Expr)
pars.add_many(('a1', 590, True, None, None, None),
('b1', 500, True, None, None, None),
('c1', 20, True, None, None , None))
out = mod1.fit(spectra_beBG[:,0], pars, x=spectra_beBG[:,1])
y = gauss(spectra_beBG[:,0],
out.best_values["a1"],
out.best_values["b1"],
out.best_values["c1"])
plt.plot(spectra_beBG[:,0], out.best_fit, "r--")
plt.plot(spectra_beBG[:,0], y, "b--")
print(out.fit_report())
返回:
[[Model]]
Model(gauss)
[[Fit Statistics]]
# function evals = 77
# data points = 1024
# variables = 3
chi-square = 28469283.530
reduced chi-square = 27883.725
[[Variables]]
a1: 561.593868 +/- 8.255604 (1.47%) (init= 590)
b1: 100.129107 +/- 85.34384 (85.23%) (init= 500)
c1: 1.3254e+06 +/- 7.23e+05 (54.52%) (init= 20)
[[Correlations]] (unreported correlations are < 0.100)
C(b1, c1) = -0.892
C(a1, c1) = -0.763
C(a1, b1) = 0.685
如果我将pars.add_many()更改为更接近自然的东西,例如:
pars.add_many(('a1', 590, True, 550, 630, None),
('b1', 500, True, 450, 650, None),
('c1', 30, True, 20, 70 , None))
我明白了:
[[Model]]
Model(gauss)
[[Fit Statistics]]
# function evals = 147
# data points = 1024
# variables = 3
chi-square = 304708538.428
reduced chi-square = 298441.272
[[Variables]]
a1: 629.999937 +/- 0 (0.00%) (init= 590)
b1: 475.821359 +/- 0 (0.00%) (init= 500)
c1: 70 +/- 0 (0.00%) (init= 30)
[[Correlations]] (unreported correlations are < 0.100)
帮助?
答案 0 :(得分:0)
嗯,应该是
out = mod1.fit(spectra_beBG[:,1], pars, x=spectra_beBG[:,0])
也就是说,你想要适应&#34; y&#34;,然后传入&#34; pars&#34;和&#34; x&#34;数组,以帮助计算具有这些参数和自变量的模型。