我有一个问题,在尝试曲线拟合时,python 如何计算 x 数组的 (f1(x),f2(x)) 形式的向量函数。
import numpy as np
from scipy.optimize import curve_fit
def func(x,a,b,c):
return np.array([a*x**b+c,a*x**b+c+1])
ydata = np.array([[1,2],[3,4],[5,6],[7,8]],dtype=float)
xdata=np.array([1,2,3,4], dtype=float)
popt,pcov = curve_fit(func, xdata, ydata)
给出“ValueError:操作数无法与形状 (2,4) (4,2) 一起广播” 转置要拟合的数据:
ydata=np.array([[1,2],[3,4],[5,6],[7,8]],dtype=float).transpose()
给出“TypeError: 不正确的输入:N=3 不能超过 M=2”,因为现在我的函数值比参数少。好的,我知道为什么我不能适应那个。所以我需要转置函数值:
def func(x,a,b,c):
return np.array([a*x**b+c,a*x**b+c+1]).transpose()
这给了我“函数调用的结果不是正确的 float 组。”
如何从这样的问题中得到解决方案?从数学上讲,应该很好地确定数据是否可以拟合模型。
最佳答案
curve_fit
需要一个返回一维数组的 func
,因此 output
应该是平展的。在这种情况下,您应该将 ydata.T.ravel()
馈送到 curve_fit
以获得作为 func(x,a,b,三)
。
import numpy as np
from scipy.optimize import curve_fit
def func(x,a,b,c):
output = np.array([a*(x**b)+c,a*(x**b)+c+1])
return output.ravel()
ydata = np.array([[1,2],[3,4],[5,6],[7,8]],dtype=float)
xdata=np.array([1,2,3,4], dtype=float)
popt,pcov = curve_fit(func, xdata, ydata.T.ravel())
# print (popt)
# [ 2., 1., -1.]
测试结果,
func(xdata,*popt).reshape(-1,len(xdata)).T
# [[ 1., 2.],
# [ 3., 4.],
# [ 5., 6.],
# [ 7., 8.]]
关于python - 如何为 scipy 的 curve_fit 正确定义向量函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41306732/