我想使用lmfit模块将函数拟合到可变数量的数据集,其中包含一些共享参数和一些单独参数。
这是一个生成高斯数据并分别拟合每个数据集的示例:
import numpy as np
import matplotlib.pyplot as plt
from lmfit import minimize, Parameters, report_fit
def func_gauss(params, x, data=[]):
A = params['A'].value
mu = params['mu'].value
sigma = params['sigma'].value
model = A*np.exp(-(x-mu)**2/(2.*sigma**2))
if data == []:
return model
return data-model
x = np.linspace( -1, 2, 100 )
data = []
for i in np.arange(5):
params = Parameters()
params.add( 'A' , value=np.random.rand() )
params.add( 'mu' , value=np.random.rand()+0.1 )
params.add( 'sigma', value=0.2+np.random.rand()*0.1 )
data.append(func_gauss(params,x))
plt.figure()
for y in data:
fit_params = Parameters()
fit_params.add( 'A' , value=0.5, min=0, max=1)
fit_params.add( 'mu' , value=0.4, min=0, max=1)
fit_params.add( 'sigma', value=0.4, min=0, max=1)
minimize(func_gauss, fit_params, args=(x, y))
report_fit(fit_params)
y_fit = func_gauss(fit_params,x)
plt.plot(x,y,'o',x,y_fit,'-')
plt.show()
# ideally I would like to write:
#
# fit_params = Parameters()
# fit_params.add( 'A' , value=0.5, min=0, max=1)
# fit_params.add( 'mu' , value=0.4, min=0, max=1)
# fit_params.add( 'sigma', value=0.4, min=0, max=1, shared=True)
# minimize(func_gauss, fit_params, args=(x, data))
#
# or:
#
# fit_params = Parameters()
# fit_params.add( 'A' , value=0.5, min=0, max=1)
# fit_params.add( 'mu' , value=0.4, min=0, max=1)
#
# fit_params_shared = Parameters()
# fit_params_shared.add( 'sigma', value=0.4, min=0, max=1)
# call_function(func_gauss, fit_params, fit_params_shared, args=(x, data))