函数 model() 缺少 1 个必需的位置参数

function model() missing 1 required positional argument

我正在尝试使用 curve_fit 估计 ODE 的两个参数值 AB,然后将此 ODE 的解拟合到我的数据集,绘制结果。

我的代码:

def model(I,t,A,B):
    dIdt = A*(2000 - I) + B*(2000 - I)*(I/2000)
    return dIdt

xData = # this is an np.array of my x values
yData = # this is an np.array of my y values
plt.plot(xData, yData, 'r.-', label='experimental-data')   #This part of the code seems to work

initialGuess = [1.0,1.0]    
popt, pcov = curve_fit(model, xData, yData, initialGuess)  #This is where the error is
print(popt)
xFit = np.arange(0.0, 5.0, 0.01)
I0 = 0
t = np.linspace(0,60)
I = odeint(model,I0,t)                                     #This is where i integrate the ODE to obtain I(t).

plt.plot(xFit, I(xFit, *popt), 'r', label='fit params: a=%5.3f, b=%5.3f' % tuple(popt))
plt.xlabel('x')
plt.ylabel('y')
plt.legend()
plt.show()

我得到的错误是

model() missing 1 required positional argument: 'B'.

我大概明白是怎么回事了:我的 model() 函数在开头接受了 4 个参数:I、t、A 和 B。但是,在某处,代码只识别前 3 个参数,并且遗漏了 B。我不确定如何解决这个问题。

我尝试了一些方法:

  1. 从错误行中取出 'initialGuess',这样 curve_fit 行中就有 3 个参数,这给了我一个新的错误

Improper input: N=3 must not exceed M=1

这让我觉得 initialGuess 条目不是问题。

  1. 将错误行中的model更改为model(),这给了我错误 model() missing 4 required positional arguments: 'I', 't', 'A', and 'B'

  2. 解决这个问题,我将 model 更改为 model(I,t,A,B),最终得到 name 'A' is not defined

现在我迷路了。

所有这些错误都发生在同一行中,所以我尝试更改其中的内容,但也许我遗漏了其他内容。大多数涉及此错误的在线资源都提到必须实例化一个 class 实例,但我不确定这在这种情况下意味着什么,我没有在代码中定义 class。

我希望我已经弄清楚了我的困惑,任何指导将不胜感激。

使用 model 函数从 scipy.optimize 执行 curve_fit(参见 https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.curve_fit.html):

import matplotlib.pyplot as plt
import numpy as np
from scipy.optimize import curve_fit


def model(i, a, b):
    return a * (2_000 - i)\
           + b * (2_000 - i)\
           * (i / 2_000)


xData = np.array(range(10))
yData = model(xData, 1, 1)

initialGuess = [1.0, 1.0]

popt, pcov = curve_fit(f=model,
                       xdata=xData,
                       ydata=yData,
                       p0=initialGuess
                       )
print(popt)

Returns:

[1. 1.]

接下来,使用来自 scipy.integrateodeint 执行集成:

from scipy.integrate import odeint

xFit = np.arange(0.0, 5.0, 0.1)
I0 = 0
t = np.linspace(0, 60)
a, b = 1, 1


def model(i, t, a, b):
    return a * (2_000 - i)\
           + b * (2_000 - i)\
           * (i / 2_000)


I = odeint(model, I0, t, args=(a, b))
plt.plot(xFit, I[:, 0], 'b', label= 'fit params: a=%5.3f, b=%5.3f' % tuple(popt))
plt.xlabel('x')
plt.ylabel('y')
plt.legend()
plt.show()

揭示情节(见https://docs.scipy.org/doc/scipy/reference/generated/scipy.integrate.odeint.html):