scipy.optimize.curve_fit a definite integral function with scipy.integrate.quad

久未见 提交于 2020-01-14 07:04:13

问题


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.

  1. How can I solve this?

  2. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!