问题描述
我正在采用 lmfit
进行曲线拟合,并使用该拟合模型进行预测.但是,以下代码无法实现我想要的.能否请你帮忙?谢谢.
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
推荐答案
包括您实际运行的代码,获得的结果以及预期的结果总是一个好主意.
It is always a good idea to include the code you actually ran, the result you got, and the result you expected.
这里,主要问题是您遇到语法错误.其次,您应该使用numpy数组,而不是列表.第三,如文档所示(请参见 https://lmfit.github.io/lmfit-py/model.html#lmfit.model.ModelResult.eval ) result.eval()
将采用 params
作为第一个参数,不是自变量.简而言之,您想将最后两行替换为
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
应该可以正常工作.
并且:当然,您不需要 lmfit
即可进行线性回归.;).
And: of course, you don't need lmfit
to do a linear regression. ;).
这篇关于lmfit模型拟合,然后进行预测的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!