JohnDoe122
JohnDoe122

Reputation: 688

Can't get the fit with lmfit

I want to do a fit using lmfit but I am having some issues. Here is my code:

from lmfit import Model
import numpy as np

def fit_func(x,a,b,c):
    return a*(b-x)**(5/8)+c

x = np.array([ 131.871     ,  218.825     ,  305.046     ,  390.533     ,
        475.128     ,  558.959     ,  642.001     ,  724.307     ,
        805.794     ,  886.422     ,  966.20900001, 1045.19300001,
       1123.39300001, 1200.75800001, 1277.23700001, 1352.83300001,
       1427.57800001, 1501.49800001, 1574.55300001, 1646.69500001,
       1717.90800001, 1788.22100001, 1857.65100001, 1926.18300001,
       1993.76400001, 2060.37000001, 2126.00900001, 2190.70600001,
       2254.44800001, 2317.20000001, 2378.92000001, 2439.60300001,
       2499.25800001, 2557.89000001, 2615.46600001, 2671.95000001,
       2727.30900001, 2781.54300001, 2834.64700001, 2886.60600001,
       2937.38000001, 2986.92900001])

y = np.array([  0.        ,   3.14159265,   6.28318531,   9.42477796,
        12.56637061,  15.70796327,  18.84955592,  21.99114858,
        25.13274123,  28.27433388,  31.41592654,  34.55751919,
        37.69911184,  40.8407045 ,  43.98229715,  47.1238898 ,
        50.26548246,  53.40707511,  56.54866776,  59.69026042,
        62.83185307,  65.97344573,  69.11503838,  72.25663103,
        75.39822369,  78.53981634,  81.68140899,  84.82300165,
        87.9645943 ,  91.10618695,  94.24777961,  97.38937226,
       100.53096491, 103.67255757, 106.81415022, 109.95574288,
       113.09733553, 116.23892818, 119.38052084, 122.52211349,
       125.66370614, 128.8052988 ])


fit_model = Model(fit_func)
params = fit_model.make_params()
params['b'].set(5000, min=3500)

result = fit_model.fit(y, x=x)

But I am getting this error:

ValueError: The model function generated NaN values and the fit aborted! Please check your model function and/or set boundaries on parameters where applicable. In cases like this, using "nan_policy='omit'" will probably not work.

What am I doing wrong? I tried to adjust the a, b, c parameters by hand and a=-1.2, b=3600, c=196 give a pretty good fit, so the program should be able to find something similar to that.

Upvotes: 0

Views: 963

Answers (1)

M Newville
M Newville

Reputation: 7862

Two things are missing:

a) you need to pass params to fit_model.fit() as with

result = fit_model.fit(y, params, x=x)

b) you need to give initial values for all parameters. Un-initialized parameters will have a value of -np.inf, which is deliberately chosen because it will throw such errors.

You say you know reasonable values for a, b, and c. Use that knowledge! Something like

fit_model = Model(fit_func)
params = fit_model.make_params(a=-1, b=4000, c=200)
params['b'].min = x.max() * (1.000001) # prevent (negative number)**fraction

result = fit_model.fit(y, params, x=x)
print(result.fit_report())

should work.

Upvotes: 1

Related Questions