问题
If I have a function that the independent variable is the upper limit of an definite integral of a mathematical model. This mathematical model has the parameters I want to do regression. This mathematical model is nonlinear and can be complicated.
How can I solve this?
if the output of my function is then be processed, can it be curve_fit?
There is a simplified case
import scipy.optimize as sp
from scipy.integrate import quad
import numpy as np
number = 100
def f(x,a,b,c):
return 500*a*x+b*c
def curvefit(d,a,b,c):
return quad(f,0,d,args=(a,b,c))[0]
x_linear = np.linspace(0.001,0.006,number)
y_linear = 23.33*x_linear + 0.02*(np.random.random(number)-0.5)
parameter = sp.curve_fit(curvefit,x_linear,y_linear)
x and y _linear are number I made up.
d in curvefit() is now x_linear that is a list, and is the upper limit in quad().
The error shows ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
I know quad() requires upper limit to be float.
回答1:
The error is raised inside the function scipy.integrate.quad
because d is a numpy.array
and not a scalar. The function given to scipy.optimize.curve_fit
take the independent variable (x_linear
in your case) as first argument.
The quick and dirty fix is to modify curvefit to compute the definite integral for each value in d:
def curvefit(xs,a,b,c):
return [quad(f,0,x,args=(a,b,c))[0] for x in xs]
来源:https://stackoverflow.com/questions/49526859/scipy-optimize-curve-fit-a-definite-integral-function-with-scipy-integrate-quad