scipy 近似函数时,curve_fit minimize期间的错误

ifsvaxew  于 2023-05-29  发布在  其他
关注(0)|答案(1)|浏览(142)

我尝试使用curve_fit来近似函数:下面是代码。

def rsk_alpha_function(x,a,b,c):
    return a* math.sqrt(x - b) + c
popt, pcov = curve_fit(risk_alpha_function, ydata, zdata, maxfev = 5000)

ydatazdata分别从我导入的csv文件设置为df['y'].valuesdf['z'].values。仅供参考,df['y'].values的范围为0.01至0.9。尝试其他函数逼近(如指数或多项式)没有问题。
我一直得到这个错误:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Users\Miniconda3\lib\site-packages\scipy\optimize\_minpack_py.py", line 859, in curve_fit     
    res = leastsq(func, p0, Dfun=jac, full_output=1, **kwargs)
  File "C:\Users\Miniconda3\lib\site-packages\scipy\optimize\_minpack_py.py", line 413, in leastsq       
    shape, dtype = _check_func('leastsq', 'func', func, x0, args, n)
  File "C:\Users\Miniconda3\lib\site-packages\scipy\optimize\_minpack_py.py", line 26, in _check_func    
    res = atleast_1d(thefunc(*((x0[:numinputs],) + args)))
  File "C:\Users\Miniconda3\lib\site-packages\scipy\optimize\_minpack_py.py", line 501, in func_wrapped  
    return func(xdata, *params) - ydata
  File "<stdin>", line 2, in risk_lambda_function
TypeError: only size-1 arrays can be converted to Python scalars

我不明白为什么我一直得到这个错误。
我试着引用一些other method用于调试目的。所以尝试:

def rsk_alpha_function(x,a,b,c):
    print(x)
return [a*math.sqrt(x_i - b) + c for x_i in i]

但这一次我会得到错误:数学域错误
所以我试图忽略x_i - B为负的情况,其中

def rsk_alpha_function(x,a,b,c):
        for x_i in x:
        if x_i - b < 0:
            continue
        else:
            return a* math.sqrt(x - b) + c`

这次我会得到

File "<stdin>", line 1, in <module>
  File "C:\Users\Miniconda3\lib\site-packages\scipy\optimize\_minpack_py.py", line 859, in curve_fit     
    res = leastsq(func, p0, Dfun=jac, full_output=1, **kwargs)
  File "C:\Users\Miniconda3\lib\site-packages\scipy\optimize\_minpack_py.py", line 413, in leastsq       
    shape, dtype = _check_func('leastsq', 'func', func, x0, args, n)
  File "C:\Users\Miniconda3\lib\site-packages\scipy\optimize\_minpack_py.py", line 26, in _check_func    
    res = atleast_1d(thefunc(*((x0[:numinputs],) + args)))
  File "C:\Users\Miniconda3\lib\site-packages\scipy\optimize\_minpack_py.py", line 501, in func_wrapped  
    return func(xdata, *params) - ydata
TypeError: unsupported operand type(s) for -: 'NoneType' and 'float'

我认为最初的错误是以某种方式解决以下链接的方法?(如果不是,请告诉我),但我不明白为什么这些其他错误不断发生。

f0brbegy

f0brbegy1#

你需要使用一个向量化的函数,将math.sqrt替换为np.sqrt(numpy等价物)。

import numpy as np

def rsk_alpha_function(x,a,b,c):
    return a* np.sqrt(x - b) + c

相关问题