Search code examples
functionparametersscipyleast-squares

Get Variables in SciPy LeastSq to use them


I need to get fitting result for each parameter created in each least_sq run. Can anyone guide me on Parameter names inferred from the function arguments in the SciPy LeastSq??


Solution

  • ** Good news! using the lmfit such a wonderful package!**

    from scipy.optimize import least_squares
    from matplotlib.pylab import plt
    import numpy as np
    from numpy import exp, linspace, random
    from lmfit import Model
    
    
    def gaussian(x, amp, cen, wid):
        return amp * np.exp(-(x-cen)**2 / wid)
    
    
    x = linspace(-10, 10, 101)
    y = gaussian(x, 2.33, 0.21, 1.51) + random.normal(0, 0.2, len(x))
    
    gmodel = Model(gaussian)
    params = gmodel.make_params()
    print('parameter names: {}'.format(gmodel.param_names))
    print('independent variables: {}'.format(gmodel.independent_vars))
    result = gmodel.fit(y, params, x=x, amp=5, cen=5, wid=1)
    print(result.fit_report())
    [n many cases we might want to extract parameters and standard error estimates programatically rather than by reading the fit report][1]