python - Scipiy.optimize.minimaze unconstrained error -
i want perform constrained least square methon polynom. before that, decided try unconstrined optimalization. here problem:
my polynom looks
$f(x) = ax^4 + bx^3 + cx^2 + dx + e$
so want find best coefficients a, b, c, d , e. function want minimize looks like
def lsq(args, x, y): return sum([(y[i] - (args[0]*x[i]**4 + args[1]*x[i]**3 + args[2]*x**2 + args[3]*x + args[4]))**2 in np.arange(len(x))])
where x
, y
lists of coordinates of points. thus, code may like:
import numpy np import scipy.optimize ph = np.array([8,8,8,7,7,7,7,7,7,7,7,7,6,3,2,2,2,1]) def rank2(y): return np.array([(i+1)/len(y) in range(len(y))]) x = rank2(ph) y = ph def lsq(args, x, y): return sum([(y[i] - (args[0]*x[i]**4 + args[1]*x[i]**3 + args[2]*x**2 + args[3]*x + args[4]))**2 in np.arange(len(x))]) params = scipy.optimize.minimize(nejmensi_ctverce, [1.0, 1.0, 1.0, 1.0, 1.0], args = (x, y))
but here got error:
file "c:\users\robert\desktop\winpython-64bit-3.6.1.0qt5\python- 3.6.1.amd64\lib\site-packages\scipy\optimize\optimize.py", line 628, in _approx_fprime_helper grad[k] = (f(*((xk + d,) + args)) - f0) / d[k] valueerror: setting array element sequence
can me? guess not cempletely understand how parse arguments minimize
function.
some x
s in lsq
not indexed i
:
args[0]*x[i]**4 + args[1]*x[i]**3 + args[2]*x**2 + args[3]*x + args[4] ---^ ---^
this led lsq
returning array of values instead of scalar:
in [9]: lsq([1.0, 1.0, 1.0, 1.0, 1.0], x, y) out[9]: array([ 468.00714962, 458.38490951, 448.01979096, 436.95911906, 425.25433416, 412.9609918 , 400.13876277, 386.85143307, 373.16690395, 359.15719185, 344.89842847, 330.47086072, 315.95885075, 301.45087591, 287.0395288 , 272.82151724, 258.89766428, 245.37290818])
this leads valueerror
since scipy.optimize.minimze
expects lsq
return scalar values minimized. 1 way fix problem replace bare x
s x[i]
s.
a better way solve problem replace x[i]
s x
s, remove for in np.arange(len(x))
, use numpy array-based arithmetic:
def lsq(args, x, y): return ((y - (args[0]*x**4 + args[1]*x**3 + args[2]*x**2 + args[3]*x + args[4]))**2).sum()
for example,
import numpy np import scipy.optimize optimize ph = np.array([8,8,8,7,7,7,7,7,7,7,7,7,6,3,2,2,2,1]) def rank2(y): return np.array([(i+1)/len(y) in range(len(y))]) x = rank2(ph) y = ph def lsq(args, x, y): a, b, c, d, e = args return ((y - (a*x**4 + b*x**3 + c*x**2 + d*x + e))**2).sum() params = optimize.minimize(lsq, [1.0, 1.0, 1.0, 1.0, 1.0], args = (x, y)) print(params.x)
yields
[ 94.48618936 -211.42358992 144.93063545 -37.24078798 10.23934514]
with minimum lsq
value of:
print(lsq(params.x, x, y)) # 6.91284752049
Comments
Post a Comment