Reputation: 22994
I'm trying
Data fitting using fmin
http://glowingpython.blogspot.ca/2011/05/curve-fitting-using-fmin.html
Which contains the following code to use fmin
:
# fitting the data with fmin
p0 = rand(3) # initial parameter value
p = fmin(e, p0, args=(x,y))
However, it is giving me the following error when I try it:
TypeErrorTraceback (most recent call last)
<ipython-input-1-41b53befd463> in <module>()
22 # fitting the data with fmin
23 p0 = rand(3) # initial parameter value
---> 24 p = fmin(e, p0, args=(x,y))
25
26 print 'estimater parameters: ', p
TypeError: 'args' is an invalid keyword to ufunc 'fmin'
When I looked at doc here, I do see the args
is a valid keyword.
UPDATE:
I was running the script as-is in Python2.7, and got the above error. Having seen Warren Weckesser's answer here is the updated script:
from pylab import *
import numpy as np
from numpy.random import normal
from scipy.optimize import fmin
%pylab inline
# parametric function, x is the independent variable
# and c are the parameters.
# it's a polynomial of degree 2
fp = lambda c, x: c[0]+c[1]*x+c[2]*x*x
real_p = rand(3)
# error function to minimize
e = lambda p, x, y: (abs((fp(p,x)-y))).sum()
# generating data with noise
n = 30
x = linspace(0,1,n)
y = fp(real_p,x) + normal(0,0.05,n)
# fitting the data with fmin
p0 = rand(3) # initial parameter value
p = fmin(e, p0, args=(x,y))
print 'estimater parameters: ', p
print 'real parameters: ', real_p
xx = linspace(0,1,n*3)
plot(x,y,'bo', xx,fp(real_p,xx),'g', xx, fp(p,xx),'r')
show()
and I'm still getting the exact same error as above.
How to fix it? Thx.
Upvotes: 1
Views: 906
Reputation: 114811
It would be easier to help you if you provided a minimal, complete and verifiable example that reproduced the problem. Without that, we have to guess.
In this case, my guess is that you are actually using numpy.fmin
, not scipy.optimize.fmin
. Add the line
from scipy.optimize import fmin
at the top of your script. And if you are doing something like
from numpy import *
(as the code at glowingpython
does), then remove that line, and either use
import numpy as np
and use the np.
prefix with all the numpy names that you use, or explicitly import only those names from numpy that you actually use, e.g.
from numpy import array, linspace # whatever you actually use
from numpy.random import rand # etc.
Using the *
form of import
is a bad practice in scripts, for exactly the reason that you have this question.
It is true, however, that something like from pylab import *
is very convenient when you are working interactively in ipython or in a jupyter notebook. To avoid the problem of fmin
being shadowed by the fmin
from numpy, you could do:
from scipy import optimize
and then call fmin
using
p = optimize.fmin(e, p0, args=(x, y))
Upvotes: 1