我在大学里有一组来自物理实验(简单实验)的数据,我试图将这些数据拟合到我从lmfit库构建的模型中。 我想要一个这样形式的窦基本方形:
I(X)=I0.sinc²(pi.a.X/(λD))
用a:狭缝的宽度, lambda:光的波长 D:距离相机/狭缝 I0:原始强度
import csv as csv
from math import pi
import matplotlib.pyplot as plt
import numpy as np
from lmfit import *
# create data to be fitted
with open('data_1.csv', 'r') as f:
values = list(csv.reader(f, delimiter=','))
values = np.array(values[1:], dtype=np.float)
position = values[:, 0]
intensity = values[:, 1]
#define function model
def fct(x, I0, a, D, b):
return I0 * np.square(np.sinc(pi * a * (x + b) / (0.00000063 * D)))
#b is for the horizontal shift because my experience
#was centered on 700 due to the camera
# do fit
vmodel = Model(fct)
vmodel.set_param_hint('I0', min=0., max=300.)
vmodel.set_param_hint('a', value=0.0005, min=0.0, max=1.)
vmodel.set_param_hint('D', value=0.53, min=0.0, max=1.)
vmodel.set_param_hint('b', min=0., max=2000.)
pars = vmodel.make_params()
result = vmodel.fit(intensity, pars, x=position)
# write report
print(result.fit_report())
#after we plot the data, with position on x and intensity on y
它返回完全错误的值和错误:
RuntimeWarning: invalid value encountered in double_scalars spercent =
'({0:.2%})'.format(abs(par.stderr/par.value))
[[Model]]
Model(fct)
[[Fit Statistics]]
# function evals = 7
# data points = 1280
# variables = 4
chi-square = 4058147.794
reduced chi-square = 3180.367
Akaike info crit = 10326.876
Bayesian info crit = 10347.494
[[Variables]]
I0: 0 +/- 0 (nan%) (init= 0)
a: 0.00050000 +/- 0 (0.00%) (init= 0.0005)
D: 0.50000000 +/- 0 (0.00%) (init= 0.5)
b: 400 +/- 0 (0.00%) (init= 400)
你能帮帮我吗?我从这个库中尝试了很多类型的模型但没有正常工作,我真的需要它。我已经用np.square和其他读物解决了2D问题,主要问题是模型。
等待答案,
谢谢,
答案 0 :(得分:0)
您可能希望为所有参数值提供合理的起始值。在您编写时,I0
或b
没有初始值,但是方便地(?)这些参数设置了边界,因此初始值可以推断(可能很差)作为下限 - 我不知道b
如何变成400.也许是一个错字?
无论如何,我建议尝试
pars = vmodel.make_params(I0=150, b=400)
然后再试一次。