Am trying to approximate the function using the curve_fit: here are the code below.
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
and zdata
are set as df['y'].values
, df['z'].values
respectively from csv file that I imported. FYI, df['y'].values
range from 0.01 to 0.9. Has no problem with trying with other function approximation like exponential or polynomial.
I keep getting this error:
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
I don't understand why I am keep getting this error.
I tried to refer to some other method for debugging purpose. so tried:
def rsk_alpha_function(x,a,b,c):
print(x)
return [a*math.sqrt(x_i - b) + c for x_i in i]
But this time I would get error: math domain error
So I tried to ignore the case where x_i - b is negative, where
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`
This time I would get
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'
I think the initial error is somehow solved by following the link's method?(if not please tell me) but I can't get why these other errors are keep happening.
You need to work with a vectorized function, replace math.sqrt
by np.sqrt
the numpy equivalent.
import numpy as np
def rsk_alpha_function(x,a,b,c):
return a* np.sqrt(x - b) + c