I need to fit function to array of data and get optimal coefficients of an equation of this function. I use curve_fit method from scipy library. It is based on least squares method.
import numpy as np
from scipy.optimize import curve_fit
#This is my function from which i need to get optimal coefficients 'a' and 'b'
def func(x, a, b):
return a*x**(b*x)
#the arrays of input data
x = [1,2,3,4,5]
y =[6,7,8,9,10]
#default (guess) coefficients
p0 = [1, 1]
popt, pcov = curve_fit(func, x, y, p0)
print popt
It returns the following error
TypeError: unsupported operand type(s) for ** or pow(): 'list' and 'list'
But when I use the other, more simple function with no power operation it works
def func(x, a, b):
return a*x + b
It must be trying to bulid number to a power of an entire array of input data
What to do? Help please...
It looks like you're after element-wise power-raising?
Like a*x[i]**(b*x[i])
for each i?
In that case, you have to use the np.power
function:
def func(x,a,b):
return a*np.power(x,b*x)
Then it works.
(As an aside, it may be worthwhile to convert x
and y
from lists to numpy arrays: np.array(x)
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With