lmfit ODE fitting error: different shape between residuals and data

lmfit ODE fitting error: different shape between residuals and data

所以我正在尝试使用 python 和库 lmfit 将一些电化学数据拟合到 Michaelis Menten 模型 (ODE) 中。我把配件的代码放在下面,它来自 Text:

的例子
from lmfit import minimize, Parameters, Parameter, report_fit
from scipy.integrate import odeint
df = pd.read_csv("example3.csv", header=None, nrows=300) 
data=df[2].values
t = time_x

def f(xs, t, ps):
    R=1
    try:
        alpha = ps['alpha'].value
        Vmax = ps['Vmax'].value
        Km=ps['Km'].value
    except:
        alpha, Vmax, Km = ps
    S = xs
    dsdt=R-alpha*(Vmax*S/(Km+S))
    return dsdt

def g(t, x0, ps):

    solution = odeint(f, x0, t, args=(ps,))
    return solution

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



# set parameters incluing bounds
parameters = Parameters()
parameters.add('x0', value=float(data[0]), min=0, max=100)
parameters.add('Vmax',value=18,min=0, max=100)
parameters.add('alpha',value=1,min=0, max=1)
parameters.add('Km',value=5,min=0,max=100)

# fit model and find predicted values
result = minimize(residual, parameters, args=(t, data), method='leastsq')
final = data + result.residual.reshape(data.shape)

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

# display fitted statistics
report_fit(result)

我收到以下错误:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-199-1bd65276a496> in <module>
     38 # fit model and find predicted values
     39 result = minimize(residual, parameters, args=(t, data), method='leastsq')
---> 40 final = data + result.residual.reshape(data.shape)
     41 
     42 # plot data and fitted curves

ValueError: cannot reshape array of size 90000 into shape (300,)

我知道这是什么意思,残差数组比数据大,无法重塑它。但从技术上讲,残差应该与数据大小相同。如果有人熟悉 lmfit 库,那将是一个巨大的帮助。我希望这是一个愚蠢的问题,我只是看不到错误。提前谢谢你。

您很可能遇到数组广播问题,odeint 的结果是一个列向量,数据被视为行,差异被广播为具有 300*300=90000 个元素的矩阵.

在某些地方缩小 odeint 结果的形状,例如

return solution[:,0]