How do I put a constraint on SciPy curve fit?

前端 未结 5 1984
旧巷少年郎
旧巷少年郎 2020-11-30 10:11

I\'m trying to fit the distribution of some experimental values with a custom probability density function. Obviously, the integral of the resulting function should always b

5条回答
  •  执笔经年
    2020-11-30 10:37

    You could ensure that your fitted probability distribution is normalised via a numerical integration. For example, assuming that you have data x and y and that you have defined an unnormalised_function(x, a, b) with parameters a and b for your probability distribution, which is defined on the interval x1 to x2 (which could be infinite):

    from scipy.optimize import curve_fit
    from scipy.integrate import quad
    
    # Define a numerically normalised function
    def normalised_function(x, a, b):
        normalisation, _ = quad(lambda x: unnormalised_function(x, a, b), x1, x2)
        return unnormalised_function(x, a, b)/normalisation
    
    # Do the parameter fitting
    fitted_parameters, _ = curve_fit(normalised_function, x, y)
    

提交回复
热议问题