python – 将参数传递给函数以进行拟合

我试图拟合一个函数,它将输入2个独立变量x,y和3个参数作为输入a,b,c.这是我的测试代码:

import numpy as np
from scipy.optimize import curve_fit

def func(x,y, a, b, c):
    return a*np.exp(-b*(x+y)) + c    

y= x = np.linspace(0,4,50)
z = func(x,y, 2.5, 1.3, 0.5) #works ok
#generate data to be fitted
zn = z + 0.2*np.random.normal(size=len(x))
popt, pcov = curve_fit(func, x,y, zn) #<--------Problem here!!!!!

但是我得到了错误:“func()正好接受5个参数(给定51个)”.怎么能正确地传递我的论证x,y?

最佳答案 只需看看
documentation of scipy.optimize.curve_fit()即可.原型是

scipy.optimize.curve_fit(f, xdata, ydata, p0=None, sigma=None, **kw)

文档状态curve_fit()被调用,目标函数作为第一个参数,独立变量作为第二个参数,因变量作为第三个参数,参数的起始值作为第四个参数.您试图以完全不同的方式调用该函数,因此它不起作用也就不足为奇了.具体来说,您将zn作为p0参数传递 – 这就是使用如此多的参数调用函数的原因.

该文档还描述了如何调用目标函数:

f: callable
The model function, f(x, ...). It must take the independent variable as the first argument and the parameters to fit as separate remaining arguments.

xdata : An N-length sequence or an (k,N)-shaped array
for functions with k predictors. The independent variable where the data is measured.

您尝试使用来分隔因变量的参数,而它应该是一个参数数组.这是修复的代码:

def func(x, a, b, c):
    return a * np.exp(-b * (x[0] + x[1])) + c    

N = 50
x = np.linspace(0,4,50)
x = numpy.array([x, x])          # Combine your `x` and `y` to a single
                                 # (2, N)-array
z = func(x, 2.5, 1.3, 0.5)
zn = z + 0.2 * np.random.normal(size=x.shape[1])
popt, pcov = curve_fit(func, x, zn)
点赞