Scipy optimize.curve_fit cannot match a function whose return value depends on the conditional

I want to fine-tune a function defined as follows for given time series:

def func(t, a0, a1, a2, T, tau1, tau2): if t < T: return a0 + a1 * np.exp(-t/tau1) + a2 * np.exp(-t/tau2) else: return a0 + a1 * np.exp(-T/tau1) * (1 - t/tau1 + T/tau1) + a2 * np.exp(-T/tau2) * (1 - t/tau2 + T/tau2) 

Here t represents the time at which the measurement is made, and the remaining arguments are the parameters of the function. The problem is that when I feed it in curve_fit, Python complains about the ambiguity at t <T. I believe this happens because t becomes a list of data points when func is called inside curve_fit, while T is a number (not list):

 popt, pcov = curve_fit(func, t1, d1) 

where t1 is the list of times, and d1 is the list of data values ​​measured at the corresponding time instants. I tried several ways to get around this problem, but to no avail. Any suggestion? Thank you very much!

+4
source share
1 answer

That's right, t < T is a Boolean array. NumPy refuses to assign true value to logical arrays because there are many possible options - should it be True if all elements are True or if any element is True?

But it's good. In this case, NumPy provides an excellent function for replacing if ... else ... blocks, namely np.where :

 def func(t, a0, a1, a2, T, tau1, tau2): return np.where( t < T, a0 + a1 * np.exp(-t/tau1) + a2 * np.exp(-t/tau2), a0 + a1 * np.exp(-T/tau1) * (1 - t/tau1 + T/tau1) + a2 * np.exp(-T/tau2) * (1 - t/tau2 + T/tau2) ) 
+5
source

Source: https://habr.com/ru/post/1445132/


All Articles