我尝试使用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)
ydata
和zdata
分别从我导入的csv文件设置为df['y'].values
,df['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'
我认为最初的错误是以某种方式解决以下链接的方法?(如果不是,请告诉我),但我不明白为什么这些其他错误不断发生。
1条答案
按热度按时间f0brbegy1#
你需要使用一个向量化的函数,将
math.sqrt
替换为np.sqrt
(numpy等价物)。