如何正确定义向量函数以供scipy的curve_fit使用

3

我有一个问题,关于Python在尝试曲线拟合时如何计算形式为(f1(x),f2(x))的向量函数数组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:operands could not be broadcast together with shapes(2,4)(4,2)”的错误。 将要拟合的数据转置:

ydata=np.array([[1,2],[3,4],[5,6],[7,8]],dtype=float).transpose()

因为现在我拥有的函数值比参数少,所以会报“TypeError: Improper input: N=3 must not exceed M=2”的错误。好的,我知道为什么无法适配它了。因此,我需要转置函数值:

def func(x,a,b,c):
    return np.array([a*x**b+c,a*x**b+c+1]).transpose()

这个错误提示是“函数调用结果不是一个合适的浮点数数组”。

如何解决这个问题?从数学上讲,如果数据可以匹配模型,那么结果应该是确定的。


相关问题 - Stelios
你可能也会对我在这里的回答感兴趣:https://dev59.com/wZzha4cB1Zd3GeqPLdtn#40961491 - tBuLi
1个回答

3

curve_fit 期望一个返回1D数组的 func,因此 output 应该被展平。在这种情况下,您应该将 ydata.T.ravel() 提供给 curve_fit ,以便其顺序与 func(x,a,b,c) 的元素正确对应。

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.]]

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接