2

I was adopting lmfit to do a curve fitting and use that fitted model to do prediction. However, the following code did not achieve what I want. Could you please help? Thanks.

import numpy as np
from lmfit import Model

def linearModel(x, a0, a1):
    return a0+a1*x

#main code begin here
X=[1,2,4]  # data for fitting
y=[2,4,6]  # data for fitting
gmodel = Model(linearModel)  #select model      
params = gmodel.make_params(a0=1, a1=1) # initial params
result = gmodel.fit(y, params, x=X) # curve fitting
x1=[1, 2, 3] # input for prediction
a=result.eval(x)   # prediction
Mr. T
  • 11,960
  • 10
  • 32
  • 54
Shu Pan
  • 185
  • 2
  • 10
  • So, what did you want to achieve? Please provide a [Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve) This includes input, expected output, and real output. – Mr. T May 28 '18 at 23:44

1 Answers1

4

It is always a good idea to include the code you actually ran, the result you got, and the result you expected.

Here, the main problem is that you have a syntax error. Second, you should use numpy arrays, not lists. And third, as the docs show (see https://lmfit.github.io/lmfit-py/model.html#lmfit.model.ModelResult.eval) result.eval() would take params as the first argument, not the independent variable. In short, you want to replace your last two lines with

x1 = np.array([1, 2, 3]) # input for prediction
a = result.eval(x=x1)   # prediction

that should work as expected.

And: of course, you don't need lmfit to do a linear regression. ;).

M Newville
  • 7,486
  • 2
  • 16
  • 29