JohnDoe122
JohnDoe122

Reputation: 688

Fitting function with multiple outputs Python

I have a function of the form (y1,y2) = x*(a1,a2)+(b,b), where x, y1 and y2 are measured values and a1,a2 and b are the parameters I fit for. How can I do this in python? I tried using curve_fit like this:

x = np.array([1,2,3,4,5])
y = []
for i in range(len(x)):
    y = y + [[1.2*x[i]+2,-2.2*x[i]+2]]
y = np.array(y)

def f(x,a,b,c):
    return np.transpose(np.array([a*x+c,b*x+c]))

curve_fit(f,x,y)

but I am getting this error:

Result from function call is not a proper array of floats.

Upvotes: 1

Views: 448

Answers (1)

99_m4n
99_m4n

Reputation: 1265

You get the error because your function hast to return the value for y as a float and not as list. With your code the y variable is an array of lists and not an array of floats. You have to separate y1 and y2 and call curve_fit for each y.

With the following code you can get the curve_fit for y1 and y2 independently for the equation (y1,y2) = x*(a1,a2)+(b,b):

x = np.array([1,2,3,4,5])
y1 = []
for i in range(len(x)):
    y1.append(1.2*x[i]+2)
y1 = np.array(y1)

y2 = []
for i in range(len(x)):
    y2.append(-2.2*x[i]+2)
y2 = np.array(y2)

To ensure that the parameter b is the same for both y, you can define two separate functions replacing b in the second one with the result of curve_fit from the first one:

def f1(x,a,b):
    return a*x+b

def f2(x,a):
    return a*x+curve_fit(f1,x,y1)[0][1]  # here replace b for curve_fit(f1,x,y1)[0][1]

output:

>>> print(curve_fit(f1,x,y1))  # results for y1 ([a1, b])

(array([1.2, 2. ]), array([[ 1.31476816e-31, -3.94430449e-31],
       [-3.94430449e-31,  1.44624498e-30]]))

>>> print(curve_fit(f2,x,y2))  # results for y2 ([a2])

(array([-2.2]), array([[5.37859713e-33]]))

Note: You can run the script 2 times exchanging the functions (take the 2nd eq. first and then the first one) and see if the value of b2 is similar to b1 the first time you ran the script. If both are similar you can calculate the mean ((b1+b2)/2) and it would be your optimized b. If both values of b are not similar it means either there is no value for b in R (real numbers) or there are multiple values for b that satisfy both equations.

Upvotes: 1

Related Questions