Reputation: 4098
I have the following data set
angles =np.arange(-90,91,15)
n_col_cnts =([ 0.08692008,0.46557143,0.7282595,0.89681908,0.97057961,1.,0.99488705,0.91823478,0.84187586, 0.73110934,0.53363229,0.25338418,0.01328528])
I would like to fit a gaussian to this data using optimize.leastsq()
from scipy
but have reached a stumbling block. Here is what I have attempted from here
fitfunc = lambda p, x: p[0]*math.exp(-((x-p[1])/p[2])**2) #Target function
errfunc = lambda p, x, y: fitfunc(p, x) - y # Distance to the target function
p0 = [1., 0., 30.] # Initial guess for the parameters
fit, success = optimize.leastsq(errfunc, p0[:], args=(angles,n_col_cnts))
However I get the error message
TypeError: only length-1 arrays can be converted to Python scalars
which I do not understand. What have I done wrong?
Upvotes: 3
Views: 405
Reputation: 4735
As Janne says, it needs to be able to support a large multi-dimensional 'x' as the independent variable - it's actually a matrix of them, something that took me quite a bit to find out yesterday. As a result it needs to be completely vector-ized so you have to use np.exp in order to allow the exponential of the elements of the matrix; not the matrix to a power. The parameters are allowed to take up 'm' spaces, but in the function you pass the independent variable can only take up one.
I hate to do this but someone asked a similar question yesterday and I wrote a quite in depth response if you're interested:
Curve fitting in Scipy with 3d data and parameters
Upvotes: 1
Reputation: 25197
I think fitfunc
needs to work with arrays. Change math.exp
to np.exp
Upvotes: 4