多变量非线性 curve_fit 和 scipy

multivariable non-linear curve_fit with scipy

我一直在尝试使用 scipy.optimize curve_fit 使用多个变量。它适用于我创建的测试代码,但是当我尝试在我的实际数据上实现它时,我不断收到以下错误

TypeError: only arrays length -1 can be converted to python scalars

我的测试代码和实际代码中数组的形状及其元素的数据类型完全相同,所以我很困惑为什么会出现此错误。

测试代码:

    import numpy as np 
    import scipy 
    from scipy.optimize import curve_fit

    def func(x,a,b,c):
          return a+b*x[0]**2+c*x[1]
    x_0=np.array([1,2,3,4])
    x_1=np.array([5,6,7,8])
    X=scipy.array([x_0,x_1])
    Y=func(X,3.1,2.2,2.1)
    popt, pcov=curve_fit(func,X,Y)

实际代码:

    f=open("Exp_Fresnal.csv", 'rb')
    reader=csv.reader(f)
    for row in reader:
         Qz.append(row[0])
         Ref.append(row[1])
         Ref_F.append(row[2])
    Qz_arr,Ref_Farr=scipy.array((Qz)),scipy.array((Ref_F))
    x=scipy.array([Qz_arr,Ref_Farr]

    def func(x,d,sig_int,sig_cp):
         return x[1]*(x[0]*d*(math.exp((-sig_int**2)*(x[0]**2)/2)/(1-cmath.exp(complex(0,1)*x[0]*d)*math.exp((-sig_cp**2)*(x[0]**2)/2))))**2

    Y=scipy.array((Ref))
    popt, pcov=curve_fit(func,x,Y)

编辑 这是完整的错误信息

Traceback (most recent call last): File "DCM_03.py", line 46, in <module> popt, pcov=curve_fit(func,x,Y) File "//anaconda/lib/python2.7/site-packages/scipy/optimize/minpack.py", line 651, in curve_fit res = leastsq(func, p0, args=args, full_output=1, **kwargs) File "//anaconda/lib/python2.7/site-packages/scipy/optimize/minpack.py", line 377, in leastsq shape, dtype = _check_func('leastsq', 'func', func, x0, args, n) File "//anaconda/lib/python2.7/site-packages/scipy/optimize/minpack.py", line 26, in _check_func res = atleast_1d(thefunc(*((x0[:numinputs],) + args))) File "//anaconda/lib/python2.7/site-packages/scipy/optimize/minpack.py", line 453, in _general_function return function(xdata, *params) - ydata File "DCM_03.py", line 40, in func return (0.062/(2*x))**4*(x*d*(math.exp((-sig_int**2)*(x**2)/2)/(1-cmath.exp(complex(0,1)*x*d)*math.exp((-sig_cp**2)*(x**2)/2))))**2 TypeError: only length-1 arrays can be converted to Python scalars

我想通了这个问题。由于某种原因,问题是在拟合函数 func 中使用了 math.expcmath.exp。我使用 np.exp() 代替这些函数。我不完全确定原因。