将数组作为 p0 的参数传递时出现 curve_fit 错误,需要 2 个位置参数,但给出了 15 个

问题描述 投票:0回答:1

下面是在 python 中使用 SciPy 库中的 curve_fit 的示例代码。通过 curve_fit 函数传递 testLinear 的第二个参数时遇到问题。如果我将第二个参数从数组转换为解压参数,它就可以正常工作。使用数组而不是单个参数的想法是使其参数化。这样我将来如果想包含更多参数,那么我可以轻松调整系数的数量,而不用修改代码。请帮忙解决这个问题。

inputs = [[62, 15, 25, 10, 14, 7.04, 16.88, 24.48, 427219, 648745, -3.067, 3081350.0, 2], [53, 14, 32, 0, 37, 28.12, 35.94, 22.37, 403760, 516128, 0.048, 2857308.0, 2], ... ]
numP = len(inputs[0])
print("nump ",numP)
p = []
for i in range(0,int(numP)):
    p.append(column(inputs,i))
newX = np.vstack((p[0],p[1],p[2],p[3],p[4],p[5],p[6],p[7],p[8],p[9],p[10],p[11],p[12]))
#print("newX: ",newX)
def testLinear3(X,coefficients):
    p[0],p[1],p[2],p[3],p[4],p[5],p[6],p[7],p[8],p[9],p[10],p[11],p[12] = X
    c = []
    for i in range(0,len(coefficients)):
        c.append(coefficients[i])
    ret =  c[0]*p[0] + c[1]*p[1] + c[2]*p[2] + c[3]*p[3] + c[4]*p[4] + c[5]*p[5] + c[6]*p[6] + c[7]*p[7] + c[8]*p[8]+ c[9]*p[9] + c[10]*p[10] + c[11]*p[11] + c[12]*p[12] + c[13]
    return ret

#coefficients = np.array([2.0]*(13+1),dtype = float)
coefficients = [2.0]*(13+1)
popt,pcov = curve_fit(testLinear3,newX,output,coefficients)

TypeError                                 Traceback (most recent call last)
Input In \[281\], in \<cell line: 19\>()
17 #coefficients = np.array(\[2.0\]*(13+1),dtype = float)
18 coefficients = \[2.0\]*(13+1)
\---\> 19 popt,pcov = curve_fit(testLinear3,newX,output,coefficients)

483 def func_wrapped(params):
\--\> 484     return func(xdata, \*params) - ydata

TypeError: testLinear3() takes 2 positional arguments but 15 were given

如果我像下面这样编写 testLinear ,它就可以正常工作

    def testLinear2(X,c0,c1,c2,c3,c4,c5,c6,c7,c8,c9,c10,c11,c12,c13):
        p[0],p[1],p[2],p[3],p[4],p[5],p[6],p[7],p[8],p[9],p[10],p[11],p[12] = X
        ret = 0
        ret = c0 + c1*p[0] + c2*p[1] + c3*p[2] + c4*p[3] + c5*p[4] + c6*p[5] + c7*p[6] + c8*p[7]
        ret += c9*p[8]+ c10*p[9] + c11*p[10] + c12*p[11] + c13*p[12]
        return ret
python scipy curve-fitting
1个回答
0
投票

包装你的函数:

popt, pcov = curve_fit(lambda X, *coefficients: testLinear3(X, coefficients), newX, output, coefficients)

这是一个猜测,但由于你的代码不可执行,我无法测试它。请包含所有数据和导入以使您的代码运行。

© www.soinside.com 2019 - 2024. All rights reserved.