curve_fit错误:传递数组作为p0参数时期待2个位置参数,但给出了15个。
下面是一个使用Python中SciPy库的curve_fit功能的示例代码。在通过curve_fit函数传递testLinear的第二个参数时遇到了问题。如果我把第二个参数从数组转换成单独的参数,它就能正常工作。使用数组而不是单独参数的想法是为了让代码更灵活,这样将来如果我想添加更多的参数,就可以轻松调整系数的数量,而不需要修改代码。希望能帮我解决这个问题。
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from scipy.optimize import curve_fit
import sys, re, argparse, os, json
def column(matrix, i):
return [row[i] for row in matrix]
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]]
output = [50,60]
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
1 个回答
0
把你的函数包裹起来:
popt, pcov = curve_fit(lambda X, *coefficients: testLinear3(X, coefficients), newX, output, coefficients)
这只是个猜测,因为你的代码不能运行,我没法测试它。请把所有的数据和导入的内容都加上,这样我才能让你的代码运行起来。