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

2024-03-29 02:29:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图使用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'.

我大致了解发生了什么:my 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

现在我迷路了

所有这些错误都发生在同一行中,因此我尝试在其中更改内容,但可能我遗漏了其他内容。大多数涉及此错误的在线来源都提到必须实例化一个类实例,但我不确定这在本文中意味着什么,我还没有在代码中定义一个类

我希望我已经澄清了我的困惑,希望您能给予指导


Tags: of代码modelismy错误npplt
1条回答
网友
1楼 · 发布于 2024-03-29 02:29:13

使用model函数从scipy.optimize执行曲线拟合(请参见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)

返回:

[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): enter image description here

相关问题 更多 >