python多变量非线性拟合_scipy的多变量非线性curve_fit

I have been trying to use scipy.optimize curve_fit using multiple variables. It works fine with the test code I created but when I try to implement this on my actual data I keep getting the following error

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

The shape of the arrays and the data types of their elements in my test code and actual code are exactly the same so I am confused as to why I get this error.

Test code:

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)

Actual code:

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)

EDIT

Here is the full error message

Traceback (most recent call last):

File "DCM_03.py", line 46, in

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

解决方案

I figured out the issue. The problem for some reason was the use of math.exp and cmath.exp in the fitting function func. In place of these functions I used np.exp(). I am not completely sure the reason why though.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值