Fitting data with integral function

后端 未结 2 1029
时光取名叫无心
时光取名叫无心 2021-02-04 11:44

When using curve_fit from scipy.optimize to fit a some data in python, one first defines the fitting function (e.g. a 2nd order polynomial) as follows:

  1. def f
2条回答
  •  广开言路
    2021-02-04 12:07

    Sometimes you can be lucky and you're able to evaluate the integral analytically. In the following example the product of h(t)=exp(-(t-x)**2/2) and a second degree polynomial g(t) is integrated from 0 to infinity. Sympy is used to evaluate the Integral and generate a function usable for curve_fit():

    import sympy as sy
    sy.init_printing()  # LaTeX-like pretty printing of IPython
    
    
    t, x = sy.symbols("t, x", real=True)
    
    h = sy.exp(-(t-x)**2/2)
    
    a0, a1, a2 = sy.symbols('a:3', real=True)  # unknown coefficients
    g = a0 + a1*t + a2*t**2
    
    gh = (g*h).simplify()  # the intgrand
    G = sy.integrate(gh, (t, 0, sy.oo)).simplify()  # integrate from 0 to infinty
    
    # Generate numeric function to be usable by curve_fit()
    G_opt = sy.lambdify((x, t, a0, a1, a2), G)
    
    print(G_opt(1, 2, 3, 4, 5))  # example usage
    

    Note that in general the problem is often ill-posed since the integral does not neccesarily converge in a large enough neighborhood of the solution (which is assumed by curve_fit()).

提交回复
热议问题