Numdifftools计算lmfit拟合不确定性

时间:2019-07-17 10:28:20

标签: python ode data-fitting lmfit

基于示例https://people.duke.edu/~ccc14/sta-663/CalibratingODEs.html,我正在使用lmfit来估计耦合ODE系统的参数。
为了获得残差的全局最小值,我切换为使用“ basinhopping”或“ ampgo”方法,但是在显示结果时会收到这样的警告:

Warning: uncertainties could not be estimated:
this fitting method does not natively calculate uncertainties
and numdifftools is not installed for lmfit to do this.  Use
`pip install numdifftools` for lmfit to estimate uncertainties
with this fitting method.

我已经通过conda安装了“ numdifftools”,但警告(以及缺乏不确定性)仍然存在。
我该如何解决?

以下是数据最少的代码:

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from lmfit import minimize, Parameters, Parameter, report_fit
from scipy.integrate import odeint

def f(xs, t, ps):

    Ksor = ps['Ksor'].value
    Kdes = ps['Kdes'].value

    Cw, Cs, SS = xs

    return [-Ksor*SS*Cw+Kdes*Cs, Ksor*SS*Cw-Kdes*Cs,0]

def g(t, x0, ps):
    """
    Solution to the ODE x'(t) = f(t,x,k) with initial condition x(0) = x0
    """
    x = odeint(f, x0, t, args=(ps,))
    return x

def residual(ps, ts, data):
    x0 = ps['Cw0'].value, ps['Cs0'].value, ps['SS0'].value
    model = g(ts, x0, ps)
    return (model - data).ravel()

data1=np.array([[100.    ,   0.    ,   1.    ],
   [ 66.5507,  33.4493,   1.    ],
   [ 44.4018,  55.5982,   1.    ],
   [ 29.7357,  70.2643,   1.    ]])

t = pd.Series([0.408,0.816,1.224,1.632])
x0 = np.array([100,0,1])

# set parameters incluing bounds
params = Parameters()
params.add('Cw0', value=100, vary=False)
params.add('Cs0', value=0, vary=False)
params.add('SS0', value=1, vary=False)
params.add('Ksor', value=2.0, min=0, max=100)
params.add('Kdes', value=1.0, min=0, max=100)


# fit model and find predicted values
result = minimize(residual, params, args=(t, data1), method='basinhopping')
final = data1 + result.residual.reshape(data1.shape)

# plot data and fitted curves
plt.plot(t, data1, 'o')
plt.plot(t, final, '-', linewidth=2);

# display fitted statistics
report_fit(result)

编辑:代码有效。我认为未检测到numdifftools的安装,并且重新启动PC即可解决问题。

1 个答案:

答案 0 :(得分:0)

提供一个最小但完整的示例来显示问题和结果(包括拟合报告和/或任何异常)总是有帮助的。请修改问题以包括这些,并提供您正在使用的lmfit和numdifftools的版本。

另外:使用numdifftools计算不确定性要求残差数组的长度大于变量的数量。