【问题标题】:Numdifftools to calculate lmfit fit uncertaintiesNumdifftools 计算 lmfit 拟合不确定性
【发布时间】:2019-07-17 10:28:20
【问题描述】:

我正在使用 lmfit 来估计耦合 ODE 系统的参数,基于以下示例:https://people.duke.edu/~ccc14/sta-663/CalibratingODEs.html
为了获得残差的全局最小值,我转而使用“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 解决了这个问题。

【问题讨论】:

    标签: python ode data-fitting lmfit


    【解决方案1】:

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

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

    【讨论】:

    • ... 但您没有提供 lmfit 或 numdifftools 的版本或您获得的完整输出。 ;) 你的例子对我有用(lmfit 0.9.13,numdifftools 0.9.39,python 3.7.3)。 FWIW,我建议先尝试method='leastsq'——它应该让你非常接近,函数调用减少了 4000 倍。 method='ampgo' 也可用作全局优化器。
    • 它也适用于我。我认为没有检测到 numdifftools 的安装,这就是它一直要求安装它的原因。无论如何感谢您的帮助和其他优化器
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-23
    • 1970-01-01
    • 2018-10-20
    相关资源
    最近更新 更多