使用python将一组函数拟合到数据中

时间:2017-11-17 20:32:54

标签: curve-fitting data-fitting

给定此类型的目标函数:



<a href="http://www.codecogs.com/eqnedit.php?latex=\dpi{200}&space;y^{(i)}&space;=&space;\sum_{j=1}^{N_1}&space;\sum_{k=1}^{N_2}&space;D_j*\left&space;[&space;[\exp(-a_{j}*x_{jk}^{(i)})-1&space;]^2&space;-&space;1&space;\right&space;]" target="_blank"><img src="http://latex.codecogs.com/gif.latex?\dpi{200}&space;y^{(i)}&space;=&space;\sum_{j=1}^{N_1}&space;\sum_{k=1}^{N_2}&space;D_j*\left&space;[&space;[\exp(-a_{j}*x_{jk}^{(i)})-1&space;]^2&space;-&space;1&space;\right&space;]" title="y^{(i)} = \sum_{j=1}^{N_1} \sum_{k=1}^{N_2} D_j*\left [ [\exp(-a_{j}*x_{jk}^{(i)})-1 ]^2 - 1 \right ]"
  /></a>
&#13;
&#13;
&#13;

其中D_ja_j是参数,而索引j,k上的求和数不固定(N_1N_2可能不同)。对于一组输入数据( x y)( x 是2D矩阵),如何使用numpy,scipy或lmfit来拟合所涉及的参数-py(https://github.com/lmfit/lmfit-py/blob/master/doc/intro.rst)?

此处有相关帖子Fitting a sum to data in Python,但我的情况似乎有点复杂。谢谢你的评论!

1 个答案:

答案 0 :(得分:0)

我不确定你的公式是否足以给出一个完整的答案,但如果我理解正确,那么你会在拟合之前知道N_1,它将是一些有限的数字,你真的想要2 * N_1拟合参数。如果这是正确的,那么您要做的是动态生成和使用2 * N_1个参数。为此,您可以设置目标函数,如下所示:

def objective(params, ydata, xdata, n_1):
    npts = len(ydata)
    ymodel = np.zeros(npts)
    for j in range(n_1):
        dj = params['d_%i' % (i+1)].value
        aj = params['a_%i' % (i+1)].value
        submodel = calc_model(dj, aj, xdata)
        ymodel += submodel

    return (ymodel - ydata)  

构建参数并运行这样的拟合:

 params = Parameters()
 for i in range(n_1):
     params.add('d_%i' % (i+1), value=1.0)  # set init values here
     params.add('a_%i' % (i+1), value=0.2)  # 

result = minimize(objective, params, args=(ydata, xdata, n_1))