lmfit未按预期执行

2024-04-25 06:47:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在写一个脚本,它将被用来拟合一些定制模型的光致发光光谱,在用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())

这将返回:

^{pr2}$

Graph output1

如果我改变帕斯。加多()更接近自然,例如:

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)

Graph output2

帮忙吗?在


Tags: nonetruedataa1pltoutarrayb1
1条回答
网友
1楼 · 发布于 2024-04-25 06:47:05

嗯,应该是吗

out  = mod1.fit(spectra_beBG[:,1], pars, x=spectra_beBG[:,0])

也就是说,您需要拟合“y”,并传入“pars”和“x”数组,以帮助使用这些参数和自变量计算模型。在

相关问题 更多 >