【问题标题】:How to fit 2 experimental data to derivative equations with scipy?如何使用 scipy 将 2 个实验数据拟合到导数方程?
【发布时间】:2022-06-10 20:44:32
【问题描述】:

我试图同时拟合 2 个实验数据,因为它有一些共享参数。这是一种化学反应,我希望得到如附图所示的配件。我已经设法使用 symfit 包来拟合我的数据,但是我需要使用 scipy/numpy 来进一步处理数据(使用蒙特卡罗模拟)我尝试使用 scipy 的代码是:

GL conversion to GM and fitting

Dataset for download

import matplotlib.pyplot as plt
import numpy as np
import scipy as sp

# Open dataset from txt file after extraction from brute data:
with open("ydata.txt", "r") as csv_file:
    ydata = np.loadtxt(csv_file, delimiter = ',')

with open("ydata2.txt", "r") as csv_file:
    ydata2 = np.loadtxt(csv_file, delimiter = ',')

xdata = np.arange(0, len(ydata))
fulldata = np.column_stack([ydata,ydata2])


# Define the equation considering the enzymatic reaction Gl -> Gm with the HP decay.
def f(C, t, k, a, b):
    GL = ydata
    GM = ydata2
    
    dGLdt = -k*GL - GL/a
    dGMdt = k*GL - GM/b
    
    return [dGLdt, dGMdt] 

guess = (1e-3, 10, 10,1 )

popt, pcov = sp.optimize.curve_fit(f, xdata, fulldata, guess)

我得到的错误是:


  File "/Users/karensantos/Desktop/Codes/Stack_question.py", line 52, in <module>
    popt, pcov = sp.optimize.curve_fit(f, xdata, fulldata, guess)

  File "/opt/anaconda3/lib/python3.8/site-packages/scipy/optimize/minpack.py", line 784, in curve_fit
    res = leastsq(func, p0, Dfun=jac, full_output=1, **kwargs)

  File "/opt/anaconda3/lib/python3.8/site-packages/scipy/optimize/minpack.py", line 410, in leastsq
    shape, dtype = _check_func('leastsq', 'func', func, x0, args, n)

  File "/opt/anaconda3/lib/python3.8/site-packages/scipy/optimize/minpack.py", line 24, in _check_func
    res = atleast_1d(thefunc(*((x0[:numinputs],) + args)))

  File "/opt/anaconda3/lib/python3.8/site-packages/scipy/optimize/minpack.py", line 484, in func_wrapped
    return func(xdata, *params) - ydata

ValueError: operands could not be broadcast together with shapes (2,98) (98,2) 

我可以使用curve_fit一次解决一个方程,但我需要一起拟合以找到所有正确的共享参数(k),因为GM依赖于GL(分别是产品和底物)。

如何使用 scipy 优化来拟合两个实验数据?

提前谢谢你,

【问题讨论】:

    标签: python scipy


    【解决方案1】:

    您可以连接一维数组中的数组以使用curve_fit 运行

    我不能运行你的例子,所以我会做一个

    import numpy as np
    from scipy.optimize import curve_fit
    def cost(x, a, b):
        return np.hstack(f(a, b, x))
    def f(a,b,x):
        return a * x**3, a**2*np.exp(-(x-b/a)**2/a)
    x = np.linspace(-2, 2)
    y1, y2 = f(4.5, 2.3, x)
    initial_guess = (1,1)
    params, _ = curve_fit(cost, x, np.hstack([y1, y2]),initial_guess)
    print(params)
    

    在这个例子中,有一个函数 f,它接受两个参数和 x 数据,我用它来计算 (y1, y2),然后我使用 curve_fit 来确定哪些参数生成了 (y1, y2)。

    【讨论】:

      猜你喜欢
      • 2021-03-26
      • 2020-06-12
      • 2023-03-28
      • 1970-01-01
      • 2019-04-07
      • 2016-01-14
      • 1970-01-01
      • 2020-04-05
      • 2013-02-12
      相关资源
      最近更新 更多