尝试使用 curve_fit - 错误:'numpy.float64' 类型的对象没有 len()

问题描述

这是我遇到问题的代码

B_mags = [12.113,7.508,2.880]
N_b = [565.4,39521,3075076.7]
V_mags = [11.326,6.404,2.869]
N_v = [1190,43511.3,2933500] 

def linear(N,A):
    return A*np.log10(N) # This is equation (4.1) in a form such that curve_fit can be applied to estimate A.

# Finding A using curve_fit:

for (a,b,c,d) in zip(V_mags,N_v,B_mags,N_b):
    print(a,d)
    Nratio = b/d
    popt,pocov = curve_fit(linear,Nratio,(a-c),p0=[-2.5])

基本上,我正在尝试使用 curve_fit 在以下等式中找到系数 A 的估计值:

enter image description here

我将其视为线性曲线(在对数域上)并使用曲线拟合对其进行拟合,其中我的 y 变量是 (m_1-m_2),我的 x 变量是 Nratio = N_1/N_2。

>

当我尝试通过curve_fi运行它时,出现以下错误

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-13-9ecbf5ef33e3> in <module>
     12     print(a,d)
     13     Nratio = b/d
---> 14     popt,p0=[-2.5])

/local/environments/default/default-venv/lib64/python3.8/site-packages/scipy/optimize/minpack.py in curve_fit(f,xdata,ydata,p0,sigma,absolute_sigma,check_finite,bounds,method,jac,**kwargs)
    784         res = leastsq(func,Dfun=jac,full_output=1,**kwargs)
    785         popt,pcov,infodict,errmsg,ier = res
--> 786         ysize = len(infodict['fvec'])
    787         cost = np.sum(infodict['fvec'] ** 2)
    788         if ier not in [1,2,3,4]:

TypeError: object of type 'numpy.float64' has no len()

提前致谢。

解决方法

这不是曲线拟合问题。要进行曲线拟合,您有一个自变量和一个因变量。那些在哪里?你的方程真的是 A(未知数)=(m1-m2)/log10(N1/N2)。这很好,但是您不能真正拥有具有 4 个自变量的曲线。这将是一个 5 维的表面。 ;)

以下是 A 的值:

def A(dm,Nr):
    return dm / math.log10(Nr)

for (a,b,c,d) in zip(V_mags,N_v,B_mags,N_b):
    Nratio = b/d
    print( a,d,A((a-c),Nratio) )

结果如下:

11.326 1190 12.113 565.4 -2.4350913766428923
6.404 43511.3 7.508 39521 -26.42783688627219
2.869 2933500 2.88 3075076.7 0.5373754369759042

那么A在这里依赖什么?你反对什么“弯曲”A?我们在转动哪个旋钮?