[英]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.