Search code examples
pythonlmfit

Fit negative exponential model in LMFIT


How does lmfit's exponential model work when approximating a (negative) exponential function?

The following tried to follow https://lmfit.github.io/lmfit-py/model.html, but failed to provide the right results:

mod = lmfit.models.ExponentialModel()
pars = mod.guess([1, 0.5], x=[0, 1])
out = mod.fit([1, 0.5], pars, x=[0, 1])
out.eval(x=0) # result is 0.74999998273811308, should be 1
out.eval(x=1) # result is 0.75000001066995159, should be 0.5

Solution

  • You'll need more than two data points to fit the two-parameter exponential model to data. Lmfit Models are designed to do data fitting. Something like this will work:

    import numpy as np
    import lmfit
    
    xdat = np.linspace(0, 2.0, 11)
    ydat = 2.1 * np.exp(-xdat /0.88) + np.random.normal(size=len(xdat), scale=0.06)
    
    mod = lmfit.models.ExponentialModel()
    pars = mod.guess(ydat, x=xdat)
    out = mod.fit(ydat, pars, x=xdat)
    
    print(out.fit_report())
    

    Instead, you're getting amplitude = 0.75 and decay > 1e6.