我正在尝试将简单函数适合python中两个独立数据的数组。我知道我需要将独立变量的数据打包到一个数组中,但是当我尝试进行拟合时,传递变量的方式似乎仍然存在问题。 (之前有几篇与此相关的文章,但是并没有太大帮助。)
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
def fitFunc(x_3d, a, b, c, d):
return a + b*x_3d[0,:] + c*x_3d[1,:] + d*x_3d[0,:]*x_3d[1,:]
x_3d = np.array([[1,2,3],[4,5,6]])
p0 = [5.11, 3.9, 5.3, 2]
fitParams, fitCovariances = curve_fit(fitFunc, x_3d[:2,:], x_3d[2,:], p0)
print ' fit coefficients:\n', fitParams
我读到的错误,
raise TypeError('Improper input: N=%s must not exceed M=%s' % (n, m))
TypeError: Improper input: N=4 must not exceed M=3
M
的长度是多少? N
是p0
的长度吗?我在这里错了吗?
N和M在the help中定义了该功能。 N是数据点的数量,M是参数的数量。因此,您的错误基本上意味着您需要的参数至少要与数据点一样多,这是很合理的。
此代码对我有用:
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
def fitFunc(x, a, b, c, d):
return a + b*x[0] + c*x[1] + d*x[0]*x[1]
x_3d = np.array([[1,2,3,4,6],[4,5,6,7,8]])
p0 = [5.11, 3.9, 5.3, 2]
fitParams, fitCovariances = curve_fit(fitFunc, x_3d, x_3d[1,:], p0)
print ' fit coefficients:\n', fitParams
我提供了更多数据。我还更改了fitFunc
的形式,使其仅作为单个x的函数进行扫描-装配工将处理对所有数据点的调用。您发布的代码也引用了x_3d[2,:]
,这导致了错误。
默认curve_fit
方法需要用于拟合函数fitFunc
的参数比数据点少。我在安装一个总共需要15个参数的函数时遇到了同样的问题,而我只有13个数据点。解决方案是使用另一种方法(例如dogbox
或trf
)。