首页 > 解决方案 > 使用 scipy 对单个函数的多个输出进行曲线拟合

问题描述

好的,我有一个函数,它使用一系列参数来计算随着时间的推移对两个独立变量的影响。这些变量已经与一些现有数据进行曲线匹配以最小化变化(如下所示) 例子

我希望能够检查以前的工作,并匹配新数据。我一直在尝试scipy.optimize.curve_fit通过堆叠我的函数产生的 x 和 y 数据来使用该函数(如此处建议:用 scipy 拟合多个参数曲线)。

这可能不是正确的方法,或者我可能只是误解了,但我的代码一直遇到类型错误TypeError: Improper input: N=3 must not exceed M=2

我的简化原型代码最初取自这里:https ://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.curve_fit.html

import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit

def func(x, a, b, c):
    result = ([],[])
    for i in x:
        #set up 2 example curves
        result[0].append(a * np.exp(-b * i) + c)
        result[1].append(a * np.exp(-b * i) + c**2)
    return result #as a tuple containing 2 lists

#Define the data to be fit with some noise:
xdata = list(np.arange(0, 10, 1))
y = func(xdata, 2.5, 5, 0.5)[0]
y2 = func(xdata, 1, 1, 2)[1]

#Add some noise
y_noise = 0.1 * np.random.normal(size=len(xdata))
y2_noise = 0.1 * np.random.normal(size=len(xdata))

ydata=[]
ydata2=[]

for i in range(len(y)): #clunky
    ydata.append(y[i] + y_noise[i])
    ydata2.append(y2[i] + y2_noise[i])

plt.scatter(xdata, ydata, label='data')
plt.scatter(xdata, ydata2, label='data2')
#plt.plot(xdata, y, 'k-', label='data (original function)')
#plt.plot(xdata, y2, 'k-', label='data2 (original function)')

#stack the data
xdat = xdata+xdata
ydat = ydata+ydata2

popt, pcov = curve_fit(func, xdat, ydat)

plt.plot(xdata, func(xdata, *popt), 'r-',
         label='fit: a=%5.3f, b=%5.3f, c=%5.3f' % tuple(popt))

plt.xlabel('x')
plt.ylabel('y')
plt.legend()
plt.show()

非常感谢任何帮助!

标签: pythonscipycurve-fitting

解决方案


这是用一个共享参数拟合两个不同方程的图形示例代码,如果这看起来像您需要的那样,它可以很容易地适应您的特定问题。

import numpy as np
import matplotlib
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit

y1 = np.array([ 16.00,  18.42,  20.84,  23.26])
y2 = np.array([-20.00, -25.50, -31.00, -36.50, -42.00])
comboY = np.append(y1, y2)

x1 = np.array([5.0, 6.1, 7.2, 8.3])
x2 = np.array([15.0, 16.1, 17.2, 18.3, 19.4])
comboX = np.append(x1, x2)

if len(y1) != len(x1):
    raise(Exception('Unequal x1 and y1 data length'))
if len(y2) != len(x2):
    raise(Exception('Unequal x2 and y2 data length'))


def function1(data, a, b, c): # not all parameters are used here, c is shared
        return a * data + c

def function2(data, a, b, c): # not all parameters are used here, c is shared
        return b * data + c


def combinedFunction(comboData, a, b, c):
    # single data reference passed in, extract separate data
    extract1 = comboData[:len(x1)] # first data
    extract2 = comboData[len(x1):] # second data

    result1 = function1(extract1, a, b, c)
    result2 = function2(extract2, a, b, c)

    return np.append(result1, result2)


# some initial parameter values
initialParameters = np.array([1.0, 1.0, 1.0])

# curve fit the combined data to the combined function
fittedParameters, pcov = curve_fit(combinedFunction, comboX, comboY, initialParameters)

# values for display of fitted function
a, b, c = fittedParameters

y_fit_1 = function1(x1, a, b, c) # first data set, first equation
y_fit_2 = function2(x2, a, b, c) # second data set, second equation

plt.plot(comboX, comboY, 'D') # plot the raw data
plt.plot(x1, y_fit_1) # plot the equation using the fitted parameters
plt.plot(x2, y_fit_2) # plot the equation using the fitted parameters
plt.show()

print('a, b, c:', fittedParameters)

推荐阅读