Fit A Differential Equation Using Scipy, Getting "object Too Deep For Desired Array"
Solution 1:
@hpaulj has pointed out the problem with the shape of the return value from logistic_solution
and shown that fixing that eliminates the error that you reported.
There is, however, another problem in the code. The problem does not generate an error, but it does result in an incorrect solution to your test problem (the logistic differential equation). By default, odeint
expects the t
argument of the function that computes the differential equations to be the second argument. Either change the order of the first two arguments of logistic_de
, or add the argument tfirst=True
to your call of odeint
. The second option is a bit nicer, because it will allow you to use logistic_de
with scipy.integrate.solve_ivp
if you decide to try that function instead of odeint
.
Solution 2:
A sample run of logistic_solution
produces a (18,1) result:
In [268]: logistic_solution(df_yeast['td'], *parsic)
Out[268]:
array([[ 1.00000000e+00],
[ 2.66666671e+00],
[ 4.33333337e+00],
[ 1.00000004e+00],
[-1.23333333e+01],
[-4.06666666e+01],
[-8.90000000e+01],
[-1.62333333e+02],
[-2.65666667e+02],
[-4.04000000e+02],
[-5.82333333e+02],
[-8.05666667e+02],
[-1.07900000e+03],
[-1.40733333e+03],
[-1.79566667e+03],
[-2.24900000e+03],
[-2.77233333e+03],
[-3.37066667e+03]])
In [269]: _.shape
Out[269]: (18, 1)
but the y
values is
In[281]: df_yeast['cd'].values.shapeOut[281]: (18,)
Define an alternative function that returns a 1d array:
In [282]: def foo(t,r,K):
...: return logistic_solution(t,r,K).ravel()
This works:
In [283]: params, _ = optim.curve_fit(foo, df_yeast['td'], df_yeast['cd'], p0=parsic)
In [284]: params
Out[284]: array([16.65599815, 15.52779946])
test the params
:
In [287]: logistic_solution(df_yeast['td'], *params)
Out[287]:
array([[ 1. ],
[ 8.97044688],
[ 31.45157847],
[ 66.2980814 ],
[111.36464226],
[164.50594767],
[223.5766842 ],
[286.43153847],
[350.92519706],
[414.91234658],
[476.24767362],
[532.78586477],
[582.38160664],
[622.88958582],
[652.1644889 ],
[668.0610025 ],
[668.43381319],
[651.13760758]])
In [288]: df_yeast['cd'].values
Out[288]:
array([ 9.6, 18.3, 29. , 47.2, 71.1, 119.1, 174.6, 257.3, 350.7,
441. , 513.3, 559.7, 594.8, 629.4, 640.8, 651.1, 655.9, 659.6])
too deep
in this context means a 2d array, when it should be 1d, in order to compare with ydata
ydata : array_like
The dependent data, a length M array - nominally ``f(xdata, ...)``.
Post a Comment for "Fit A Differential Equation Using Scipy, Getting "object Too Deep For Desired Array""