Python3,scipy.optimize:使模型适合多个数据集

时间:2019-10-04 17:10:36

标签: python-3.x lmfit scipy-optimize

我有一个定义为的模型:

m(x,z)= C1 * x ^ 2 * sin(z)+ C2 * x ^ 3 * cos(z)

我有不同z的多个数据集(z = 1,z = 2,z = 3),其中它们给我m(x,z)作为x的函数。

对于所有z值,参数C1和C2必须相同。

因此,我必须同时使模型适合三个数据集,否则对于z的不同值,我将具有不同的C1和C2值。

这可能与scipy.optimize有关。 我只能对z的一个值进行操作,但无法弄清楚如何对所有z进行处理。

我只写了一个z:

def my_function(x,C1,C1):
    z=1
return C1*x**2*np.sin(z)+ C2*x**3*np.cos(z)


data = 'some/path/for/data/z=1'

x= data[:,0]
y= data[:,1]

from lmfit import Model

gmodel = Model(my_function)
result = gmodel.fit(y, x=x, C1=1.1)

print(result.fit_report())

如何处理多组数据(即不同的z值?)

2 个答案:

答案 0 :(得分:0)

因此,您要做的是对数据进行多维拟合(在您的情况下为二维)。这样,对于整个数据集,您将获得一组最佳地描述数据的C参数。我认为最好的方法是使用scipy.optimize.curve_fit()

因此您的代码应如下所示:

import scipy.optimize as optimize
import numpy as np

def my_function(xz, *par):
    """ Here xz is a 2D array, so in the form [x, z] using your variables, and *par is an array of arguments (C1, C2) in your case """
    x = xz[:,0]
    z = xz[:,1]
    return par[0] * x**2 * np.sin(z) + par[1] * x**3 * np.cos(z)

# generate fake data. You will presumable have this already
x = np.linspace(0, 10, 100)
z = np.linspace(0, 3, 100)
xx, zz = np.meshgrid(x, z) 
xz = np.array([xx.flatten(), zz.flatten()]).T
fakeDataCoefficients = [4, 6.5]
fakeData = my_function(xz, *fakeDataCoefficients) + np.random.uniform(-0.5, 0.5, xx.size)

# Fit the fake data and return the set of coefficients that jointly fit the x and z
# points (and will hopefully be the same as the fakeDataCoefficients
popt, _ = optimize.curve_fit(my_function, xz, fakeData, p0=fakeDataCoefficients)

# Print the results
print(popt)

当我进行拟合时,我得到的正是生成函数的fakeDataCoefficients,因此拟合效果很好。

因此,得出的结论是,您并没有独立进行3次拟合,每次都设置z的值,而是进行了2D拟合,它采用了x和{{1同时找到最佳系数。

答案 1 :(得分:0)

您的代码不完整,并且有一些语法错误。

但是我认为您想构建一个模型,以将不同数据集的模型串联起来,然后将串联的数据拟合到该模型中。在lmfit(公开:作者和维护者)的上下文中,我经常发现更容易使用minimize()和多个数据集拟合的目标函数,而不是Model类。也许从这样的事情开始:

import lmfit
import numpy as np
# define the model function for each dataset 
def my_function(x, c1, c2, z=1): 
    return C1*x**2*np.sin(z)+ C2*x**3*np.cos(z)

# Then write an objective function like this
def f2min(params, x, data2d, zlist):
    ndata, npts = data2d.shape
    residual = 0.0*data2d[:]
    for i in range(ndata):
        c1 = params['c1_%d' % (i+1)].value
        c2 = params['c2_%d' % (i+1)].value
        residual[i,:] = data[i,:] - my_function(x, c1, c2, z=zlist[i])
    return residual.flatten()

# now build that `data2d`, `zlist` and build the `Parameters`
data2d = []
zlist = []
x = None
for fname in dataset_names:
    d = np.loadtxt(fname)  # or however you read / generate data
    if x is None: x = d[:, 0]
    data2d.append(d[:, 1])
    zlist.append(z_for_dataset(fname)) # or however ...

data2d = np.array(data2d)  # turn list into nd array
ndata, npts = data2d.shape
params = lmfit.Parameters()
for i in range(ndata):
    params.add('c1_%d' % (i+1), value=1.0) # give a better starting value!
    params.add('c2_%d' % (i+1), value=1.0) # give a better starting value!

# now you're ready to do the fit and print out the results:
result = lmfit.minimize(f2min, params, args=(x, data2d, zlist))
print(results.fit_report())

该代码确实是一个草图,并且未经测试,但希望可以为您提供良好的入门基础。