简体   繁体   English

使用 scipy 拟合 ODE 时如何修复此 TypeError?

[英]How can I fix this TypeError when fitting ODE with scipy?

I would like to adjust parameters of a simple ODE using the scipy package.我想使用scipy包调整简单 ODE 的参数。 I have the feeling that it is bearable.我有一种可以忍受的感觉。 I am aware about this post but I think my question is different.我知道这篇文章,但我认为我的问题是不同的。

First we import required packages:首先我们导入需要的包:

import numpy as np
from scipy import integrate, optimize

We define the ODE with a signature compliant to the new scipy.interpolate.solve_ivp method:我们使用符合新scipy.interpolate.solve_ivp方法的签名定义 ODE:

def GGM_ODE(t, C, r, p):
    return r*np.power(C, p)

We define the integrated ODE solution with a signature compliant to the classic scipy.optimize.curve_fit :我们使用符合经典scipy.optimize.curve_fit的签名定义集成 ODE 解决方案:

def GGM_sol(t, C, r, p):
    return integrate.solve_ivp(GGM_ODE, (t[0], t[-1]), [C], t_eval=t, args=(r, p))

We create a synthetic dataset by solving the IV problem for a given set of parameters:我们通过解决给定参数集的 IV 问题来创建一个合成数据集:

t = np.arange(0, 21)
sol = GGM_sol(t, 1, 0.5, 0.7)

This works perfectly.这完美地工作。

Finally, we try to adjust parameters by fitting the integrated solution:最后,我们尝试通过拟合集成解来调整参数:

popt, pcov = optimize.curve_fit(GGM_sol, t, sol.y)

Unfortunately, this last step fails with a cryptic error (at least cryptic to me because I haven't enough insight on how scipy is built):不幸的是,这最后一步失败了,出现了一个神秘的错误(至少对我来说是神秘的,因为我对scipy的构建方式没有足够的了解):

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-45-22b0c3097986> in <module>
----> 1 popt, pcov = optimize.curve_fit(GGM_sol, t, sol.y)

~\AppData\Local\Continuum\anaconda3\lib\site-packages\scipy\optimize\minpack.py in curve_fit(f, xdata, ydata, p0, sigma, absolute_sigma, check_finite, bounds, method, jac, **kwargs)
    761         # Remove full_output from kwargs, otherwise we're passing it in twice.
    762         return_full = kwargs.pop('full_output', False)
--> 763         res = leastsq(func, p0, Dfun=jac, full_output=1, **kwargs)
    764         popt, pcov, infodict, errmsg, ier = res
    765         ysize = len(infodict['fvec'])

~\AppData\Local\Continuum\anaconda3\lib\site-packages\scipy\optimize\minpack.py in leastsq(func, x0, args, Dfun, full_output, col_deriv, ftol, xtol, gtol, maxfev, epsfcn, factor, diag)
    386     if not isinstance(args, tuple):
    387         args = (args,)
--> 388     shape, dtype = _check_func('leastsq', 'func', func, x0, args, n)
    389     m = shape[0]
    390 

~\AppData\Local\Continuum\anaconda3\lib\site-packages\scipy\optimize\minpack.py in _check_func(checker, argname, thefunc, x0, args, numinputs, output_shape)
     24 def _check_func(checker, argname, thefunc, x0, args, numinputs,
     25                 output_shape=None):
---> 26     res = atleast_1d(thefunc(*((x0[:numinputs],) + args)))
     27     if (output_shape is not None) and (shape(res) != output_shape):
     28         if (output_shape[0] != 1):

~\AppData\Local\Continuum\anaconda3\lib\site-packages\scipy\optimize\minpack.py in func_wrapped(params)
    461     if transform is None:
    462         def func_wrapped(params):
--> 463             return func(xdata, *params) - ydata
    464     elif transform.ndim == 1:
    465         def func_wrapped(params):

TypeError: unsupported operand type(s) for -: 'OdeResult' and 'float'

I can see this error is classic TypeError about incompatible operands for the difference operator.我可以看到这个错误是关于差异运算符的不兼容操作数的经典TypeError It claims it cannot subtract a float to an OdeResult object.它声称它不能将float减去OdeResult对象。 It also only concerns optimize package not the integrate .它也只涉及optimize包而不是integrate

What I do not understand it is why I am getting this error.我不明白的是为什么我会收到这个错误。

What must I change in my function signature or function call to make curve_fit work?我必须在函数签名或函数调用中更改什么才能使curve_fit工作? Or is there something else I have missed?或者还有什么我错过的吗?

It is exactly as the error message says, solve_ivp returns a solution object which contains the solution data.正如错误消息所说,solve_ivp 返回一个包含解决方案数据的解决方案对象。 Try尝试

def GGM_sol(t, C, r, p):
    res = integrate.solve_ivp(GGM_ODE, (t[0], t[-1]), [C], t_eval=t, args=(r, p))
    return res.y[0]

to get only the solution values.仅获取解决方案值。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用scipy.optimize.minimize修正拟合条件 - How to fix fitting with scipy.optimize.minimize for derivation condition 尝试多进程时如何解决“ TypeError:无法序列化&#39;_io.BufferedReader&#39;对象”错误 - How can I fix “TypeError: cannot serialize '_io.BufferedReader' object” error when trying to multiprocess 如何修复 TypeError: &#39;NoneType&#39; 对象在使用 Flask 和 Sqlite3 时不可下标? - How can i fix TypeError: 'NoneType' object is not subscriptable when using flask and Sqlite3? 如何解决TypeError:计算字母时&#39;int&#39;对象不可迭代? - how can I fix this TypeError: 'int' object is not iterable when counting the alphabet? 使用 zip() 函数时如何修复以下错误? 类型错误:“列表”对象不可调用 - How can I fix the following error when using the zip() function? TypeError: 'list' object is not callable 如何在 Python 中修复数据类的 TypeError? - How can I fix the TypeError of my dataclass in Python? TypeError: 'Add' object 不可调用,我该如何解决? - TypeError: 'Add' object is not callable, How can I fix it? 求解ODE系统时,对scipy.integrate.ode使用自适应时间步长 - Using adaptive time step for scipy.integrate.ode when solving ODE systems 如何在Python的多维数据集中最大地分离n个点? 如何使用scipy.integrate.ode? - How do I maximally separate n points in a cube in Python? How do I use scipy.integrate.ode? 我该如何修复程序,无论我如何更改对象的类型,它始终显示TypeError? - How can I fix my program, it always show TypeError no matter how I change the type of the object?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM