Prevent curve_fit from trying certain values

273 Views Asked by At

I'm trying to use Python's curve_fit to fit a function to some data.

I have a function

y = aln(bx + 1)

where a and b are constants to be found, y is the dependant variable and x is the dependant variable.

The data for x and y are given by xdata and ydata respectively.

So far I have the following code:

def func(x, a, b):
     return a * np.log(x * b + 1)

popt, pcov = curve_fit(func, xdata, ydata, maxfev = 5000)

However when running the code, I get the error:

RuntimeWarning: invalid value encountered in log return a * np.log(x * b + 1)

Which I believe is due to the fact that curve_fit is trying negative values inside the log.

How can I prevent curve_fit from trying negative numbers and throwing up the error? Is there another way to approach this?

1

There are 1 best solutions below

2
Guinther Kovalski On

if curve_fit iterates a single value each time just add a max() check:

 a * np.log(max(0,x * b + 1))

if it does it from a numpy array, you can change negative values with a boolean mask:

X = x * b + 1
boolean_mask = (x * b + 1)<0
X[boolean_mask] = 0