# 在curve_fit中修复拟合参数

##### 问题描述投票：1回答：2

``````def Imaginary(freq, alpha, res, Ms, off):
numerator = (2*alpha*freq*res**2)
denominator = (4*(alpha*res*freq)**2) + (res**2 - freq**2)**2
Im = Ms*(numerator/denominator) + off
return Im

pI = np.array([alpha_init, f_peak, Ms_init, 0])

bounds_I = ([0,0,0,0, -np.inf], [np.inf,np.inf,np.inf, np.inf])

poptI, pcovI = curve_fit(Imaginary, x_interpolate, y_interpolate, pI, bounds=bounds_I)
``````

``````bounds_I = ([0,f_peak+0.001,0,0, -np.inf], [np.inf,f_peak-0.001,np.inf, np.inf])
``````

python scipy curve-fitting
##### 2个回答
3

``````x = np.arange(10)
y = np.sqrt(x)
def parabola(x, a, b, c):
return a*x**2 + b*x + c

fit1 = curve_fit(parabola, x, y)  #  [-0.02989396,  0.56204598,  0.25337086]
b_fixed = 0.5
fit2 = curve_fit(lambda x, a, c: parabola(x, a, b_fixed, c), x, y)
``````

0

``````from lmfit import Model
lmodel = Model(Imaginary)
``````

``````params = lmodel.make_params(alpha=alpha_init, res=f_peak, Ms=Ms_init, off=0)
``````

``````params['alpha'].min = 0
params['res'].min = 0
params['Ms'].min = 0
``````

``````params['res'].vary = False
``````

``````result = lmodel.fit(y_interpolate, params, freq=x_interpolate)
``````

``````print(result.fit_report())
``````

FWIW，lmfit还有许多常见形式的内置模型，包括Lorentzian和Constant偏移。所以，你可以构建这个模型

``````from lmfit.models import LorentzianModel, ConstantModel

mymodel = LorentzianModel(prefix='l_') + ConstantModel()

params = mymodel.make_params()
``````