Search code examples
python-3.xcurve-fittingnonlinear-optimizationlmfit

Fitting two variables using lmfit


How can I fit this function with two input variables using lmfit in python? function f(x) =a*(x - b)**2, a and b are variables and they can be a random number.


Solution

  • Can you try this?

    import matplotlib.pyplot as plt
    import numpy as np
    from lmfit.models import ExpressionModel
    
    # synthetic data
    x = np.linspace(-10, 10, 100)
    a,b = 0.9,1.9
    y = a*(x-b)**2
    
    # fit y using lmfit; with "guesses": a=1, b=2
    gmod = ExpressionModel("a*(x-b)**2")
    result = gmod.fit(y, x=x, a=1, b=2)
    
    print(result.fit_report())
    
    plt.plot(x, y, 'bo')
    plt.plot(x, result.init_fit, 'k--', label='initial fit')
    plt.plot(x, result.best_fit, 'r-', label='best fit')
    plt.legend(loc='best')
    plt.show()
    

    Output: enter image description here