Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python scipy: unsupported operand type(s) for ** or pow(): 'list' and 'list'

Tags:

python

scipy

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...

like image 937
Vladimir Avatar asked Feb 06 '12 06:02

Vladimir


1 Answers

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)).

like image 54
mathematical.coffee Avatar answered Nov 15 '22 16:11

mathematical.coffee