Below is the example code to use curve_fit from the SciPy library in Python. Facing issue while passing the second argument of testLinear via curve_fit function. It works fine if I convert the second argument from an array to unpacked arguments. The idea to use an array instead of individual arguments is to make it parameterized. so that in the future if I want to include more parameters then I can adjust the number of coefficients easily instead of modifying the code. Please help in resolving this issue.
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
If I write the testLinear like below it works fine
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
Wrap your function:
popt, pcov = curve_fit(lambda X, *coefficients: testLinear3(X, coefficients), newX, output, coefficients)
This is a guess, but since your code is not executable, I can't test it. Please include all data and imports to make your code run.