我正在试着用一个微分方程来拟合少量的测量值。我在solve_ivp中遇到了需要初始状态的问题,我不得不将其定义为静态值。这个问题可以在下面的图片中看到。每次拟合被强制通过第一个测量点时,一些调整将提供更好的拟合。

有没有办法让初始状态y0在curve_fit使用的fitfunc中变得灵活
我可以求解微分方程,只使用curve_fit,但我更喜欢将它保留在我的代码中。以防将来我有更复杂的微分方程,这些微分方程不能用一般的方法解决。
import scipy.optimize as scopt
import scipy.integrate as scint
def Tdot(t, T, h, X):
Tdot = -(T - T_inf)*((h*A)/(rho*c*V))
return Tdot
def do_fit(D, d):
x_data = D.loc[:, 't'].values
y_data = D.loc[:, 'T'].values
def fitfunc(t, h):
y0 = y_data[0]
# Solve differential equation
sol = scint.solve_ivp(Tdot, [0, np.max(x_data)], [y0],
args = (h, 0),
t_eval = x_data, max_step=1e-3)
return sol.y.flatten()
# Fit equation to measurements
h_fit, kcov = scopt.curve_fit(fitfunc, x_data, y_data, p0=200)
# Limits and values for plotted fit
tfit = np.linspace(0, D.t.round(1).max())
fit = scint.solve_ivp(Tdot, [0, np.max(tfit)], [y_data[0]], max_step=1e-3, args=(h_fit, 0))
return fit, h_fit发布于 2020-09-10 17:28:10
想出了解决方案。将初始值添加到我的拟合函数中,并修改数据计算以进行匹配。
从def fitfunc(t, h)到def fitfunc(t, h, y0),
h_fit, kcov = scopt.curve_fit(fitfunc, x_data, y_data, p0=200) to
popt, _ = scopt.curve_fit(fitfunc, x_data, y_data)
和
fit = scint.solve_ivp(Tdot, [0, np.max(tfit)], [y_data[0]], max_step=1e-3, args=(h_fit, 0)) to
fit = scint.solve_ivp(Tdot, [0, np.max(tfit)], [popt[1]], max_step=1e-3, args=(popt[0], 0))
https://stackoverflow.com/questions/63823135
复制相似问题